當我點擊應用程序的logo,閃屏後,就會從intent中調用的第一個類。但是當tab加載後, onPreExecute() 一旦執行,應用程序就奔潰了。
public class HomeActivity extends Activity{
private static final String dialog = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_main_tab_home);
new HomeDownloadPage().execute();
}
public class HomeDownloadPage extends AsyncTask<String,Void,String>{
private final ProgressDialog dialog = new ProgressDialog(HomeActivity.this);
protected void onPreExecute() {
this.dialog.setMessage("Have Paitence! ");
this.dialog.show();
}
@Override
protected String doInBackground(String... params) {
User user = null;
try {
user = new User("4eeb");
user.getList();
/*
* Custom adapter
* */
ArrayList<User> users = new ArrayList<User>();
for(User u : user.following){
users.add(u);
}
ListView lv = (ListView) findViewById(R.id.user_list);
final UserFollowingListAdapter csl = new UserFollowingListAdapter(HomeActivity.this,R.layout.user_list,users,this);
OnItemClickListener listener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Object o = csl.getItem(position);
setTitle(parent.getItemAtPosition(position).toString());
}
};
lv.setAdapter(csl);
lv.setOnItemClickListener(listener);
/*
* Onclick listener
* */
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Intent i = new Intent("com.list.SEARCH");
Toast.makeText(HomeActivity.this, "rowitem clicked", Toast.LENGTH_LONG).show();
// TODO Auto-generated method stub
}
});
} catch (Exception e) {
showError();
}
return null;
}
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
}
}
public void showError(){
new AlertDialog.Builder(HomeActivity.this)
.setTitle(" Oops , Server down :( ")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
//
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Do nothing.
}
}).show();
}
}
在 doInBackground() 函數處得到錯誤。
確切的錯誤:
01-27 19:03:01.264: E/AndroidRuntime(1138): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
問題出在哪呢?
你正在試圖實現的功能在一個後台線程中包括 UI(ListView lv = (ListView)
findViewById(R.id.user_list);)
你可以在後台處理信息,然後傳回UI線程,更新UI.