我試圖從Web服務獲取用戶名和用戶ID,我試圖改變他的價值取決於價值我從服務器獲得它,當我嘗試更改textview的onCreate函數外部值我有這樣的錯誤:
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();
}
這是半自我說明的。和[搜索](http://stackoverflow.com/search?q=%5Bandroid%5D+CalledFromWrongThreadException)給你休息。 – keyser
可能重複的[CalledFromWrongThreadException](http://stackoverflow.com/questions/3413544/calledfromwrongthreadexception) – keyser