AsyncTask和Toast不是在onPostExecute上创建的

时间:2013-03-04 17:04:39

标签: android

我有一个AsyncTask类。当我有一个错误,我想看到一个祝酒词。这是我的AsynTask类:

private GetUtenti threadutenti;
threadutenti= (GetUtenti) new GetUtenti(this.getActivity()).execute();

这是我的班级:

class GetUtenti extends AsyncTask<Void, Void, Void> {
    private Context context;
    private boolean errore = false; 
    private Database db;

    public GetUtenti(Context context){
        this.context=context;
    }
    @Override
    protected void onPostExecute(Void result) {
        db.disconnetti();
        if (errore) {
             Toast.makeText(context, "error!", Toast.LENGTH_SHORT)
              toast.show();
        }
        else{
            setListaUtenti();
        }
        bProgresso.dismiss();           
    }
    @Override
    protected void onPreExecute() {
        db = new Database(.....);
    }
    @Override
    protected Void doInBackground(Void... params) {
        db.connetti();
        if(!db.isConnesso()){           
            errore= true;               
        } else {
            utenti.clear();
            utenti = Utente.getUtenti(db);              
        }
    return null;
    }
}

当我想看到我的Toast Message时,我有这个:

03-04 17:41:06.534: E/AndroidRuntime(13622): FATAL EXCEPTION: main
03-04 17:41:06.534: E/AndroidRuntime(13622): java.lang.RuntimeException: This Toast was not created with Toast.makeText()
03-04 17:41:06.534: E/AndroidRuntime(13622):    at android.widget.Toast.setText(Toast.java:282)
03-04 17:41:06.534: E/AndroidRuntime(13622):    at com.unipg.utente.ListUtente$GetUtenti.onPostExecute(ListUtente.java:145)

为什么?

2 个答案:

答案 0 :(得分:5)

尝试类似:

if (errore) {
    Toast toast = Toast.makeText(context, "error!", Toast.LENGTH_SHORT);
    toast.show();
}

答案 1 :(得分:3)

此行中的错误

 Toast.makeText(context, "error!", Toast.LENGTH_SHORT)  no semicolon

无需使用双重步骤,即使用toast对象引用然后显示。你可以像这样直接打电话

 Toast.makeText(context, "error!", Toast.LENGTH_SHORT).show();