点击时出现Android错误/崩溃

时间:2013-08-21 16:56:15

标签: java android json

我正在尝试做一些简单的JSON解析来从URL获取数据,并在屏幕上更改一些值。但是,当前,当单击按钮并最终崩溃时,应用程序会锁定。我从

中提取数据

http://dev4.vcsonline.com/deding/vpmi_mobile/WebAPI/WebAPI/api/address

onclick监听器和异步任务:

    Pull_Data = (Button) findViewById(R.id.Pull_Data);
    Pull_Data.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {
            new MyAsyncTask().execute(URL);

        }


    });


private class MyAsyncTask extends AsyncTask<String, String, String>{
    protected String doInBackground(String... args) {
        SetValues(args[0]);
        return null;
    }

JSON拉/操作代码:

 public static JSONObject getJSONfromURL(String url){

    //initialize
    InputStream is = null;
    String result = "";
    JSONObject JArray = null;

    //http post
    try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    }catch(Exception e){
        Log.e("log_tag", "Error in http connection " + e.toString());
    }

    // convert response to string
    try{
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null){
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
        //client_Address1.setText(result);
    }catch(Exception e){
        Log.e("log_tag", "Error converting result " + e.toString());
    }


    // try parse the string to a JSON object

    try{
            JArray = new JSONObject(result);
    }catch(JSONException e){
        Log.e("log_tag", "Error parsing data " + e.toString());
    }
    return JArray;
}

public void SetValues(String url){
    JSONObject json = getJSONfromURL(url);

    // get the element that holds the addresses
    try{
        JSONArray addresses = json.getJSONArray("Address");

        // get the proper items
        JSONObject e = addresses.getJSONObject(0);
        client_Address1.setText(e.getString("addressLineOne"));
        client_Address2.setText(e.getString("addressLineTwo"));
        client_Address3.setText(e.getString("addressCity") + ", " + e.getString("addressState") + " " + e.getString("addressZip"));
        client_Id.setText(e.getString("clientID"));
    }catch(JSONException e){
    Log.e("log_tag", "Error parsing data " + e.toString());
    }
}

最后,logcat条目:

 08-21 11:49:42.860: E/log_tag(30551): Error converting result java.lang.NullPointerException
 08-21 11:49:42.860: E/log_tag(30551): Error parsing data org.json.JSONException: End of input at character 0 of 
 08-21 11:49:42.865: W/dalvikvm(30551): threadid=12: thread exiting with uncaught exception (group=0x40c101f8) 
 08-21 11:49:42.870: E/AndroidRuntime(30551): FATAL EXCEPTION: AsyncTask #1
 08-21 11:49:42.870: E/AndroidRuntime(30551): java.lang.RuntimeException: An error occured while executing doInBackground()
 08-21 11:49:42.870: E/AndroidRuntime(30551):   at android.os.AsyncTask$3.done(AsyncTask.java:278)
 08-21 11:49:42.870: E/AndroidRuntime(30551):   at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
 08-21 11:49:42.870: E/AndroidRuntime(30551):   at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
 08-21 11:49:42.870: E/AndroidRuntime(30551):   at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
 08-21 11:49:42.870: E/AndroidRuntime(30551):   at java.util.concurrent.FutureTask.run(FutureTask.java:137)
 08-21 11:49:42.870: E/AndroidRuntime(30551):   at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
 08-21 11:49:42.870: E/AndroidRuntime(30551):   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
 08-21 11:49:42.870: E/AndroidRuntime(30551):   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
 08-21 11:49:42.870: E/AndroidRuntime(30551):   at java.lang.Thread.run(Thread.java:856)
 08-21 11:49:42.870: E/AndroidRuntime(30551): Caused by: java.lang.NullPointerException
 08-21 11:49:42.870: E/AndroidRuntime(30551):   at com.example.networking.MainActivity.SetValues(MainActivity.java:353)
 08-21 11:49:42.870: E/AndroidRuntime(30551):   at com.example.networking.MainActivity$MyAsyncTask.doInBackground(MainActivity.java:222)
 08-21 11:49:42.870: E/AndroidRuntime(30551):   at com.example.networking.MainActivity$MyAsyncTask.doInBackground(MainActivity.java:1)
 08-21 11:49:42.870: E/AndroidRuntime(30551):   at android.os.AsyncTask$2.call(AsyncTask.java:264)
 08-21 11:49:42.870: E/AndroidRuntime(30551):   at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
 08-21 11:49:42.870: E/AndroidRuntime(30551):   ... 5 more

4 个答案:

答案 0 :(得分:2)

使用Opera Dragonfly工具向您提供的Url发出Http POST请求(没有发布的数据):

请求:

POST /deding/vpmi_mobile/WebAPI/WebAPI/api/address HTTP/1.1
Host: dev4.vcsonline.com
Content-Length: 0

这是我回复的回复:

HTTP/1.1 204 No Content
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Sun, 25 Aug 2013 17:18:51 GMT

请注意No Content。看起来您的Web服务不接受POST请求?

答案 1 :(得分:0)

        new MyAsyncTask().execute(URL);

对我来说似乎有风险。由于您没有创建对新MyAsyncTask实例的任何引用,因此它可能会被垃圾收集。尝试将其分配给成员变量:

        mAsyncTask = new MyAsyncTask();
        mAsyncTask.execute(URL);

其中mAsyncTask是您的活动的成员。

此更改可能会也可能不会解决此问题,但可能会阻止其他人。

答案 2 :(得分:0)

您正在使用setValues()更新未在UI线程上运行的doInBackground方法中的UI控件。

相反,将其转移到在UI线程上运行的onPostExecute()。我的意思是更新UI控件。您必须在doInBackground

中执行所有网络和任何时间处理

请告诉我这是否有效。

答案 3 :(得分:0)

我有同样的问题,在我发现问题出现在HttpPost参考之后。所以,我在HttpGet中更改了它,我的问题解决了。

试试这段代码:

public static JSONObject getJSONfromURL(String url){
//initialize
InputStream is = null;
String result = "";
JSONObject JArray = null;

//http post
try{
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url);
    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    is = entity.getContent();
}catch(Exception e){
    Log.e("log_tag", "Error in http connection " + e.toString());
}

// convert response to string
try{
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null){
        sb.append(line + "\n");
    }
    is.close();
    result = sb.toString();
    //client_Address1.setText(result);
}catch(Exception e){
    Log.e("log_tag", "Error converting result " + e.toString());
}


// try parse the string to a JSON object

try{
        JArray = new JSONObject(result);
}catch(JSONException e){
    Log.e("log_tag", "Error parsing data " + e.toString());
}
return JArray;
 }


 public void SetValues(String url){
JSONObject json = getJSONfromURL(url);

// get the element that holds the addresses
try{
    JSONArray addresses = json.getJSONArray("Address");

    // get the proper items
    JSONObject e = addresses.getJSONObject(0);
    client_Address1.setText(e.getString("addressLineOne"));
    client_Address2.setText(e.getString("addressLineTwo"));
    client_Address3.setText(e.getString("addressCity") + ", " + e.getString("addressState") + " " + e.getString("addressZip"));
    client_Id.setText(e.getString("clientID"));
}catch(JSONException e){
Log.e("log_tag", "Error parsing data " + e.toString());
}
}