【问题标题】:how to solve this : Fatal Exception Asynctask #1 java.lang.RuntimeException error occured while executing doInBackground()如何解决:执行 doInBackground() 时发生致命异常 Asynctask #1 java.lang.RuntimeException 错误
【发布时间】:2014-05-09 15:11:40
【问题描述】:

我是从 android 连接到 php 的新手。 所以这是我的代码:

package com.example.androidhive;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;


public class tesMainScreen extends Activity{

    Button btnViewProducts;
    Button btnNewProduct;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_screen);

        // Buttons
        btnViewProducts = (Button) findViewById(R.id.btnViewProducts);
        btnNewProduct = (Button) findViewById(R.id.btnCreateProduct);

        // view products click event
        btnViewProducts.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                // Launching All products Activity
                Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
                startActivity(i);

            }
        });

        // view products click event
        btnNewProduct.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                // Launching create new product activity
                Intent i = new Intent(getApplicationContext(), NewProductActivity.class);
                startActivity(i);

            }
        });
    }
}

这就是 doinBackground 存在的地方:

package com.example.androidhive;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class NewProductActivity extends Activity {

    // Progress Dialog
    private ProgressDialog pDialog;

    JSONParser jsonParser = new JSONParser();
    EditText inputName;
    EditText inputPrice;
    EditText inputDesc;

    // url to create new product
    private static String url_create_product = "http://10.0.2.2/android_connect/create_product.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_product);

        // Edit Text
        inputName = (EditText) findViewById(R.id.inputName);
        inputPrice = (EditText) findViewById(R.id.inputPrice);
        inputDesc = (EditText) findViewById(R.id.inputDesc);

        // Create button
        Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);

        // button click event
        btnCreateProduct.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                // creating new product in background thread
                new CreateNewProduct().execute();
            }
        });
    }

    /**
     * Background Async Task to Create new product
     * */
    class CreateNewProduct extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(NewProductActivity.this);
            pDialog.setMessage("Creating Product..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Creating product
         * */
        protected String doInBackground(String... args) {
            String name = inputName.getText().toString();
            String price = inputPrice.getText().toString();
            String description = inputDesc.getText().toString();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name", name));
            params.add(new BasicNameValuePair("price", price));
            params.add(new BasicNameValuePair("description", description));

            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest("{http://10.0.2.2/android_connect/create_product.php}",
                    "POST", params);

            // check log cat fro response
            //Log.d("Create Response", json.toString());

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // successfully created product
                    Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
                    startActivity(i);

                    // closing this screen
                    finish();
                } else {
                    // failed to create product
                }
            } 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 done

            pDialog.dismiss();
        }

    }
}

它有很多来自 logcat 的错误:

- 05-09 10:56:44.007: ERROR/AndroidRuntime(456): FATAL EXCEPTION: AsyncTask #1
 - 05-09 10:56:45.207: ERROR/WindowManager(456): Activity com.example.androidhive.NewProductActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4052ea40 that was originally added here
 - 05-09 10:56:46.447: ERROR/InputDispatcher(61): channel '4070d668 com.example.androidhive/com.example.androidhive.tesMainScreen (server)' ~ Consumer closed input channel or an error occurred.  events=0x8

所以请帮助我,谢谢。

【问题讨论】:

  • 尝试这个if (success == 1) { pDialog.dismiss(); }并从onPostExecute(.......)中删除pDialog.dismiss();
  • 不要在doInBackground(String... args) 中调用startActivity(i)finish() 函数。从 doInBackground(String... args)' and then take action in onPostExecute(String info)` 以字符串形式返回信息,具体取决于 info 的值。
  • 试过了,还是报错,还有什么方法吗?
  • 谁能帮帮我?

标签: java android android-asynctask


【解决方案1】:

在 onPostExecute 中调用下面的东西:-

                Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
                startActivity(i);

                // closing this screen
                finish();

检查 onPostExecute 上的关闭

        if(dialog != null && dialog.isShowing())
            dialog.dismiss();

UI 元素只能从 UI 线程更新。使用异步任务做背景词,在onPostExecute中修改UI,运行在UI线程上

【讨论】:

  • 相同,它是 05-09 11:26:43.417: ERROR/AndroidRuntime(637): FATAL EXCEPTION: AsyncTask #1 05-09 11:26:43.417: ERROR/AndroidRuntime(637): java .lang.RuntimeException:执行doInBackground()时发生错误
  • 仍然显示相同的错误,这让我很困惑。所以我的 onPostExecute 现在是: Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);开始活动(一); // 关闭这个屏幕 finish(); if(pDialog != null && pDialog.isShowing()) pDialog.dismiss();
【解决方案2】:

这个错误:

Activity [...] 泄露了最初添加在这里的窗口 com.android.internal.policy.impl.PhoneWindow$DecorView@4052ea40

发生是因为您尝试在 Dialog 仍在显示时启动另一个 Activity。您尝试从 onPostExecutedismiss 它是正确的方法,但是,您调用了新的 Intent 并从 doInBackground 启动了新的活动。然后,系统无法访问onPostExecute,因为您没有从doInBackground 向其发送任何内容。
改变你的方法如下:

protected String doInBackground(String... args) {
    String isLoaded;
    // ...
    try {
        int success = json.getInt(TAG_SUCCESS);
        if (success == 1) {
            // success: return a string value "success"
            isLoaded = "Success";
        } else {
            // failed: return a string value "failed"
            isLoaded = "Failed";
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    // return this String value to onPostExecute
    return isLoaded;
}

// then retrieve this value by param "file_url"
protected void onPostExecute(String file_url) {
    // dismiss the dialog once done
    pDialog.dismiss();
    if(file_url.equals("Success") {
        // success: launch another activity
        Intent i = new Intent(NewProductActivity.this, AllProductsActivity.class);
        startActivity(i);
        NewProductActivity.this.finish();
    } else if(file_url.equals("Failed") {
        // failed: do something
        Toast.makeText(NewProductActivity.this, "An error occurred...", Toast.LENGTH_SHORT).show();
    }
}  

另外,你可以通过onPause(或onDestroy)方法调用dismiss,以防用户退出你的应用。如果他回来,你只需要稍后找回它:

@Override
public void onPause(){
    super.onPause();
    if(pDialog != null)
        pDialog.dismiss();
}

【讨论】:

  • 我认为您需要更改getApplicationContext,我猜它是附加到上下文tesMainScreen 而不是NewProductActivity 类。对tesMainScreen 中的Intents 执行相同的操作。查看我的编辑。
  • 还有@stevian12,对于InputDispatcher 错误,我真的不知道如何解决这个问题,但this thread 可能会有所帮助,this one 也会有帮助。
  • 非常感谢您的帮助,但还是一样,很奇怪。
猜你喜欢
  • 2018-01-11
  • 1970-01-01
  • 2013-06-01
  • 2020-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多