Android从本地文件获取JSON

时间:2018-10-11 14:06:45

标签: android json listview android-json

我正在尝试从本地存储在应用程序中的文件中获取JSON信息。我的代码收到以下错误,我想知道是否有人能够提供任何解决方法。我还将附上错误和代码。

  

10-11 15:02:27.277 9184-9209 / info.androidhive.jsonparsing   E / AndroidRuntime:致命异常:AsyncTask#1       流程:info.androidhive.jsonparsing,PID:9184       java.lang.RuntimeException:执行doInBackground()时发生错误           在android.os.AsyncTask $ 3.done(AsyncTask.java:354)           在java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)           在java.util.concurrent.FutureTask.setException(FutureTask.java:252)           在java.util.concurrent.FutureTask.run(FutureTask.java:271)           在android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:245)           在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)           在java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:641)           在java.lang.Thread.run(Thread.java:764)        原因:java.lang.NullPointerException:尝试调用虚拟方法'org.json.JSONArray   空对象上的org.json.JSONObject.getJSONArray(java.lang.String)'   参考           在info.androidhive.jsonparsing.MainActivity $ GetContacts.doInBackground(MainActivity.java:101)           在info.androidhive.jsonparsing.MainActivity $ GetContacts.doInBackground(MainActivity.java:52)           在android.os.AsyncTask $ 2.call(AsyncTask.java:333)           在java.util.concurrent.FutureTask.run(FutureTask.java:266)           在android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:245)           在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)           在java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:641)           在java.lang.Thread.run(Thread.java:764)10-11 15:02:27.289 9184-9209 / info.androidhive.json分析I / Process:发送信号。 PID:   9184 SIG:9

public class MainActivity extends AppCompatActivity {

    private String TAG = MainActivity.class.getSimpleName();

    private ProgressDialog pDialog;
    private ListView lv;
    ArrayList<HashMap<String, String>> contactList;

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

        contactList = new ArrayList<>();

        lv = (ListView) findViewById(R.id.list);
        GetContacts task = new GetContacts(this.getApplicationContext());
        task.execute();
    }

    /**
     * Async task class to get json by making HTTP call
     */
    private class GetContacts extends AsyncTask<Void, Void, Void> {

        private Context mContext;

        public GetContacts (Context context){
            mContext = context;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            //pDialog = new ProgressDialog(MainActivity.this);
            //pDialog.setMessage("Please wait...");
           // pDialog.setCancelable(false);
           // pDialog.show();

        }
        private JSONObject loadJSONFromAsset() {
            String inFile = "test.json";
            JSONObject assetJson = null;
            try {
                InputStream stream = mContext.getAssets().open(inFile);
                int size = stream.available();
                byte[] buffer = new byte[size];
                stream.read(buffer);
                stream.close();
                String assetString = new String(buffer);
                assetJson = new JSONObject(assetString);
            } catch (IOException e) {
                // Handle IO exceptions here
            } catch (JSONException e) {
                // Handle JSON exceptions here
            }
            return assetJson;


        }
        @Override
        protected Void doInBackground(Void... arg0) {
                try {
                    JSONObject jsonObj = loadJSONFromAsset();

                    JSONArray contacts = jsonObj.getJSONArray("contacts");

                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);

                        String id = c.getString("id");
                        String name = c.getString("name");
                        String email = c.getString("email");
                        String address = c.getString("address");
                        String gender = c.getString("gender");

                        JSONObject phone = c.getJSONObject("phone");
                        String mobile = phone.getString("mobile");
                        String home = phone.getString("home");
                        String office = phone.getString("office");

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

                        contact.put("id", id);
                        contact.put("name", name);
                        contact.put("email", email);
                        contact.put("mobile", mobile);

                        contactList.add(contact);
                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }


            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            if (pDialog.isShowing())
                pDialog.dismiss();

            ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this, contactList,
                    R.layout.list_item, new String[]{"name", "email",
                    "mobile"}, new int[]{R.id.name,
                    R.id.email, R.id.mobile});

            lv.setAdapter(adapter);
        }

    }
}

0 个答案:

没有答案