Asynctask在后台运行身份验证

时间:2013-01-03 07:46:18

标签: android json authentication android-asynctask

我正在使用AsyncTask尝试一个简单的身份验证页面。我在doInBackground()方法中运行与webservice的连接,并在onPostExecute()方法中更新UI。我的webservice只检查发送给它的用户名和密码,并返回一个JSON对象。只要webservice启动并返回JSON对象,此代码就可以正常工作。但是当服务停止并且连接失败时,我得到了下面附带的错误。

这是我的代码:

  private class AuthneticateTask extends AsyncTask<String, Void, JSONObject> {

    public InputStream is = null;
    public JSONObject jObj = null;
    public String json = "";
    public int flag = 0;

    protected JSONObject doInBackground(String... urls) {
        HttpClient client = new DefaultHttpClient();  
        String getURL = "http://MYWEBSERVICE";
        HttpGet get = new HttpGet(getURL);
        get.addHeader("authorization", urls[0]);
        HttpResponse responseGet;

        try {

            responseGet = client.execute(get);
            HttpEntity httpEntity = responseGet.getEntity();
            is = httpEntity.getContent();  
             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");
                        System.out.println("Authentication status: "+sb.toString());
                    }
                    is.close();

                    json = sb.toString();
                    try {
                        jObj = new JSONObject(json);
                    } catch (JSONException e) {
                        Log.e("JSON Parser", "Error parsing data " + e.toString());
                    }



                } catch (Exception e) {
                   // Log.e("Buffer Error", "Error converting result " + e.toString());
                }


        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block

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

            System.out.println("this is where connection errors are caught!");
        jObj.put("authentication", "cfailed");
                return jObj;
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }

        }
            return jObj;
    }


    protected void onPostExecute(JSONObject result) {
         String auth;
         String notes;

        try {
            auth = jObj.getString("authentication");
            notes = jObj.getString("note");

            if (auth.equalsIgnoreCase("cfailed"))
            {
                emessage.setTextColor(RED);
                emessage.setText("Connection to server failed");
            }
            else
            {
            if (auth.equalsIgnoreCase("Successfull"))
                    {
                // TODO login to page   

            }else if(auth.equalsIgnoreCase("unSuccessfull"))
            {
                emessage.setText(notes);
                emessage.setTextColor(RED);
                if(notes.contains("password"))
                    lpass.setTextColor(RED);
                else if(notes.contains("name"))
                    luname.setTextColor(RED); 


            }
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

Logcat:

  01-03 13:22:13.567: E/AndroidRuntime(334): FATAL EXCEPTION: AsyncTask #1
  01-03 13:22:13.567: E/AndroidRuntime(334): java.lang.RuntimeException: An error occured while executing doInBackground()
  01-03 13:22:13.567: E/AndroidRuntime(334): atandroid.os.AsyncTask$3.done(AsyncTask.java:200)
  01-03 13:22:13.567: E/AndroidRuntime(334):at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
 01-03 13:22:13.567: E/AndroidRuntime(334): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
 01-03 13:22:13.567: E/AndroidRuntime(334):at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
 01-03 13:22:13.567: E/AndroidRuntime(334):at java.util.concurrent.FutureTask.run(FutureTask.java:137)
 01-03 13:22:13.567: E/AndroidRuntime(334):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
 01-03 13:22:13.567: E/AndroidRuntime(334):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
 01-03 13:22:13.567: E/AndroidRuntime(334):     at java.lang.Thread.run(Thread.java:1096)
 01-03 13:22:13.567: E/AndroidRuntime(334): Caused by: java.lang.NullPointerException
 01-03 13:22:13.567: E/AndroidRuntime(334):     at com.cyberink.asyncauth.login$AuthneticateTask.doInBackground(login.java:194)
 01-03 13:22:13.567: E/AndroidRuntime(334):     at com.cyberink.asyncauth.login$AuthneticateTask.doInBackground(login.java:1)
 01-03 13:22:13.567: E/AndroidRuntime(334):     at android.os.AsyncTask$2.call(AsyncTask.java:185)
 01-03 13:22:13.567: E/AndroidRuntime(334):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
 01-03 13:22:13.567: E/AndroidRuntime(334):     ... 4 more

2 个答案:

答案 0 :(得分:2)

替换jObj.put("authentication", "cfailed");
 jObj=new JSONObject();
 jObj.put("authentication", "cfailed");

并将您当前的onPostExecute更改为:

protected void onPostExecute(JSONObject result) {
         String auth;
         String notes;
       // check here if result if null or not
       if(result !=null){
         try {
             auth = result.getString("authentication");
             notes = result.getString("note");
             // your code here      
           } catch (JSONException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
           }
       }
      else{
           // code here if json null
       }

    }

答案 1 :(得分:1)

嘿嘿仔细观察你的代码之后,我发现它是由NullPointerException引起的jObj(JsonObject)。正如您在代码中发布的那样,检查jObj是否初始化为null,并且只有在Web服务成功执行时才创建Object。但是当发生Connection错误时,它被抛出到IOException块,在那里您直接放置键值对而不创建对象。在第194行之前再添加一行jObj = new JsonObject();。希望它能解决你的问题。