【发布时间】:2014-05-02 20:04:53
【问题描述】:
我正在尝试从 Web 服务获取用户名和用户 ID,并且我尝试根据我从服务器获取的值更改他的值,当我尝试在 onCreate 函数之外更改 textview 值时出现此错误:
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
Profile.java
public class Profile extends Activity {
TextView mymoUserName;
TextView mymoID;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.profile);
getActionBar().hide();
mymoUserName = (TextView)findViewById(R.id.profMymoUserName);
mymoID = (TextView)findViewById(R.id.profMymoID);
getUserInfo();
}
protected void getUserInfo()
{
Thread t = new Thread() {
public void run() {
Looper.prepare();
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
String URL = "MY_URL";
try {
HttpPost post = new HttpPost(URL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("section", "API" ));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = client.execute(post);
if(response!=null)
{
String res = EntityUtils.toString(response.getEntity());
JSONObject result = new JSONObject(res);
Toast.makeText(getBaseContext(), res , Toast.LENGTH_LONG).show();
String username = result.getString("username");
mymoUserName.setText(username);
String mymoId = result.getString("mymo_id");
mymoID.setText(mymoId);
}
} catch(Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
Looper.loop();
}
};
t.start();
}
@Override
public void onBackPressed()
{
finish();
}
【问题讨论】:
-
这是半不言自明的。 searching 给你剩下的。
标签: android web-services textview