获取doInBackground AsyncTask中的EditText值

时间:2016-04-21 07:42:14

标签: android android-studio android-asynctask android-edittext

我想在doInBackground AsyncTask中传递Edittext的值,我试着这段代码:

    protected void onCreate(Bundle savedInstanceState) {
    ID = (EditText) findViewById(R.id.ID);
    lname = (EditText) findViewById(R.id.lname);
    fname = (EditText) findViewById(R.id.fname);
    phone = (EditText) findViewById(R.id.phone);
    H = ID.getText().toString();
    Q = lname.getText().toString();
    C = fname.getText().toString();
    Ls = phone.getText().toString();

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

        public void onClick(View arg0) {
        new CreateNewexercise().execute(H,Q,C,Ls);
    }
    });
}

class CreateNewexercise extends AsyncTask<String, String, String> {
    /**
     * Creating exercise
     */
    protected String doInBackground(String... args) {
        //getting field's text
        id=args[0];
        ln=args[1];
        fn=args[2];
        p=args[3];

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("ID", id));
        params.add(new BasicNameValuePair("lname", ln));
        params.add(new BasicNameValuePair("fname",fn));
        params.add(new BasicNameValuePair("phone", p));
        Log.d("ID", "Value: " + id);
        Log.d("lname", "Value: " + ln);
        Log.d("fname", "Value: " + fn);
        Log.d("phone", "Value: " + p);

我将参数作为参数传递,但它总是空的我不知道为什么?

有人可以告诉我我做错了吗?

1 个答案:

答案 0 :(得分:1)

您正在使用EditText方法中的onCreate加载文字,而不是在点击按钮时点播。从getText()外部删除调用OnClickListener的行,并将其添加到内部。

addbtn.setOnClickListener(new View.OnClickListener() {
    public void onClick(View arg0) {
        H = ID.getText().toString();
        Q = lname.getText().toString();
        C = fname.getText().toString();
        Ls = phone.getText().toString();
        new CreateNewexercise().execute(H,Q,C,Ls);
    }
});