AsyncTask 将数据存储到服务器

AsyncTask to Store Data to Server

我能够将数据存储到服务器,为此我正在使用 AsyncTask,但每次我在 行号 221 处得到 Unfortunately App has stopped 即:

Toast.makeText(MainActivity.this, "Registered Succesfully", Toast.LENGTH_SHORT).show();

完整日志:

01-06 06:57:02.614: E/AndroidRuntime(1458): FATAL EXCEPTION: AsyncTask #2
01-06 06:57:02.614: E/AndroidRuntime(1458): Process: com.example.loginsystem, PID: 1458
01-06 06:57:02.614: E/AndroidRuntime(1458): java.lang.RuntimeException: An error occured while executing doInBackground()
01-06 06:57:02.614: E/AndroidRuntime(1458):     at android.os.AsyncTask.done(AsyncTask.java:300)
01-06 06:57:02.614: E/AndroidRuntime(1458):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
01-06 06:57:02.614: E/AndroidRuntime(1458):     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
01-06 06:57:02.614: E/AndroidRuntime(1458):     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
01-06 06:57:02.614: E/AndroidRuntime(1458):     at android.os.AsyncTask$SerialExecutor.run(AsyncTask.java:231)
01-06 06:57:02.614: E/AndroidRuntime(1458):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
01-06 06:57:02.614: E/AndroidRuntime(1458):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
01-06 06:57:02.614: E/AndroidRuntime(1458):     at java.lang.Thread.run(Thread.java:841)
01-06 06:57:02.614: E/AndroidRuntime(1458): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
01-06 06:57:02.614: E/AndroidRuntime(1458):     at android.os.Handler.<init>(Handler.java:200)
01-06 06:57:02.614: E/AndroidRuntime(1458):     at android.os.Handler.<init>(Handler.java:114)
01-06 06:57:02.614: E/AndroidRuntime(1458):     at android.widget.Toast$TN.<init>(Toast.java:327)
01-06 06:57:02.614: E/AndroidRuntime(1458):     at android.widget.Toast.<init>(Toast.java:92)
01-06 06:57:02.614: E/AndroidRuntime(1458):     at android.widget.Toast.makeText(Toast.java:241)
01-06 06:57:02.614: E/AndroidRuntime(1458):     at com.example.loginsystem.MainActivity$RegisterUser.doInBackground(MainActivity.java:221)
01-06 06:57:02.614: E/AndroidRuntime(1458):     at com.example.loginsystem.MainActivity$RegisterUser.doInBackground(MainActivity.java:1)
01-06 06:57:02.614: E/AndroidRuntime(1458):     at android.os.AsyncTask.call(AsyncTask.java:288)
01-06 06:57:02.614: E/AndroidRuntime(1458):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
01-06 06:57:02.614: E/AndroidRuntime(1458):     ... 4 more
01-06 06:57:02.654: W/ActivityManager(380):   Force finishing activity com.example.loginsystem/.MainActivity

异步任务:

class RegisterUser extends AsyncTask<String, String, String> {
        private ProgressDialog pDialog;

         /**
        * Before starting background thread Show Progress Dialog
        * */

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

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

            strUrlRegistration = "http:/someurl/register.php";  

            helper = new Helper();                                    

            params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("sName", strName));

            strServerResult  = helper.getHttpPost(strUrlRegistration ,params);

            strStatusId = "0";
            strMessage = "Unknow Status!";

            try {
                jsonObject = new JSONObject(strServerResult);
                strStatusId = jsonObject.getString("StatusID");
                strMessage = jsonObject.getString("Message");
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }               

            // Prepare Save Data
            if(strStatusId.equals("0"))
            {
                Toast.makeText(MainActivity.this, "Unable to register", Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(MainActivity.this, "Registered Succesfully", Toast.LENGTH_SHORT).show();
                editTextName.setText("");                   
            }  

           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(MainActivity.this, file_url, Toast.LENGTH_LONG).show();
           }

       }

    }

在 onPostExecute() 而不是 doingBackground() 中执行 Toast 将解决您的问题。不要在doingBackground()中使用UI相关操作。

protected void onPostExecute(String file_url) {
           // dismiss the dialog once product deleted
           pDialog.dismiss();
if(strStatusId.equals("0"))
            {
                Toast.makeText(MainActivity.this, "Unable to register", Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(MainActivity.this, "Registered Succesfully",       Toast.LENGTH_SHORT).show();
                editTextName.setText("");                   
            }  
           if (file_url != null){
            Toast.makeText(MainActivity.this, file_url, Toast.LENGTH_LONG).show();
           }

       }

Can't create handler inside thread that has not called Looper.prepare()

因为您正试图显示来自 doInBackground 的 Toast 消息,其中 运行 在非 ui 线程上。

根据 doInBackground 方法输出,使用 onPostExecute 而不是 doInBackground 向用户显示消息。