用于解析本地JSON文件的AssetManager返回NullPointer

时间:2018-01-10 10:14:42

标签: java android json

我有很多关于它的主题和问题,但无法找到任何解决方案。我也是Android和Java的新手。

我尝试做的是解析我的本地JSON文件并设置适配器以在ListView中查看我的字符串。不应该太复杂,但我收到了这个错误:

01-10 10:04:38.109 29962-29962/com.thkoeln.stucked E/AndroidRuntime: FATAL EXCEPTION: main
                                                                 Process: com.thkoeln.stucked, PID: 29962
                                                                 java.lang.RuntimeException: Unable to start activity ComponentInfo{com../com...MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.AssetManager android.content.Context.getAssets()' on a null object reference
                                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                     at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                     at android.os.Looper.loop(Looper.java:148)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.AssetManager android.content.Context.getAssets()' on a null object reference
                                                                     at android.content.ContextWrapper.getAssets(ContextWrapper.java:81)
                                                                     at com.thkoeln.stucked.JSONParser.loadJSONFromAsset(JSONParser.java:28)
                                                                     at com.thkoeln.stucked.JSONParser.parseJson(JSONParser.java:52)
                                                                     at com.thkoeln.stucked.MainActivity.onCreate(MainActivity.java:24)
                                                                     at android.app.Activity.performCreate(Activity.java:6237)
                                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
                                                                     at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                                                                     at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                     at android.os.Looper.loop(Looper.java:148) 
                                                                     at android.app.ActivityThread.main(ActivityThread.java:5417) 
                                                                     at java.lang.reflect.Method.invoke(Native Method) 
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

这是我的MainActivity.java:

package com.thkoeln.stucked;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;

public class MainActivity extends AppCompatActivity {

ListView activityList;


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    activityList = (ListView) findViewById(R.id.activityList);

    String fromArray[] = {"uid", "uname", "ustart"};
    int to[] = {R.id.uid, R.id.uname, R.id.ustart};

    JSONParser jp = new JSONParser();
    jp.parseJson();
    /*ListAdapter adapter = new SimpleAdapter(this, jp.userList, R.layout.user_item, fromArray, to);
    activityList.setAdapter(adapter);*/

    }


}

这是我的JSONParser.java:

package com.thkoeln.stucked;

import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;


public class JSONParser extends AppCompatActivity {

ArrayList<HashMap<String, String>> userList;

public String loadJSONFromAsset() {
    String json = null;
    try {
        InputStream is = getAssets().open("users.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 json;

}

public JSONObject parseJson() {

    //ArrayList<HashMap<String, String>> userList
    try {

        JSONObject reader = new 
       JSONObject(String.valueOf(loadJSONFromAsset()));

        JSONArray users = reader.getJSONArray("users");
        Log.d("AnzahlUser", String.valueOf(users.length()));

        for (int i = 0; i < users.length(); i++) {
            JSONObject u = users.getJSONObject(i);
            Log.d("Details-->", u.toString());
            String uid = u.getString("uid");
            String uname = u.getString("uname");
            String ustart = u.getString("ustart");
            //String uend = u.getString("u.end");

            HashMap<String, String> user = new HashMap<>();

            user.put("uid", uid);
            user.put("uname", uname);
            user.put("ustart", ustart);
            //user.put("u.end", uend);

            userList.add(user);




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

    return null;
    }
}

如果有人可以帮助我,我会非常感激...

1 个答案:

答案 0 :(得分:-1)

您不应将AppCompatActivity扩展为上下文。您应该将上下文传递给JSONParser类以获取资产。

如果活动附加到Android生命周期,您只能获取活动的上下文。

您的JSONParser应该是这样的。

public class JSONParser{
private Context context;

public JSONParser(Context context){
   this.context =  context;
}

ArrayList<HashMap<String, String>> userList;

public String loadJSONFromAsset() {
    String json = null;
    try {
        InputStream is = context.getAssets().open("users.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 json;

}

public JSONObject parseJson() {

    //ArrayList<HashMap<String, String>> userList
    try {

        JSONObject reader = new 
       JSONObject(String.valueOf(loadJSONFromAsset()));

        JSONArray users = reader.getJSONArray("users");
        Log.d("AnzahlUser", String.valueOf(users.length()));

        for (int i = 0; i < users.length(); i++) {
            JSONObject u = users.getJSONObject(i);
            Log.d("Details-->", u.toString());
            String uid = u.getString("uid");
            String uname = u.getString("uname");
            String ustart = u.getString("ustart");
            //String uend = u.getString("u.end");

            HashMap<String, String> user = new HashMap<>();

            user.put("uid", uid);
            user.put("uname", uname);
            user.put("ustart", ustart);
            //user.put("u.end", uend);

            userList.add(user);




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

    return null;
    }
}

您的MainActivity应该是这样的。

public class MainActivity extends AppCompatActivity {

ListView activityList;


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    activityList = (ListView) findViewById(R.id.activityList);

    String fromArray[] = {"uid", "uname", "ustart"};
    int to[] = {R.id.uid, R.id.uname, R.id.ustart};

    JSONParser jp = new JSONParser(this);
    jp.parseJson();
    /*ListAdapter adapter = new SimpleAdapter(this, jp.userList, R.layout.user_item, fromArray, to);
    activityList.setAdapter(adapter);*/

    }


}