开发者

I can't initialize component in asynctask background function

How would I call this function in asynctask?

void somefunc()
{
tr1 = (TableRow) new TableRow(this);
//error
txt1=new TextView(this);
txt9.setText(strinarr[0]);

tr1.addView(txt1);
tl.addView(tr1,new TableLayout.LayoutParams(layoutParams));
}


class SaveAdDetail extends AsyncTask<Void, String, Void> 
{
@Override
public void onPreExecute() 
{
super.onPreExecute();
Progdialog = ProgressDialog.show(demotable.this, "", "Please Wait...", true);
Progdialog.show();
}
@Override
public Void doInBackground(Void... unused) 
{开发者_运维百科
try 
{somefunc();} 
catch (Exception e) 
{strdata="Error";}
return null;
}
@Override
public void onPostExecute(Void unused) 
{
Progdialog.dismiss();
if(strdata.equals("Error"))
{Toast(strdata);}
else
{
Toast("asdasdasd");
}
}
}


You have a choice : use handlers or call directly. In both cases you should pass a reference to the constructor of AsyncTask. onPostExecute() is called on the UI thread, so you can call the method directly on the reference of your activity.

private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case Constants.TASK_FINISHED:
                somefunc();
                break;                
        }
    }
};

SaveAdDetail task = new SaveAdDetail(handler);
task.execute();

// in your SaveAdDetail:

@Override
public void onPostExecute(Void unused) {
   Progdialog.dismiss();
   handler.obtainMessage(Constants.TASK_FINISHED).sendToTarget();
}


I would use a Handler. Here is an example: http://developer.android.com/resources/articles/timed-ui-updates.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜