2014-05-20 35 views
0

我試圖從json文件中獲取數據,以便稍後可以使用它與aChartEngine。這是我使用的得到這個數據的方法:Android getAssets()NullPointerException從資產中加載Json文件

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之前提供上下文( )),但是這次我不能得到這個工作。

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

} 
+0

你調用'getIntent()'並且你有一個'getIntent(Context)'方法將上下文作爲參數。 – Raghunandan

+0

stacktrace表明'ChartTeste'是用'new'實例化的。永遠不要用'new'實例化活動。 – laalto

+0

所以我應該將其更改爲getIntent(this)?原諒我我的無知我是新手機android – MadTyrael

回答

2

堆棧跟蹤表明,ChartTeste進行實例化new。千萬不要用new實例化活動。

要麼考慮您是否需要其他活動,要麼使用Intent來實例化一個活動,例如,

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

真棒..你是否發現操作實例化與新。上下文爲空。一旦創建活動,上下文就可用。 'new'上下文爲null .. – Raghunandan

+0

@Raghunandan異常來自null basecontext,即活動未正確初始化,並且最有可能的方式是使用'new'來實例化活動。直接在堆棧跟蹤中看到一個活動會調用另一個活動也會產生不良影響。 – laalto

+0

好的。得到它了。謝謝。我應該意識到.. – Raghunandan

0

試試這個,

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; 

    } 

這可能會幫助你

+0

仍然是同樣的東西,變量「ficheiro」是文件名。 – MadTyrael

+0

但你必須定義文件擴展名(如.txt,.json) –

+0

這就是我現在的 InputStream is = getApplicationContext()。getAssets()。open(「getCentrais_JSON.json」); – MadTyrael

0
this 

指當前對象,在我看來,你應該使用

getApplicationContext() 
+0

我已經嘗試過,但它仍然給我同樣的錯誤 – MadTyrael

相關問題