简体   繁体   English

AsyncTask在后台运行身份验证

[英]Asynctask to run authentication in background

i am trying a simple authentication page using the AsyncTask. 我正在尝试使用AsyncTask的简单身份验证页面。 I am running the connection to my webservice in the doInBackground() method and updating the UI in the onPostExecute() method. 我正在doInBackground()方法中运行到Web服务的连接,并在onPostExecute()方法中更新UI。 My webservice simply checks the username and password sent to it and returns a JSON object. 我的Web服务仅检查发送给它的用户名和密码,并返回一个JSON对象。 As long as the webservice is up and returns the JSON object this code works fine. 只要Web服务启动并返回JSON对象,此代码就可以正常工作。 But when the service is down and the connection fails i get the error i have attached below. 但是,当服务关闭并且连接失败时,我会收到以下错误。

Here is my code : 这是我的代码:

  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 : 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

replace jObj.put("authentication", "cfailed"); 替换jObj.put("authentication", "cfailed"); with

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

and change your current onPostExecute as : 并将您当前的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
       }

    }

Hey after close observation of your code, I found that it was due to NullPointerException caused by jObj (JsonObject). 嘿,仔细观察您的代码后,我发现这是由于jObj (JsonObject)引起的NullPointerException As you posted in the code check that jObj is initialized as null and Object was created only when web service executed successfully. 如您在代码中所发布的,请检查jObj是否初始化为null以及仅在成功执行Web服务时创建对象。 But when Connection error occured it was thrown to IOException block where you are directly putting the key value pairs without creating object. 但是,当发生连接错误时,它将被抛出到IOException块中,您可以在其中直接创建键值对而不创建对象。 Add one more line jObj = new JsonObject(); 再增加一行jObj = new JsonObject(); before 194th line. 第194行之前。 Hope it solves your issue. 希望它能解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM