当前位置: 首页 > 知识库问答 >
问题:

致命异常AsyncTask #1和Android doInBackground()

崔宇
2023-03-14

早上好StackOver Flow Pros,

我需要一点帮助。我正在运行一个Android应用程序,该应用程序通过php脚本调用MySql数据库,当我运行该应用程序时,我得到一个由空指针异常导致的AsyncTask #1的致命异常错误。它说是在执行doInBackground时发生的。这是我从MyBringBack跟随的一个教程。我真的需要好好想想这件事,因为我已经想了好几天了。如果我删除/注释大部分Log.d语句,它将运行良好,但我不会从JSON响应中看到标签,代码列在下面,谁能帮我解决这个问题或告诉我代码有什么问题。

这是logcat的错误日志

10-25 09:27:47.818:E/JSON解析器(1041):解析org.JSON数据时出错。JSONException:java.lang.String类型的值数组(2)无法转换为JSONObject 10-25 09:27:47.818:W/dalvikvm(1041):threadid=11:线程退出,未捕获异常(组=0xb1b06ba8)10-25 9:27:48.828:E/AndroidRuntime(1041:致命异常:AsyncTask35;1 10-25 10:27:46.828:E/AndrodRuntime(041):进程:com。山猫服务,PID:1041 10-25 09:27:47.828:E/AndroidRuntime(1041):java.lang.RuntimeException:执行doInBackground()时出错10-25 9:27:48.828:E/AndroRuntime(041):在android.os.AsyncTask$3.done(AsyncTask.java:300)10-25 2009:27:45.828:E/AndrodRuntime(104 1):在java.util.concurrent.FutureTask.finishCompletion(FutureTTask.java:355)10-20 09:27:47.829:E/DroidRuntime我(1041):在java.util.concurrent.FutureTask.setException(FutureTtask.java:222)10-25 09:27:47.828:E/AndroidRuntime(1041):在java.uti.Concurent.FutureStask.run(FutureTask.java:242)10-20 09:27:47.822:E/AndroidRuntime(041):在android.os.AsyncTask$SerialExecutor$1.run上运行(AsyncTask.java:231)10.25 09:29:47.82:E/AndroidRuntime(1041)在java.util.Concorrent.ThreadPoolExecutor.runWorker上运行(ThreadPoolExecutor.java:1112)10-25 09:27:47.828:E/AndroidRuntime(1041):at java.util.concurrent.ThreadPool Executor$Worker.run(ThreadPooleExecutor.java:587)10-10 09:27:47.827:E/AndroidRuntime(041):at java.lang.Thread.run(Thread.java:841)10-20 09:27:47.822:E/AndroidRuntime(1041)由:java.lang.NullPointerException引起我(1041):在com.bobcatservice.Login$AttemptLogin.doInBackground(Login.java:126)10-25 09:27:47.828:E/AndroidRuntime(1041):在com.bobcatservice.Login$atttemptlogin/doInBackground(登录.java:1)10-2509:27:47.822:at android.os.AsyncTask$2.call(AsyncTask.java:288)10-25209:27:47.821:E/AndroidRuntime(1042):at java.util.concurrent.FutureTask.run(future UreTask.java:237)10-25 09:27:47.828:E/AndroidRuntime(1041):…4更多10-25 09:27:49.968:E/WindowManager(1041):android.view。窗口泄漏:活动com.bobcatservice。登录已泄漏到com.android.internal.policy.impl窗口。PhoneWindow$DecorView{b1e8e430 V.E..R..d0,0-684192}最初添加到这里10-25 09:27:49.968:E/WindowManager(1041):在android.view.ViewRootImpl.(ViewRootImp.java:348)10-25 9:27:48.968:E/WindowManager(1041)在android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)10-20 09:27:49.969:E/WindowManager(1042):在android.view.WindowManager rimpl.addView(WindowManagerImpl.java:69)10-25 09:27:49.968:E/WindowManager(1041):在android.app.Dialog.show(Dialog.java:286)

这是有问题的代码

//AsyncTask is a seperate thread than the thread that runs the GUI
//Any type of networking should be done with asynctask.
class AttemptLogin extends AsyncTask<String, String, String> {

     /**
    * Before starting background thread Show Progress Dialog
    * */
    boolean failure = false;

   @Override
   protected void onPreExecute() {
       super.onPreExecute();
       pDialog = new ProgressDialog(Login.this);
       pDialog.setMessage("Attempting login...");
       pDialog.setIndeterminate(false);
       pDialog.setCancelable(true);
       pDialog.show();
   }

    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
         // Check for success tag
       int success;
       String username = user.getText().toString();
       String password = pass.getText().toString();

           // Building Parameters
           List<NameValuePair> params = new ArrayList<NameValuePair>();
           params.add(new BasicNameValuePair("username", username));
           params.add(new BasicNameValuePair("password", password));

           Log.d("request!", "starting");
           // getting product details by making HTTP request
           JSONObject json = jsonParser.makeHttpRequest(
                  LOGIN_URL, "POST", params);

           try {
           // check your log for json response
           Log.d("Login attempt", json.toString());

           // json success tag
           success = json.getInt(TAG_SUCCESS);
           if (success == 1) {
            Log.d("Login Successful!", json.toString());
            Intent i = new Intent(Login.this, Welcome.class);
            finish();
            startActivity(i);
            return json.getString(TAG_MESSAGE);
            }else{
            Log.d("Login Failure!", json.getString(TAG_MESSAGE));
            return json.getString(TAG_MESSAGE);

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

       return null;

    }
    /**
    * After completing background task Dismiss the progress dialog
    * **/
   protected void onPostExecute(String file_url) {
       // dismiss the dialog once product deleted
       pDialog.dismiss();
       if (file_url != null){
        Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
       }

   }

}

}

共有2个答案

穆理
2023-03-14

在您的代码之上,请检查是否存在create_product.php(此处在android文件夹中),并将table_name替换为您的表名,并$response[“message”] = mysql_error();要知道create_product.php在android sdk的logcat中有什么问题

// url to create send data. This contains the ip address of my machine on which the local server is running. You will write the IP address of your machine
         private static String url = "http://192.168.***.1:8080/android/create_product.php";

create_product.php

<?php 
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['id']) && isset($_POST['name'])) { 
$id = $_POST['id'];
$name = $_POST['name'];   
// include db connect class
require_once __DIR__ . '/db_connect.php'; 
// connecting to db
$db = new DB_CONNECT(); 
// mysql inserting a new row
$result = mysql_query("INSERT INTO table_name(id, name) VALUES('$id', '$name')"); 
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created."; 
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] =  mysql_error();; 
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing"; 
// echoing JSON response
echo json_encode($response);
}
?>

并在清单中添加此代码,否则将会生成此错误

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
袁弘化
2023-03-14

如果我删除/评论大部分日志。d声明:它将运行良好

我们似乎可以在< code>doInBackground()方法的一些日志调用中找到一个问题。这个怎么样?

Log.d("request!", "starting");

不,似乎不错。下一个呢?

Log.d("Login attempt", json.toString());

啊哈!我们如何获得这个<code>json<code>变量?

JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);

检查超文本传输协议请求的结果,您可能会在此处获得null

如果<code>json<code>不为空怎么办?我们还有一个可疑的日志呼叫:

Log.d("Login Failure!", json.getString(TAG_MESSAGE));

据我所知,如果< code>Log.d()的第二个参数是< code>null,就会得到< code > NullPointerException ,所以也要检查这个参数。

如果这也不是问题呢?嗯,我建议你在这里使用调试器。

 类似资料: