错误:必须从UI线程调用getText

时间:2016-03-13 19:16:40

标签: java android json listview

我正在尝试将名称,电话和电子邮件输入到mysql数据库中。我在doInBackground方法中遇到错误,需要从ui线程调用getText。

这是我的用户详细信息文件:

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 UserDetails extends Activity {

// Progress Dialog
private ProgressDialog pDialog;

JSONParser1 jsonParser = new JSONParser1();
EditText inputName;
EditText inputPhone;
EditText inputEmail;

// url to create new product
private static String url_create_product = "http://bookit.net16.net//book.php";

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

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

    // Edit Text
    inputName = (EditText) findViewById(R.id.inputName);
    inputPhone = (EditText) findViewById(R.id.inputPhone);
    inputEmail = (EditText) findViewById(R.id.inputEmail);


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

    // 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(UserDetails.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 phone = inputPhone.getText().toString();
    String email = inputEmail.getText().toString();



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

        // getting JSON Object
        // Note that create product url accepts POST method
        JSONObject json = JSONParser1.makeHttpRequest(url_create_product,
                "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


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

}

}

3 个答案:

答案 0 :(得分:1)

对视图的任何访问都必须在UI线程上完成,而不是在另一个线程或AsyncTask上完成。将它们作为参数传递,而不是在doInBackground中查询它们。在onPreExecute中请求它们是完全可以的。

答案 1 :(得分:0)

创建一个类并扩展它的Application并在其上定义一个Handler。

public class Global extends Application{
    public static Handler HANDLER = new Handler();
    onCreate(){
    }
}

然后代码使用:

Global.HANDLER.post(new Runable(){
     // do anythin with UI you like
});

答案 2 :(得分:0)

在调用异步任务并将其作为参数传递之前,不要从doInBackground获取字符串。

btnCreateProduct.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            // creating new product in background thread
               String name = inputName.getText().toString();
                String phone = inputPhone.getText().toString();
                String email = inputEmail.getText().toString();

                new CreateNewProduct(name,phone,email).execute();
        }
    });

在Async任务中创建构造函数

class CreateNewProduct extends AsyncTask<String, String, String> {
        String name,  phone,  email;

        public CreateNewProduct(String param1, String param2, String param3) {
            name= param1;
            phone =param2;
            email = param3;
        }
   @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(UserDetails.this);
        pDialog.setMessage("Creating Product..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Creating product
     * */
    protected String doInBackground(String... args) {

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

        // getting JSON Object
        // Note that create product url accepts POST method
        JSONObject json = JSONParser1.makeHttpRequest(url_create_product,
                "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


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

}