Java 方法 getText() 必须从 UI 线程调用(Android Studio)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32011996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Method getText() must be called from the UI Thread (Android Studio)
提问by Daniele Oriana
I'm trying to create a login for an application. However I have a problem.
我正在尝试为应用程序创建登录名。但是我有一个问题。
This is my code:
这是我的代码:
package com.forgetmenot.loginregister;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText uname, password;
Button submit;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
private static final String TAG = "Login";
JSONObject json;
private static String url_login = "http://localhost:8080/ForgetMeNotApplication/Login";
//JSONArray incoming_msg = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewsById();
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// 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.
new Login().execute();
}
});
}
private void findViewsById() {
uname = (EditText) findViewById(R.id.txtUser);
password = (EditText) findViewById(R.id.txtPass);
submit = (Button) findViewById(R.id.login);
}
private class Login extends AsyncTask<String, String, String>{
@Override
protected String doInBackground(String... args) {
// Getting username and password from user input
String username = uname.getText().toString();
String pass = password.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("u",username));
params.add(new BasicNameValuePair("p",pass));
json = jParser.makeHttpRequest(url_login, "GET", params);
String s=null;
try {
s= json.getString("info");
Log.d("Msg", json.getString("info"));
if(s.equals("success")){
Intent login = new Intent(getApplicationContext(), home.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
finish();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Android studio says that method getText()
must be called from the UI Thread at the istructions: uname.getText().toString();
and password.getText().toString();
Possible solutions??
Android studio 说getText()
必须从 UI 线程在指令中调用该方法:uname.getText().toString();
和 password.getText().toString();
可能的解决方案?
采纳答案by dieter_h
Try to pass Your values to Login AsyncTask
via execute(param1, param1, ..., paramN)
method:
尝试将您的值传递给Login AsyncTask
viaexecute(param1, param1, ..., paramN)
方法:
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
String username = uname.getText().toString();
String pass = password.getText().toString();
new Login().execute(username, pass);
}
});
}
private void findViewsById() {
uname = (EditText) findViewById(R.id.txtUser);
password = (EditText) findViewById(R.id.txtPass);
submit = (Button) findViewById(R.id.login);
}
private class Login extends AsyncTask<String, String, String>{
@Override
protected String doInBackground(String... args) {
// Getting username and password from user input
String username = args[0];
String pass = args[1];
回答by Rustam
make username
and pass
login
class variable and override onPreExcecute()
and do this:
makeusername
和pass
login
class 变量并覆盖onPreExcecute()
并执行以下操作:
@Override
protected void onPreExecute() {
username = uname.getText().toString();
pass = password.getText().toString();
}
回答by Leon Joosse
The exception is thrown because doInBackground()
is invoked from a background thread. I would add two String parameters to the constructor of your Login
class.
抛出异常是因为它doInBackground()
是从后台线程调用的。我会向您的Login
类的构造函数添加两个 String 参数。
I would like to advise you to gain more knowledge about AsyncTasks
and Threading on Android. For example, there is a page in the official docs: http://developer.android.com/guide/components/processes-and-threads.html.
我想建议您获得更多AsyncTasks
关于 Android 和线程的知识。例如,官方文档中有一个页面:http: //developer.android.com/guide/components/processes-and-threads.html。
You might also take a look at this course: https://www.udacity.com/course/developing-android-apps--ud853. You can learn a lot of basics of the Android framework.
你也可以看看这个课程:https: //www.udacity.com/course/developing-android-apps--ud853。你可以学习很多Android框架的基础知识。
回答by Vinny K
You're accessing the UI thread from a background thread here:
您正在从后台线程访问 UI 线程:
String username = uname.getText().toString();
String pass = password.getText().toString();
What you want to do is just pass the username/password strings in to your background task constructor or you could pass them directly to the execute method. I prefer to define them in to the constructor if they are going to be required (like yours are).
您想要做的只是将用户名/密码字符串传递给后台任务构造函数,或者您可以将它们直接传递给 execute 方法。如果需要它们(就像你的一样),我更喜欢将它们定义到构造函数中。
Define your LoginTask like
定义您的 LoginTask 像
String uname;
String password;
public Login(String username, String password({
this.uname = username;
this.password = password;
}
Then in doInBackground() you use the members instead.
然后在 doInBackground() 中使用成员。
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("u",this.username));
params.add(new BasicNameValuePair("p",this.pass));
json = jParser.makeHttpRequest(url_login, "GET", params);
Edit - so then your new Login().execute() call would look more like this
编辑 - 那么你的新 Login().execute() 调用看起来更像这样
new Login(uname.getText().toString(), password.getText().toString()).execute();
回答by codeMagic
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.
除非发生了我不知道的变化,否则这应该不是问题。UI 元素无法从后台更新,但访问它们的 getter 从来都不是问题。
Anyway, you can get around this by adding a constructor to your AsyncTask
which would take the two String
s then send them when creating your task.
无论如何,您可以通过向您添加一个构造函数来解决此问题,该构造函数AsyncTask
将String
在创建任务时使用两个s 然后发送它们。
private class Login extends AsyncTask<String, String, String>{
// member variables of the task class
String uName, pwd
public Login(String userName, String password) {
uName = userName;
pwd = password;
}
@Override
protected String doInBackground(String... args) {...}
and pass them in your onClick()
并将它们传递给你 onClick()
@Override
public void onClick(View arg0) {
// 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 Login(uname.getText().toString(), password.getText().toString()).execute();
}