无法在DialogFragment中的AsyncTask中显示Toast

时间:2013-11-04 06:12:03

标签: android android-asynctask toast android-dialogfragment dialogfragment

我正在使用DialogFragment显示一个简单的表单,然后将其发布到远程服务器并发回成功/失败代码。

但是,每当我想在发生错误时显示Toast时,我会得到一个异常,其中getActivity()返回null。知道为什么会这样吗?

这是代码摘要:

private class UploadNewGroupToServer extends AsyncTask<String, Void, Void>
{

    ProgressDialog createGroupProgressDialog;


    @Override
    protected Void doInBackground(String... params)
    {

        getActivity().runOnUiThread(new Runnable() 
        {
           public void run() 
           {
               createGroupProgressDialog = new ProgressDialog(getActivity());
               createGroupProgressDialog.setTitle("Creating group...");
               createGroupProgressDialog.show();
           }
        });


        String encodedImage = params[0];
        String groupTitle = params[1];
        String groupDesc = params[2];

        //Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(URL_API_CREATE_GROUP);

        try
        {
            // Add data
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            if(encodedImage != null)
            {
                nameValuePairs.add(new BasicNameValuePair("picture", encodedImage));
            }
            nameValuePairs.add(new BasicNameValuePair("title", groupTitle));
            nameValuePairs.add(new BasicNameValuePair("desc", groupDesc));
            nameValuePairs.add(new BasicNameValuePair("token", "MY_TOKEN_HERE!"));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            Log.d("APP", "Going to execute ");
            final String responseBody = httpclient.execute(httppost, responseHandler);
            Log.d("APP", "Back from execute, responseBody is " + responseBody);


            //More business logic here
            //   . . . . .

            throw new Exception(); //simulate an error

        } catch (final Exception e)
        {
            Log.d("APP", "Exception es " + e.getMessage());
            createGroupProgressDialog.dismiss();

            getActivity().runOnUiThread(new Runnable()    //App dies here!
            {
               public void run() 
               {
                   Toast.makeText(getActivity(), "Error!", Toast.LENGTH_LONG).show(); 
               }
            }); 

        }

        return null; 
    }

这是logcat:

11-04 00:16:18.414: E/AndroidRuntime(7229): Caused by: java.lang.NullPointerException
11-04 00:16:18.414: E/AndroidRuntime(7229):     at com.myapp.android.GroupCreateDialogFragment$UploadNewGroupToServer.doInBackground(GroupCreateDialogFragment.java:204)
11-04 00:16:18.414: E/AndroidRuntime(7229):     at com.myapp.android.GroupCreateDialogFragment$UploadNewGroupToServer.doInBackground(GroupCreateDialogFragment.java:1)
11-04 00:16:18.414: E/AndroidRuntime(7229):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-04 00:16:18.414: E/AndroidRuntime(7229):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-04 00:16:18.414: E/AndroidRuntime(7229):     ... 4 more

2 个答案:

答案 0 :(得分:2)

当您调用asynctask时使用

new UploadNewGroupToServer(getActivity()).execute();. 

现在在构造函数

Context mContext; 
pulic void UploadNewGroupToServer(Context context)
{
mContext = context;
} 

还将progressdialog初始化移动到构造函数

pulic void UploadNewGroupToServer(Context context)
{
 createGroupProgressDialog = new ProgressDialog(context);
 createGroupProgressDialog.setTitle("Creating group..."); 
} 

onPreExecute

public void onPreExecute()
{
     super.onPreExecute();
     createGroupProgressDialog.show();
}  

而不是在doInbackground返回结果和onPostExecute关闭对话框中显示吐司,并相应地显示吐司。

答案 1 :(得分:0)

您可以在异步任务中创建处理程序吗?如果在UI线程中创建的处理程序(如果使用MainLooper)post方法同样runOnUiThread。

private class UploadNewGroupToServer extends AsyncTask<String, Void, Void>
{

    ProgressDialog createGroupProgressDialog;
    Handler handler;    


    protected void onPreExecute(){
      handler = new Handler();
    }


    @Override
    protected Void doInBackground(String... params)
    {

        handler.post(new Runnable() 
        {
           public void run() 
           {
               createGroupProgressDialog = new ProgressDialog(getActivity());
               createGroupProgressDialog.setTitle("Creating group...");
               createGroupProgressDialog.show();
           }
        });


        String encodedImage = params[0];
        String groupTitle = params[1];
        String groupDesc = params[2];

        //Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(URL_API_CREATE_GROUP);

        try
        {
            // Add data
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            if(encodedImage != null)
            {
                nameValuePairs.add(new BasicNameValuePair("picture", encodedImage));
            }
            nameValuePairs.add(new BasicNameValuePair("title", groupTitle));
            nameValuePairs.add(new BasicNameValuePair("desc", groupDesc));
            nameValuePairs.add(new BasicNameValuePair("token", "MY_TOKEN_HERE!"));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            Log.d("APP", "Going to execute ");
            final String responseBody = httpclient.execute(httppost, responseHandler);
            Log.d("APP", "Back from execute, responseBody is " + responseBody);


            //More business logic here
            //   . . . . .

            throw new Exception(); //simulate an error

        } catch (final Exception e)
        {
            Log.d("APP", "Exception es " + e.getMessage());
            createGroupProgressDialog.dismiss();

            handler.post(new Runnable()    //App dies here!
            {
               public void run() 
               {
                   Toast.makeText(getActivity(), "Error!", Toast.LENGTH_LONG).show(); 
               }
            }); 

        }

        return null; 
    }