Android getAssets()NullPointerException从资产加载Json文件

Android getAssets()NullPointerException从资产加载Json文件,android,json,nullpointerexception,android-context,Android,Json,Nullpointerexception,Android Context,我试图从一个json文件中获取数据,以便稍后在aChartEngine中使用它。这是我用来获取这些数据的方法: public String loadJSONFromAsset() { String json = null; try { InputStream is = this.getAssets().open(ficheiro); int size = is.available();

我试图从一个json文件中获取数据,以便稍后在aChartEngine中使用它。这是我用来获取这些数据的方法:

public String loadJSONFromAsset() {
        String json = null;


        try {



            InputStream is = this.getAssets().open(ficheiro);

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;

    }
我在其他类上使用此方法,在这些类中,我只在listview中显示json数据(即使没有在getAssets()之前提供上下文),但是这次我无法使用此方法

日志:

05-20 10:26:14.108: E/AndroidRuntime(6388): FATAL EXCEPTION: main
05-20 10:26:14.108: E/AndroidRuntime(6388): Process: com.example.euroxxi_testeficheiro, PID: 6388
05-20 10:26:14.108: E/AndroidRuntime(6388): java.lang.IllegalStateException: Could not execute method of the activity
05-20 10:26:14.108: E/AndroidRuntime(6388):     at android.view.View$1.onClick(View.java:3969)
05-20 10:26:14.108: E/AndroidRuntime(6388):     at android.view.View.performClick(View.java:4633)
05-20 10:26:14.108: E/AndroidRuntime(6388):     at android.view.View$PerformClick.run(View.java:19330)
05-20 10:26:14.108: E/AndroidRuntime(6388):     at android.os.Handler.handleCallback(Handler.java:733)
05-20 10:26:14.108: E/AndroidRuntime(6388):     at android.os.Handler.dispatchMessage(Handler.java:95)
05-20 10:26:14.108: E/AndroidRuntime(6388):     at android.os.Looper.loop(Looper.java:157)
05-20 10:26:14.108: E/AndroidRuntime(6388):     at android.app.ActivityThread.main(ActivityThread.java:5356)
05-20 10:26:14.108: E/AndroidRuntime(6388):     at java.lang.reflect.Method.invokeNative(Native Method)
05-20 10:26:14.108: E/AndroidRuntime(6388):     at java.lang.reflect.Method.invoke(Method.java:515)
05-20 10:26:14.108: E/AndroidRuntime(6388):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
05-20 10:26:14.108: E/AndroidRuntime(6388):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
05-20 10:26:14.108: E/AndroidRuntime(6388):     at dalvik.system.NativeStart.main(Native Method)
05-20 10:26:14.108: E/AndroidRuntime(6388): Caused by: java.lang.reflect.InvocationTargetException
05-20 10:26:14.108: E/AndroidRuntime(6388):     at java.lang.reflect.Method.invokeNative(Native Method)
05-20 10:26:14.108: E/AndroidRuntime(6388):     at java.lang.reflect.Method.invoke(Method.java:515)
05-20 10:26:14.108: E/AndroidRuntime(6388):     at android.view.View$1.onClick(View.java:3964)
05-20 10:26:14.108: E/AndroidRuntime(6388):     ... 11 more
05-20 10:26:14.108: E/AndroidRuntime(6388): Caused by: java.lang.NullPointerException
05-20 10:26:14.108: E/AndroidRuntime(6388):     at android.content.ContextWrapper.getAssets(ContextWrapper.java:88)
05-20 10:26:14.108: E/AndroidRuntime(6388):     at com.example.euroxxi_testeficheiro.ChartTeste.loadJSONFromAsset(ChartTeste.java:53)
05-20 10:26:14.108: E/AndroidRuntime(6388):     at com.example.euroxxi_testeficheiro.ChartTeste.getIntent(ChartTeste.java:91)
05-20 10:26:14.108: E/AndroidRuntime(6388):     at com.example.euroxxi_testeficheiro.MainActivity.ChartPlot(MainActivity.java:77)
05-20 10:26:14.108: E/AndroidRuntime(6388):     ... 14 more
这是全部活动

 package com.example.euroxxi_testeficheiro;


import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import org.achartengine.ChartFactory;
import org.achartengine.chart.BarChart.Type;
import org.achartengine.model.CategorySeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.jjoe64.graphview.BarGraphView;
import com.jjoe64.graphview.GraphViewSeries;
import com.jjoe64.graphview.GraphView.GraphViewData;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;

public class ChartTeste extends Activity{

    private static final String TAG_CENTRAL = "getCentrais_JSONResult";
    private static final String TAG_NOME = "Central";
    private static final String TAG_DATA = "Data";
    private static final String TAG_PRODUCAO = "Producao";
    String ficheiro = "getCentrais_JSON.json";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chart_teste);

        getIntent();

    }

    public String loadJSONFromAsset() {
        String json = null;


        try {



            InputStream is = getApplicationContext().getAssets().open("getCentrais_JSON.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;

    }



    public Intent getIntent(Context context) 
    {   

        XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
        XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();

        try {

            String nome; 
            int producao; 


            // contacts JSONArray
            JSONArray centrais = null;

            JSONObject jsonObj = new JSONObject(loadJSONFromAsset());


            // Getting JSON Array node
            centrais = jsonObj.getJSONArray(TAG_CENTRAL);

            int[] y={0};
            String[] xLabel = {""};

            // looping through All Contacts
            for (int i = 0; i < centrais.length(); i++) {
                JSONObject c = centrais.getJSONObject(i);

                //String id = c.getString(TAG_ID);
                nome = c.getString(TAG_NOME); 
                producao = c.getInt(TAG_PRODUCAO);


                xLabel[i]=nome;
                y[i]=producao;

                mRenderer.addXTextLabel(y[i], xLabel[i]);
            }  

             // Bar 1

                CategorySeries series = new CategorySeries("Grafico de producao");
                for (int j = 0; j < y.length; j++) {
                    series.add("Bar " + (j+1), y[j]);


                }


                dataset.addSeries(series.toXYSeries());

                // This is how the "Graph" itself will look like
                mRenderer.setChartTitle("Gráfico de produção");
                mRenderer.setXTitle("X VALUES");
                mRenderer.setYTitle("Y VALUES");


                mRenderer.setXLabels(0);


                mRenderer.setAxesColor(Color.GREEN);
                mRenderer.setLabelsColor(Color.RED);

                // Customize bar 1
                XYSeriesRenderer renderer = new XYSeriesRenderer();
                renderer.setDisplayChartValues(true);
                renderer.setChartValuesSpacing((float) 0.5);
                mRenderer.addSeriesRenderer(renderer);
              //renderer.setChartTitleTextSize(titleSize);  // if we change title text size, it will render off screen
                mRenderer.setLabelsTextSize(25);
                mRenderer.setLegendTextSize(25);



        } catch (JSONException e) {
            e.printStackTrace();
        }

        Intent intent = ChartFactory.getBarChartIntent(context, dataset,mRenderer, Type.DEFAULT);

        return intent;
    }

}
package com.example.euroxxi_testeficheiro;
导入java.io.IOException;
导入java.io.InputStream;
导入java.text.simpleDataFormat;
导入java.util.ArrayList;
导入java.util.Calendar;
导入java.util.Date;
导入java.util.HashMap;
导入org.achartengine.ChartFactory;
导入org.achartengine.chart.BarChart.Type;
导入org.achartengine.model.CategorySeries;
导入org.achartengine.model.xymultiplesseriesdataset;
导入org.achartengine.renderer.XYMultipleSeriesRenderer;
导入org.achartengine.renderer.XYSeriesRenderer;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入com.jjoe64.graphview.BarGraphView;
导入com.jjoe64.graphview.GraphViewSeries;
导入com.jjoe64.graphview.graphview.graphview数据;
导入android.app.Activity;
导入android.content.Context;
导入android.content.Intent;
导入android.graphics.Color;
导入android.os.Bundle;
导入android.util.DisplayMetrics;
导入android.util.TypedValue;
导入android.widget.EditText;
导入android.widget.LinearLayout;
导入android.widget.ListView;
公共类ChartTeste扩展活动{
私有静态最终字符串标记_CENTRAL=“getcentralis_JSONResult”;
私有静态最终字符串标记_NOME=“Central”;
私有静态最终字符串标记_DATA=“DATA”;
私有静态最终字符串标记_PRODUCAO=“PRODUCAO”;
字符串ficheiro=“getCentrais_JSON.JSON”;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u chart\u teste);
getIntent();
}
公共字符串loadJSONFromAsset(){
字符串json=null;
试一试{
InputStream is=getApplicationContext().getAssets().open(“getCentrais_JSON.JSON”);
int size=is.available();
字节[]缓冲区=新字节[大小];
is.read(缓冲区);
is.close();
json=新字符串(缓冲区,“UTF-8”);
}捕获(IOEX异常){
例如printStackTrace();
返回null;
}
返回json;
}
公共意图getIntent(上下文)
{   
XYmultiplesseriesdataset数据集=新的XYmultiplesseriesdataset();
XYmultiplesseriesrender mrender=新的XYmultiplesseriesrender();
试一试{
字符串名称;
int producao;
//联系JSONArray
JSONArray centrais=null;
JSONObject jsonObj=新的JSONObject(loadJSONFromAsset());
//获取JSON数组节点
centrais=jsonObj.getJSONArray(TAG_CENTRAL);
int[]y={0};
字符串[]xLabel={”“};
//通过所有触点循环
对于(int i=0;i
试试这个

public String loadJSONFromAsset() {
        String json = null;
        try {

            InputStream is = getAssets().open("file_name.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;

    }
这可能对你有帮助

this 
参考当前对象,我认为您应该使用

getApplicationContext() 

stacktrace建议将
ChartTeste
实例化为
new
。切勿使用
新建
实例化活动

要么考虑是否需要另一个活动,要么使用<代码>意图<代码>实例化一个,例如

Intent i = new Intent(MainActivity.this, ChartTeste.class);
startActivity(i);

同样,变量“ficheiro”是文件名。但是您必须定义文件扩展名(如.txt、.json),这就是我现在输入的InputStream is=getApplicationContext().getAssets().open(“getCentrais_json.json”);活动的oncreate方法在哪里?如果您在其他类中使用此方法,则必须传递使用此方法的类的上下文,我已尝试过此方法,但它仍然给我相同的错误,您调用
getIntent()
,并且您有一个方法
getIntent(context)
将上下文作为参数。stacktrace建议用
new
实例化
ChartTeste
。切勿使用
new