这是我的代码。当我点击我的应用徽标时,在启动画面之后,这是首先从意图调用的类。但是,在加载选项卡后,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-19 19:03:01.264:E / AndroidRuntime(1138):引起:java.lang.RuntimeException:无法在未调用Looper.prepare()的线程内创建处理程序
有什么问题?
答案 0 :(得分:1)
您正在尝试在后台线程中执行涉及UI(ListView lv = (ListView) findViewById(R.id.user_list);
)的操作。你不能做这个。您可以在后台处理信息,然后将其传递回UI线程并更新UI
答案 1 :(得分:1)
正如pyrodante所说,你正在尝试修改UI,而不是在UI线程上。如果要从非UI线程修改UI,可以使用runOnUiThread()函数。也就是说,对您的问题有更好的解决方案。你真的应该使用Loader。它们基本上是为了准确地解决你想要做的事情。请注意,即使您正在设计3.0之前的应用,您仍然可以通过Android Support package访问加载器。