服务器没有响应时,避免强制关闭错误

时间:2014-01-17 09:06:44

标签: android nullpointerexception connection forceclose

在我的应用程序中,用户必须登录才能访问app.Login详细信息存储在MySQL数据库和php文件中。由于apache服务器已经关闭了应用程序,它在我的logcat中显示了以下详细信息,

[<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
01-17 08:59:01.935: I/tagconvertstr1(1160): <html><head>
01-17 08:59:01.935: I/tagconvertstr1(1160): <title>404 Not Found</title>
01-17 08:59:01.935: I/tagconvertstr1(1160): </head><body>
01-17 08:59:01.935: I/tagconvertstr1(1160): <h1>Not Found</h1>
01-17 08:59:01.935: I/tagconvertstr1(1160): <p>The requested URL     /bcreasearchT/Service/loginresponse.php was not found on this server.</p>
01-17 08:59:01.935: I/tagconvertstr1(1160): <hr>
01-17 08:59:01.935: I/tagconvertstr1(1160): <address>Apache/2.2.15 (CentOS) Server at www.medsmonit.com Port 80</address>
01-17 08:59:01.935: I/tagconvertstr1(1160): </body></html>
01-17 08:59:01.935: I/tagconvertstr1(1160): ]
01-17 08:59:01.945: E/JSON Parser(1160): Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
01-17 08:59:01.955: I/Choreographer(1160): Skipped 40 frames!  The application may be doing too much work on its main thread.
01-17 08:59:01.965: I/tagconvertstr3(1160): [null]
01-17 08:59:01.965: W/dalvikvm(1160): threadid=14: thread exiting with uncaught exception (group=0x40a71930)
01-17 08:59:01.995: I/Choreographer(1160): Skipped 31 frames!  The application may be doing too much work on its main thread.
01-17 08:59:02.025: E/AndroidRuntime(1160): FATAL EXCEPTION: AsyncTask #3
01-17 08:59:02.025: E/AndroidRuntime(1160): java.lang.RuntimeException: An error occured while executing doInBackground()
01-17 08:59:02.025: E/AndroidRuntime(1160):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
01-17 08:59:02.025: E/AndroidRuntime(1160):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
01-17 08:59:02.025: E/AndroidRuntime(1160):     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
01-17 08:59:02.025: E/AndroidRuntime(1160):     at java.util.concurrent.FutureTask.run(FutureTask.java:239)
01-17 08:59:02.025: E/AndroidRuntime(1160):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-17 08:59:02.025: E/AndroidRuntime(1160):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
01-17 08:59:02.025: E/AndroidRuntime(1160):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
01-17 08:59:02.025: E/AndroidRuntime(1160):     at java.lang.Thread.run(Thread.java:856)
01-17 08:59:02.025: E/AndroidRuntime(1160): Caused by: java.lang.NullPointerException
01-17 08:59:02.025: E/AndroidRuntime(1160):     at com.example.sms.LoginActivity$AttemptLogin.doInBackground(LoginActivity.java:280)
01-17 08:59:02.025: E/AndroidRuntime(1160):     at com.example.sms.LoginActivity$AttemptLogin.doInBackground(LoginActivity.java:1)
01-17 08:59:02.025: E/AndroidRuntime(1160):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-17 08:59:02.025: E/AndroidRuntime(1160):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
01-17 08:59:02.025: E/AndroidRuntime(1160):     ... 4 more

我怎样才能纠正它?任何人都可以帮助我!

更新:

这是我的aynctask代码,

 class AttemptLogin extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        username = (EditText) findViewById(R.id.mobnum);
           passw = (EditText) findViewById(R.id.password);
           uname = username.getText().toString();

              password = passw.getText().toString();    

        pDialog = new ProgressDialog(LoginActivity.this);
        pDialog.setMessage("VALIDATING USER...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {


          proInfo.clear();

         List<NameValuePair> params1 = new ArrayList<NameValuePair>();

         params1.add(new BasicNameValuePair("username", uname));
         params1.add(new BasicNameValuePair("pswd", password));

         JsonParser jLogin = new JsonParser();
         JSONObject json = jLogin.makeHttpRequest(url,"POST", params1);


         Log.i("tagconvertstr3", "["+json+"]");
         try
         {

             JSONObject jUser = json.getJSONObject(TAG_SRESL);
             userid = jUser.getString(TAG_USERID );

             successL = jUser.getString(TAG_SUCCESS1);

             proInfo.add(userid);


             }

         catch(JSONException e)
         {
             e.printStackTrace();

         }


        return null;
    }

   protected void onPostExecute(String file_url) {


       if(successL.equalsIgnoreCase("Yes"))
       {
           usrname=uname;
           new ViewProfile().execute();

       }

       else{
         final Dialog dialog = new Dialog(context);
             dialog.setContentView(R.layout.custom_dialog);
             dialog.setTitle("Login Failed");
             dialog.setCancelable(false);
             dialog.setCanceledOnTouchOutside(false);
             TextView txt = (TextView) dialog.findViewById(R.id.errorlog);
              txt.setText("Incorrect username or password!");
              Button dialogButton = (Button) dialog.findViewById(R.id.release);
              dialogButton.setOnClickListener(new OnClickListener() {
                  public void onClick(View vd) {
                       dialog.dismiss();

            }
            });
              dialog.show();
              pDialog.dismiss();
          }
        }


    }

这是我的json解析器类,

  public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {


    try {

        if(method.equalsIgnoreCase("POST")){


            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

            System.out.println(is);

            System.out.println("getting the content");

        }else if(method.equalsIgnoreCase("GET")){

            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }           

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


    System.out.println("getting  all the values ");

    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();

        json = sb.toString();    


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


    try {

        Log.i("tagconvertstr1", "["+json+"]");

        jsonObject = new JSONObject(json);
          System.out.println("json object parse finished");

        Log.i("tagconvertstr2","["+json+"]");




    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }




    return jsonObject;

}






public JSONObject getJSONFromUrl(String url) {

            try {

                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();           

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            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();
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }

            try {
                Log.i("tagconvertstr", "["+json+"]");
                jsonObject = new JSONObject(json);
                Log.i("tagconvertstr", "["+json+"]");

            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }


            return jsonObject;

}

3 个答案:

答案 0 :(得分:1)

JSONObject jUser = json.getJSONObject(TAG_SRESL);//This is mt 280th line 

您的json为空。开始调试。 jLogin.makeHttpRequest(url,"POST", params1);返回null。

同样移动(它更好)

 username = (EditText) findViewById(R.id.mobnum);
 passw = (EditText) findViewById(R.id.password);

onCreate

您可以将params直接传递给asynctask doInbackground

 new AttemptLogin().execute(username.getText().toString(),passw.getText().toString());

然后在doInbackground()

 //String... params 
 params[0] is username
 params[1]  is password  

你也错过了

@Override
protected void onPostExecute(String file_url) {
super.onPostExecute(file_url);

答案 1 :(得分:0)

我认为您应该检查来自服务器的响应代码并根据该行为进行操作,因为它会导致json创建失败并且可能导致nullpointer。

答案 2 :(得分:0)

使用json对象之前的Kepp条件。替换doInBackground中的代码。

try {
    if(json != null){
        JSONObject jUser = json.getJSONObject(TAG_SRESL);
        userid = jUser.getString(TAG_USERID );
        successL = jUser.getString(TAG_SUCCESS1);
        proInfo.add(userid);
    }
}catch(JSONException e) {
    e.printStackTrace();
}

在检查equalsIgnoreCase之前检查此字符串,替换onPostExecute代码。

if(successL != null && successL.equalsIgnoreCase("Yes")) {
    usrname=uname;
    new ViewProfile().execute();
}

请试试。