如何解决此nullpointer异常?

时间:2015-12-19 17:19:05

标签: java android nullpointerexception

MainActivity.java

package com.example.yashpachisia.fetchjson;

import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;


public class MainActivity extends ActionBarActivity {

    String myJSON;

    private static final String TAG_RESULTS="result";
    private static final String TAG_NAME = "name";
    private static final String TAG_AGE = "age";
    private static final String TAG_SEX ="sex";

    JSONArray peoples = null;

    ArrayList<HashMap<String, String>> personList;

    ListView list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        list = (ListView) findViewById(R.id.listView);
        personList = new ArrayList<HashMap<String,String>>();
        getData();
    }


    protected void showList(){
        try {
            JSONObject jsonObj = new JSONObject(myJSON);
            peoples = jsonObj.getJSONArray(TAG_RESULTS);

            for(int i=0;i<peoples.length();i++){
                JSONObject c = peoples.getJSONObject(i);
                String name = c.getString(TAG_NAME);
                String age = c.getString(TAG_AGE);
                String sex = c.getString(TAG_SEX);

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

                persons.put(TAG_NAME,name);
                persons.put(TAG_AGE,age);
                persons.put(TAG_SEX,sex);

                personList.add(persons);
            }

            ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this, personList, R.layout.list_item,
                    new String[]{TAG_NAME,TAG_AGE,TAG_SEX},
                    new int[]{R.id.name, R.id.age, R.id.sex}
            );

            list.setAdapter(adapter);

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

    }

    public void getData(){
        class GetDataJSON extends AsyncTask<String, Void, String>{

            @Override
            protected String doInBackground(String... params) {
                DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
                HttpPost httppost = new HttpPost("http://localhost/test/form.php");

                // Depends on your web service
                httppost.setHeader("Content-type", "application/json");

                InputStream inputStream = null;
                String result = null;
                try {
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();

                    inputStream = entity.getContent();
                    // json is UTF-8 by default
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                    StringBuilder sb = new StringBuilder();

                    String line = null;
                    while ((line = reader.readLine()) != null)
                    {
                        sb.append(line + "\n");
                    }
                    result = sb.toString();
                } catch (Exception e) {
                    // Oops
                }
                finally {
                    try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
                }
                return result;
            }

            @Override
            protected void onPostExecute(String result){
                myJSON=result;
                showList();
            }
        }
        GetDataJSON g = new GetDataJSON();
        g.execute();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

   /* @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_user) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }*/
}

清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yashpachisia.fetchjson">
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Logcat窗口

12-19 17:17:59.353 5132-5132/? D/OpenGLRenderer: Enabling debug mode 0
12-19 17:17:59.353 5132-5132/? D/AndroidRuntime: Shutting down VM
12-19 17:17:59.357 5132-5132/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa6299288)
12-19 17:17:59.357 5132-5132/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 java.lang.NullPointerException
                                                     at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
                                                     at org.json.JSONTokener.nextValue(JSONTokener.java:94)
                                                     at org.json.JSONObject.<init>(JSONObject.java:154)
                                                     at org.json.JSONObject.<init>(JSONObject.java:171)
                                                     at com.example.yashpachisia.fetchjson.MainActivity.showList(MainActivity.java:56)
                                                     at com.example.yashpachisia.fetchjson.MainActivity$1GetDataJSON.onPostExecute(MainActivity.java:128)
                                                     at com.example.yashpachisia.fetchjson.MainActivity$1GetDataJSON.onPostExecute(MainActivity.java:89)
                                                     at android.os.AsyncTask.finish(AsyncTask.java:631)
                                                     at android.os.AsyncTask.access$600(AsyncTask.java:177)
                                                     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
                                                     at android.os.Handler.dispatchMessage(Handler.java:99)
                                                     at android.os.Looper.loop(Looper.java:137)
                                                     at android.app.ActivityThread.main(ActivityThread.java:4745)
                                                     at java.lang.reflect.Method.invokeNative(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:511)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
                                                     at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

只有在检查showList()中的结果不为空或空

后才调用此方法onPostExecute()
if(result != null && result.length >0 ){
  myJSON=result;
  showList()
}

由于您的myJson可能为空,因此您尝试在其上运行Json代码,因此您将获得NulPointerError

  

更新

如果您获得空值,则表示您没有从Web服务获取数据,或者您调用的是错误的。

我在你的代码中看到了一些错误,所以我给你写了一个新错误。我的代码使用commons-io-2.4.jar库,但您总是可以编写自己的代码来查看结果

 String chartString = "your url which you want to call"; 
 URL chartURL = new URL(chartString);
 HttpURLConnection chartHttpURLConnection = (HttpURLConnection) chartURL.openConnection();
 chartHttpURLConnection.connect();
 String result = IOUtils.toString(chartHttpURLConnection.getInputStream());
 System.out.println(""+result);

因为您尝试通过模拟器调用本地服务,因此IP地址将为10.0.2.2

所以你要调用的网址是

URL url = new URL(http://10.0.2.2/test/form.php);

查看此IP Address for the Emulator