【问题标题】:Android getAssets() NullPointerException loading Json file from assetsAndroid getAssets() NullPointerException 从资产加载 Json 文件
【发布时间】:2014-07-08 11:42:38
【问题描述】:

我正在尝试从 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;

    }

我在其他类上使用此方法,我只在列表视图中显示 json 数据(即使在 getAssets() 之前没有提供上下文),但是这次我不能让它工作。

LogCat:

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;
    }

}

【问题讨论】:

  • 你调用 getIntent() 并且你有一个方法 getIntent(Context) 将上下文作为参数。
  • 堆栈跟踪表明ChartTeste 是用new 实例化的。永远不要使用new 实例化活动。
  • 所以我应该把它改成 getIntent(this) 吗?原谅我的无知我是android新手
  • @laalto 问题已解决。我把它改成了Intent myIntent = new Intent(MainActivity.this, ChartTeste.class); startActivity(myIntent);
  • 它没有显示我的图表,但至少 nullpointerexception 消失了,谢谢 :)

标签: android json nullpointerexception android-context


【解决方案1】:

试试这个,

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;

    }

这可能对你有帮助

【讨论】:

  • 还是一样,变量“ficheiro”就是文件名。
  • 但你必须定义文件扩展名(如.txt、.json)
  • 这就是我现在的 InputStream is = getApplicationContext().getAssets().open("getCentrais_JSON.json");
  • 活动的 oncreate 方法在哪里?
  • 如果您在其他类中使用此方法,则必须传递您使用此方法的类的上下文
【解决方案2】:
this 

引用当前对象,我认为你应该使用

getApplicationContext() 

【讨论】:

  • 我已经尝试过了,但它仍然给我同样的错误
【解决方案3】:

堆栈跟踪表明ChartTeste 是用new 实例化的。永远不要使用new 实例化活动。

要么考虑你是否需要另一个活动,或者使用Intent 来实例化一个,例如

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

【讨论】:

  • 太棒了..你是如何找到用 new 实例化的操作的。上下文为空。创建活动后,上下文就可用。 new 上下文为空..
  • @Raghunandan 异常来自 null basecontext,即活动未正确初始化,最有可能做到这一点的方法是使用 new 实例化活动。在堆栈跟踪中看到一个活动直接调用另一个活动也很糟糕。
  • 太糟糕了,我还不能投票,谢谢大家的帮助:)
  • @laalto 你太棒了!
猜你喜欢
  • 2014-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-19
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多