【问题标题】:Avoid force Close Error when Server is not responding当服务器没有响应时避免强制关闭错误
【发布时间】:2014-01-17 09:06:43
【问题描述】:

在我的应用程序中,用户必须登录才能访问应用程序。登录详细信息存储在 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;

}

【问题讨论】:

  • 张贴LoginActivity.java并注明第280行
  • 在此处发布您的 AsyncTask 代码...或在使用对象之前保留一个条件来检查对象是否为空..
  • 第 280 行是什么?
  • @Raghunandan!!!我已经粘贴了我的代码
  • @vishesh chandra 我已经粘贴了我的代码

标签: android nullpointerexception connection forceclose


【解决方案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

您可以将参数直接传递给 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);

【讨论】:

  • 即必须比较返回的对象是否为空
  • @vimala 不,只是响应表单服务器为空。应该检查 jsonparser 代码
  • @vimala 你可以使用 if(TextUtils.isEmpty("yourstring")) this 如果字符串为空或长度为 0,则返回 true。
  • 你的想法对我有用..但它经常卡在某个地方并显示错误的输出
  • @vimala 检查服务器的响应
【解决方案2】:

我认为您应该检查来自服务器的响应代码并据此采取行动,因为它表明 json 创建失败并且可能导致空指针。

【讨论】:

  • 我尝试通过将 null 与响应进行比较..但它不起作用
  • @vimala 响应代码是 int ,因此不能等于 null。检查 int 值并据此采取行动。
【解决方案3】:

使用 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();
}

请试一试。

【讨论】:

  • 检查没问题,但真正的问题是返回的 json 为 null,应该先修复
  • @vishesh chandra..谢谢它有效,但在我的帖子执行中我无法正确配置......
  • successL 是字符串,你如何将它与 !=??/ 进行比较
  • @vimala 你必须接受 Raghunandan 的指导,他是对的。
  • @vishesh chandra 你的想法对我有用..但它经常卡在某个地方并显示错误的输出
猜你喜欢
  • 2017-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-13
  • 1970-01-01
  • 2023-03-23
相关资源
最近更新 更多