當我的baseadapter的getView方法中單擊一個按鈕時,我無法在asynctask類的preexecute方法中顯示進度對話框。當pDialog.show()方法ID調用我得到「無法添加窗口異常」例外。當我刪除preexecute方法時,它工作正常。有人可以解釋爲什麼發生這種情況。無法添加窗口異常時,在getView方法的BaseAdapter中的按鈕單擊事件中使用Asynctask?
這裏是我的代碼:
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Please wait..");
pDialog.setCancelable(false);
pDialog.show();
}
這是我的按鈕單擊事件代碼:
holder.buttonid.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
try
{
new MyAsyncTask().execute();
} catch (Exception e)
{
e.printStackTrace();
}
}
});
這是我BadeAdapter類
公共類FriendListAdapter延伸BaseAdapter {
private Context context;
private LayoutInflater inflater=null;
private ArrayList<MyObject> mDisplayedValues;
static class ViewHolder
{
ImageView img_friend;
TextView tvname_friend;
Button btnstatus_friend;
}
public FriendListAdapter(Context context, ArrayList<MyObject> arrayList) {
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.context = context;
this.mDisplayedValues = arrayList;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mDisplayedValues.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view =convertView;
ViewHolder holder = null;
if(convertView==null)
{
view = inflater.inflate(R.layout.inflate_view,parent,false);
holder = new ViewHolder();
holder.buttonid= (Button)view.findViewById(R.id.btnid);
view.setTag(holder);
}
else
{
holder = (ViewHolder)view.getTag();
}
try
{
holder.buttonid.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
try
{
new MyAsyncTask().execute();
} catch (Exception e)
{
e.printStackTrace();
}
}
});
} catch (Exception e)
{
e.printStackTrace();
}
return view;
}
private class MyAsyncTask extends AsyncTask<String, Void, Void> {
private ProgressDialog pDialog = null;
private boolean hasExceptionOccured = false;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Please wait..");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
//Intent to next activity
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
}
}
}
上下文的作用是什麼? – Piyush
你在getView()方法中調用你的** MyAsyncTask **嗎? – Piyush
不,我在getView()方法後在BaseAdapter中調用它。 – Anirudh