错误:“必须从UI线程调用方法getText(),当前推断的线程是worker." [英] Error: "Method getText() must be called from the UI thread, currently inferred thread is worker."
问题描述
在项目上工作时,我在进行以下活动时收到错误消息. 1. Login.java 在下面的代码行上.
While working on the project i get an error on following Activity. 1. Login.java on following Line of code.
行:字符串用户名= user.getText().toString();" 错误:必须从UI线程调用方法getText(),当前推断的线程是worker."
Line: "String username = user.getText().toString();" Error: "Method getText() must be called from the UI thread, currently inferred thread is worker."
这是我的整个活动代码.
This is my whole Activity Code.
package com.example.mysqltest;
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.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends Activity implements OnClickListener {
private EditText user, pass;
private Button mSubmit, mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//php login script location:
//localhost :
//testing on your device
//put your local ip instead, on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1
// private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/login.php";
//testing from a real server:
//private static final String LOGIN_URL = "http://www.example.com/webservice/login.php";
//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
public static String username;
public static String password;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
//setup input fields
user = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
//setup buttons
mSubmit = (Button) findViewById(R.id.login);
mRegister = (Button) findViewById(R.id.register);
//register listeners
mSubmit.setOnClickListener(this);
mRegister.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.login:
username = user.getText().toString();
password = pass.getText().toString();
new AttemptLogin().execute();
break;
case R.id.register:
Intent i = new Intent(this, Register.class);
startActivity(i);
break;
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
boolean failure = false;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
Intent i = new Intent(Login.this, ReadComments.class);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} 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 product deleted
pDialog.dismiss();
if (file_url != null) {
Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
推荐答案
除非我不知道有什么变化,否则应该不会有问题. UI元素无法从后台进行更新,但是访问其getter从来都不是问题.
Unless something has changed that I'm not aware of, that shouldn't be a problem. UI elements can't be updated from the background but accessing their getters has never been an issue.
无论如何,您可以通过在AsyncTask中添加一个构造函数来解决此问题,该构造函数将接受两个String,然后在创建任务时将它们发送给他们.
Anyway, you can get around this by adding a constructor to your AsyncTask which would take the two Strings then send them when creating your task.
private class Login extends AsyncTask<String, String, String>{
// member variables of the task class
String uName, pwd
public AttemptLogin(String userName, String password) {
uName = userName;
pwd = password;
}
@Override
protected String doInBackground(String... args) {...}
并将其传递到您的onClick()
and pass them in your onClick()
case R.id.login:
// execute method invokes doInBackground() where we open a Http URL connection using the given Servlet URL
//and get output response from InputStream and return it.
// pass them here
new AttemptLogin(uname.getText().toString(), password.getText().toString()).execute();
break;
这篇关于错误:“必须从UI线程调用方法getText(),当前推断的线程是worker."的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!