尝试使用Async任务获取json时的java.lang.NullPointerException

时间:2015-05-13 07:40:48

标签: java android json android-activity http-get

当我点击按钮时,我试图从Url获​​取json,但是获取空指针异常并且遗憾的是应用程序停止这是我的onCreate方法。

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    autoCompView = (AutoCompleteTextView)findViewById(R.id.autocomplete_current);

 findViewById(R.id.shortestButton).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            getUrl();//calling getUrl method for getting Url
        }
    });

这是我的getUrl方法,用于创建url并从该url获取json。

private void getUrl() {
    String result = null;
    String dest1 = list.get(0);
    String dest2 = list.get(1);
    String dest3 = list.get(2);
    String start = getAddress();

        String urls = "https://maps.googleapis.com/maps/api/distancematrix/json?";
        try {
            encodedString = urls + "origins="
                    + URLEncoder.encode(start, "utf8")+"|"
                    + URLEncoder.encode(dest1, "utf8")+"|"
                    + URLEncoder.encode(dest2, "utf8")+"|"
                    + URLEncoder.encode(dest3, "utf8")
                    +"&destinations="
                    + URLEncoder.encode(dest1, "utf8")+"|"
                    + URLEncoder.encode(dest2, "utf8")+"|"
                    + URLEncoder.encode(dest3, "utf8")+"|"
                    + URLEncoder.encode(start, "utf8")
                    +"&mode=driving"
                    +"&language = en-En"
                    +"&key="+API_KEY;
            encodedString = encodedString.replaceAll("%2C","+");
            encodedString = encodedString.replaceAll("\\++", "+");

        }  

private class ConnectToUrlTask extends AsyncTask<String,Void,String> {

    @Override
    protected String doInBackground(String... uRl) {
        String data = "";

            HttpConnections httpConnections = new HttpConnections();
        try {
            data = httpConnections.readUrl(uRl[0]);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return data;
    }

    @Override
    protected void onPostExecute(String s) {
      new UrlTasks().execute(s);
    }
}
private class UrlTasks extends AsyncTask<String,Void,String> {

    @Override
    protected String doInBackground(String... params) {
        String distance = null;
        JSONObject jobj = null;

        try {
            jobj = new JSONObject(params[0]);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            JSONArray jsonArray = jobj.getJSONArray("rows");
          // Log.d("jsonArray", String.valueOf(jsonArray));
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject object = jsonArray.getJSONObject(i);
                JSONArray ja2 = object.getJSONArray("elements");
                for (int j = 0; j < ja2.length(); j++) {
                    JSONObject object3 = ja2.getJSONObject(j);
                    distance = object3.getJSONObject("distance").getString("text");
                }
            }
           //Log.d("jsonArray", String.valueOf(jsonArray));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return distance;
    }

    @Override
    protected void onPostExecute(String s) {
        Log.d("St*",s);
    }
}

这是我的错误日志。

 java.lang.RuntimeException: An error occured while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:299)
        at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
        at java.util.concurrent.FutureTask.run(FutureTask.java:137)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
        at java.lang.Thread.run(Thread.java:838)
 Caused by: java.lang.NullPointerException
        at com.example.wm.shortestpathdemo.MainActivity$UrlTasks.doInBackground(MainActivity.java:359)
        at com.example.wm.shortestpathdemo.MainActivity$UrlTasks.doInBackground(MainActivity.java:346)
        at android.os.AsyncTask$2.call(AsyncTask.java:287)

1 个答案:

答案 0 :(得分:0)

我在创建网址时犯了错误。在getUrl()方法中:

private void getUrl() {
String result = null;
String dest1 = list.get(0);
String dest2 = list.get(1);
String dest3 = list.get(2);
String start = getAddress();

    String urls = "https://maps.googleapis.com/maps/api/distancematrix/json?";
    try {
        encodedString = urls + "origins="
                + URLEncoder.encode(start, "utf8")+"|"
                + URLEncoder.encode(dest1, "utf8")+"|"
                + URLEncoder.encode(dest2, "utf8")+"|"
                + URLEncoder.encode(dest3, "utf8")
                +"&destinations="
                + URLEncoder.encode(dest1, "utf8")+"|"
                + URLEncoder.encode(dest2, "utf8")+"|"
                + URLEncoder.encode(dest3, "utf8")+"|"
                + URLEncoder.encode(start, "utf8")
                +"&mode=driving"
              // this is the mistake 
                +"&language = en-En"  
              //correct form is
                +"&language = en"
                +"&key="+API_KEY;
        encodedString = encodedString.replaceAll("%2C","+");
        encodedString = encodedString.replaceAll("\\++", "+");

    }