尝试在空对象引用上调用虚拟方法'int java.lang.String.length()'-Android

时间:2018-07-09 13:00:18

标签: android json

我是Android新手,当我运行应用程序时遇到此错误,我一直在尝试使用PHP和MYSQL进行JSON解析。

错误:

  

致命异常:主要                     流程:com.example.admin.androidjsonparsing,PID:13399                     java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'int java.lang.String.length()'                         在org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)                         在org.json.JSONTokener.nextValue(JSONTokener.java:94)                         在org.json.JSONArray。(JSONArray.java:92)                         在org.json.JSONArray。(JSONArray.java:108)                         在com.example.admin.androidjsonparsing.MainActivity.loadIntoListView(MainActivity.java:79)                         在com.example.admin.androidjsonparsing.MainActivity.access $ 000(MainActivity.java:22)                         在com.example.admin.androidjsonparsing.MainActivity $ 1GetJSON.onPostExecute(MainActivity.java:51)                         在com.example.admin.androidjsonparsing.MainActivity $ 1GetJSON.onPostExecute(MainActivity.java:38)                         在android.os.AsyncTask.finish(AsyncTask.java:695)                         在android.os.AsyncTask.access $ 600(AsyncTask.java:180)                         在android.os.AsyncTask $ InternalHandler.handleMessage(AsyncTask.java:712)                         在android.os.Handler.dispatchMessage(Handler.java:106)                         在android.os.Looper.loop(Looper.java:193)                         在android.app.ActivityThread.main(ActivityThread.java:6669)                         在java.lang.reflect.Method.invoke(本机方法)                         在com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run(RuntimeInit.java:493)                         在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

以下是代码

MainActivity.java

package com.example.admin.androidjsonparsing;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

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

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

ListView listView;

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

    listView = (ListView) findViewById(R.id.listView);
    getJSON("http://192.168.1.4/AndroidJSONParsing/getdata.php");
}


private void getJSON(final String urlWebService) {

    class GetJSON extends AsyncTask<Void, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }


        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
            try {
                loadIntoListView(s);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        protected String doInBackground(Void... voids) {
            try {
                URL url = new URL(urlWebService);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                StringBuilder sb = new StringBuilder();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String json;
                while ((json = bufferedReader.readLine()) != null) {
                    sb.append(json + "\n");
                }
                return sb.toString().trim();
            } catch (Exception e) {
                return null;
            }
        }
    }
    GetJSON getJSON = new GetJSON();
    getJSON.execute();
}

private void loadIntoListView(String json) throws JSONException {
    JSONArray jsonArray = new JSONArray(json);
    String[] heroes = new String[jsonArray.length()];
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject obj = jsonArray.getJSONObject(i);
        heroes[i] = obj.getString("name");
    }
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, heroes);
    listView.setAdapter(arrayAdapter);
}

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.admin.androidjsonparsing.MainActivity">


<!-- this is our listview where we will display the fetched data -->
<ListView
    android:id="@+id/listView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true" />

</RelativeLayout>

4 个答案:

答案 0 :(得分:2)

检查空字符串。

       @Override
       protected void onPostExecute(String s) {
       super.onPostExecute(s);
       if(s!=null){

        Toast.makeText(getApplicationContext(),s,Toast.LENGTH_SHORT).show();
                try {
                      loadIntoListView(s);
                    } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
    }

答案 1 :(得分:0)

尝试此代码...

    @Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    if (!TextUtils.isEmpty(s) && s!=null) {
        Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
        try {
            loadIntoListView(s);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

答案 2 :(得分:0)

出现此问题是因为您的String json不是有效的json,可能是因为它是nullbad formated json,然后尝试如下操作:

第1步。

if (s!=null && !TextUtils.isEmpty(s)) loadIntoListView(s);

第2步。

private void loadIntoListView(String json) throws JSONException {
    JSONArray jsonArray = new JSONArray(json);
    try {
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject obj = jsonArray.getJSONObject(i);
            heroes[i] = obj.getString("name");
        }
    } catch(JSONException e) {
        //handler json exception
    }
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, heroes);
    listView.setAdapter(arrayAdapter);
}

答案 3 :(得分:0)

如果URI为null或未按以下示例设置那样,也会引发此错误(而不是意外)

        URL url = new URL(xml_file);
        URLConnection conn = url.openConnection();

如果xml_file为空(未设置),则会在第二行引发错误。确保它具有有效值。您可以使用Log.e("App", "XML File is " + xml_file);来检查日志中的值