方法getText必须从ui线程调用

时间:2015-10-26 13:49:00

标签: android json

我正在做一个需要将数据从android发送到数据库的应用程序。我正在使用JSONParser。但是当我启动应用程序时遇到问题,它不会将数据发送到服务器。我得到了“String name = inputName.getText()。toString();”的错误。这是它:

protected String doInBackground(String... args) {
            String name = inputName.getText().toString();
            String date = inputDate.getText().toString();
            String time = inputTime.getText().toString();
            String latitude = inputLatitude.getText().toString();
            String longitude = inputLongitude.getText().toString();
            String contacts = inputContacts.getText().toString();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name", name));
            params.add(new BasicNameValuePair("date", date));
            params.add(new BasicNameValuePair("time", time));
            params.add(new BasicNameValuePair("latitude", latitude));
            params.add(new BasicNameValuePair("longitude", longitude));
            params.add(new BasicNameValuePair("contacts", contacts));

            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.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
                    Intent i = new Intent(getApplicationContext(), MainActivity.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();
        }

    }

1 个答案:

答案 0 :(得分:0)

正如错误告诉您的那样,您无法在后台线程上调用getText()。相反,将您的六个getText()调用移动到AsyncTask的构造函数中,或者可能移动到onPreExecute()回调中,以便在主应用程序线程上进行getText()调用。 / p>