Java 如何解决此空指针异常?

Java 如何解决此空指针异常?,java,android,nullpointerexception,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.ListA

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);
    }*/
}
package com.example.yashpachisia.fetchjson;
导入android.os.AsyncTask;
导入android.support.v7.app.ActionBarActivity;
导入android.os.Bundle;
导入android.view.Menu;
导入android.view.MenuItem;
导入android.widget.ListAdapter;
导入android.widget.ListView;
导入android.widget.simpledapter;
导入android.widget.TextView;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.params.BasicHttpParams;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入java.io.BufferedReader;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.util.ArrayList;
导入java.util.HashMap;
公共类MainActivity扩展了ActionBarActivity{
字符串myJSON;
私有静态最终字符串标记_RESULTS=“result”;
私有静态最终字符串标记_NAME=“NAME”;
私有静态最终字符串标记_AGE=“AGE”;
私有静态最终字符串标记_SEX=“SEX”;
JSONArray-peoples=null;
ArrayList个人主义者;
列表视图列表;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list=(ListView)findViewById(R.id.ListView);
personList=新的ArrayList();
getData();
}
受保护的无效显示列表(){
试一试{
JSONObject jsonObj=新的JSONObject(myJSON);
peoples=jsonObj.getJSONArray(标记结果);

对于(int i=0;i只有在检查您在
onPostExecute()
中得到的结果不为null或空后,才能调用此方法
showList()

if(result != null && result.length >0 ){
  myJSON=result;
  showList()
}
由于myJson可能为空,因此您正在尝试在其上运行
Json
code,因此会得到
numpointererror

更新

如果您得到的是空值,这意味着您没有从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);
当您试图通过emulator调用本地服务时,IP地址将为
10.0.2.2

所以你要调用的URL是

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

请看一看这个

其中的行抛出NullPointException我不知道是什么导致了这段代码中的异常。while((line=reader.readLine())!=null){sb.append(line+“\n”);}result=sb.toString();}catch(异常e){//Oops}最后{try{if(inputStream!=null)inputStream.close();}catch(Exception squish){}返回结果;您能为我们显示JSON响应吗?或者告诉witch line是ShowList()方法中的56行吗。但看起来您试图访问JSON中不存在的内容。请在“myJSON=result”行上设置断点,并检查结果是否包含有效的JSON。如果是,请在“JSONObject JSONObject=new JSONObject(myJSON);”行上设置断点再次检查JSON是否良好。然后你可能会知道更多。谢谢你的回复。我设置了条件,我的JSON似乎返回空值。你能告诉我为什么吗?这是我页面输出的屏幕截图。@Taurus,问题在于你得到的数据,JSON数据应该包含在[]中表示JSON数组或数据应在{}表示JSON对象,您必须确保删除在php中响应的表单file@Taurus,代码中的另一个问题是您正在进行的API调用。我已更新了答案,以便您可以查看。如果您可以从web浏览器中获取API的结果,则表示这是一个get请求,而不是帖子
 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);
URL url = new URL(http://10.0.2.2/test/form.php);