簡體   English   中英

Android Studio錯誤:“必須從UI線程調用方法getText(),當前推斷的線程是worker

[英]Android Studio error: "Method getText() must be called from the UI Thread, currently inferred thread is worker

我正在android studio中創建一個CRUD操作,但我不斷收到錯誤。 錯誤是當我檢查LogCat這是他們告訴我的

第156-158行
1907-1931 / com.example.casquejo.loginadmin E / AndroidRuntime:FATAL EXCEPTION:AsyncTask#2進程:com.example.casquejo.loginadmin,PID:1907 java.lang.RuntimeException:執行doInBackground時發生錯誤()由:java.lang.NullPointerException atcom.example.casquejo.loginadmin.NewProductActivity $ CreateNewProduct.doInBackground(NewProductActivity.java:85)at com.example.casquejo.loginadmin.NewProductActivity $ CreateNewProduct.doInBackground(NewProductActivity.java:58)atcom.example .casquejo.loginadmin.NewProductActivity $ CreateNewProduct.onPreExecute(NewProductActivity.java:67)atcom.example.casquejo.loginadmin.NewProductActivity $ 1.onClick(NewProductActivity.java:53)

有人可以幫我這個或者有人可以提出一個想法如何解決這個問題下面是我的java類EditProductActivity.class的代碼

       package com.example.casquejo.loginadmin;

        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;

        /**
        * Created by Casquejo on 9/14/2015.
        */
        public class NewProductActivity extends Activity {
    private ProgressDialog pDialog;

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

    private static String url_create_product = "http://10.0.2.2/android_connect/create_product.php";

    private static final String TAG_SUCCESS = "success";

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

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

        Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);
        btnCreateProduct.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                String name = inputName.getText().toString();
                String price = inputPrice.getText().toString();
                String description = inputDesc.getText().toString();
                new CreateNewProduct().execute(name, price,description);
            }
        });
    }

    class CreateNewProduct extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(NewProductActivity.this);
            pDialog.setMessage("Creating Product..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();

        }

        protected String doInBackground(String... args) {

            String name = args[0],
                    price = args[1],
                    description = args[2];

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

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

            Log.d("Create Response", json.toString());

            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
                    startActivity(i);
                    finish();
                }
                else {

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

            return null;
        }

        protected void onPostExecute(String file_url) {
            pDialog.dismiss();
        }

    }
}

ide指的是

  String name = txtName.getText().toString();
  String price = txtPrice.getText().toString();
  String description = txtDesc.getText().toString();

讀取值不應該是一個問題,但為了擺脫這個警告/錯誤,您可以將其移動到onClick並通過execute()傳遞值。 例如

btnSave.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View arg0) {
        String name = txtName.getText().toString();
        String price = txtPrice.getText().toString();
        String description = txtDesc.getText().toString();
        new SaveProductDetails().execute(name, price, description);
    }
});

當調用doInBackground時,你可以通過前params, String... args讀取那些bac。 三個點構造保留為varargs,並且varargs可以使用[]表示法像數組一樣訪問。 在示例的情況下,

args[0]包含name的值, args[1]包含price的值, args[2]包含description的值。

您正在從AsyncTask生成的后台線程中調用getText()

首先獲取文本,然后調用異步任務。 這是一個例子

new SaveProductDetails()
    .execute(txtName.getText().toString(), 
        txtPrice.getText().toString(), 
        txtDesc.getText().toString());

而內部SaveProductDetails doInBackground方法:

String name = args[0],
       price = args[1],
       description = args[2];

在asynctask中, doInBackground(...)方法在后台(非UI)線程中運行。 正如您在給出的錯誤中看到的那樣,您不能與后台線程中的UI元素進行交互。

您可以將參數傳遞到后台線程中,如其他一個答案中所建議的那樣,或者,您可以修改您的asynctask,以便在UI線程上執行的onPreExecute()方法中讀取UI字符串值(如是onPostExecute()方法)。

class SaveProductDetails extends AsyncTask<String, String, String> {

private String name, price, description;

@Override
protected void onPreExecute() {
    super.onPreExecute();
    pDialog = new ProgressDialog(EditProductActivity.this);
    pDialog.setMessage("Saving product ...");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(true);
    pDialog.show();

    name = txtName.getText().toString();
    price = txtPrice.getText().toString();
    description = txtDesc.getText().toString();
}

protected String doInBackground(String... args) {
    //... Use as you would before

我建議看一下像這樣的博客文章,以了解更多關於AsyncTasks,它們如何工作,如何使用它們,包括詳細信息,例如哪個方法在哪個線程上運行。

您可以在工作線程的UI線程上閱讀此使用變量
在您的問題中,您嘗試從后台線程訪問TextView的文本。 為了保持一致,你不應該這樣做,因為它們可能是主線程的可能性(UI線程同時設置TextView)。 為了避免這樣的風景你可以這樣:

class SaveProductDetails extends AsyncTask<String, String, String>{
      //create constructor and pass values of text view in it
      String textViewValue1;
      public SaveProductDetails (String textViewValue1 ){
           this.textViewValue1=textViewValue1
      }

     //other code below
} 

您不需要將值傳遞給execute方法。 將名稱,價格和描述變量設置為全局變量。 要從按鈕上獲取EditTest的值,請單擊以下代碼:

每次您需要單擊按鈕以獲取JSON數據。

btnSave.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View arg0) {
        name = txtName.getText().toString();
        price = txtPrice.getText().toString();
        description = txtDesc.getText().toString();
        new CreateNewProduct().execute();
    }
});

現在,無論您輸入什么,名稱,價格和描述都有其價值。

現在你的CreateNewProduct類看起來像這樣:

class CreateNewProduct extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(NewProductActivity.this);
        pDialog.setMessage("Creating Product..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();

    }

    protected String doInBackground(String... args) {

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

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

        Log.d("Create Response", json.toString());

        try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
                startActivity(i);
                finish();
            }
            else {

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

        return null;
    }

    protected void onPostExecute(String file_url) {
        pDialog.dismiss();
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM