我正在关注这个问题Using JSON File in Android App Resources尝试访问我的JSON文件并将其作为参数传递给我的fromJSON调用,但是我在mobileArray初始化时获得了一个NPE,因为jsonString的值仍为null。这里发生了什么? 我的问题不是NPE本身,而是我的价值没有被初始化。
编辑:尝试传递InputStreamReader但它仍然崩溃,更新代码并添加了logcat
Event[] myArray;
Gson gson = new Gson();
InputStream is = getResources().openRawResource(R.raw.myJSON);
InputStreamReader isReader = new InputStreamReader(is);
myArray = gson.fromJson(isReader, Event[].class);
Logcat:
Caused by: java.lang.NullPointerException
at com.example.test.testassigment.Event.setDayOfTheWeek(Event.java:36)
at com.example.test.testassigment.Event.<init>(Event.java:21)
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
at com.google.gson.internal.ConstructorConstructor$3.construct(ConstructorConstructor.java:108)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:210)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:41)
at com.google.gson.internal.bind.ArrayTypeAdapter.read(ArrayTypeAdapter.java:72)
at com.google.gson.Gson.fromJson(Gson.java:887)
at com.google.gson.Gson.fromJson(Gson.java:825)
at com.example.test.testassigment.MainActivity.onCreate(MainActivity.java:70)
at android.app.Activity.performCreate(Activity.java:4486)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1052)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1931)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
at android.app.ActivityThread.access$600(ActivityThread.java:127)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4511)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)