0

我正在使用 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; 
    }

这是日志猫:

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
4

2 回答 2

2

当您调用 asynctask 使用

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

现在在构造函数中

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

还将您的进度对话框初始化移动到构造函数

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

onPreExecute

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

也不是在doInbackground返回结果和onPostExecute关闭对话框中显示 toast 并相应地显示 toast。

于 2013-11-04T06:32:39.163 回答
0

您可以在异步任务中创建处理程序吗?如果在 UI 线程中创建的处理程序(如果使用 MainLooper)发布方法同样 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; 
    }
于 2013-11-04T06:32:44.243 回答