取消AsyncTask

时间:2013-08-05 14:59:25

标签: android android-asynctask

点击取消按钮后,我遇到硬盘故障,请看logcat。行ChartingFragment.java:617dialog.dismiss();我不太确定为什么它说空或无法找到那里的对话框。有人看到我在这里失踪了吗?

public class WebPageAsync extends AsyncTask<Void, Integer, Void>{
    ProgressBar progressBar;
    TextView tvLoading, tvPer;
    Dialog dialog;
    Button btnCancel;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = new Dialog(getActivity());
        dialog.setCancelable(false);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.progressdialog);

        progressBar = (ProgressBar) dialog.findViewById(R.id.progressBar1);
        tvLoading = (TextView) dialog.findViewById(R.id.tv1);
        tvPer = (TextView) dialog.findViewById(R.id.tvper);
        btnCancel = (Button) dialog.findViewById(R.id.btncancel);

        btnCancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                objMyTask.cancel(true);
                dialog.dismiss();
            }
        });

        dialog.show();
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        progressBar.setProgress(values[0]);
        tvLoading.setText("Uploading...  " + values[0] + " %");
        tvPer.setText(values[0]+" %");
    }


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

        String userID = null;

        Log.i("PROJECTCARUSO","Fetching User/Posting User");
        userID = postUser();

        Log.i("PROJECTCARUSO","Fetching Charting/Posting Charting");
        if (userID != null) {
            postCharting();
        } 

        return null;
    }


    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);

        dialog.dismiss();

        AlertDialog alert = new AlertDialog.Builder(getActivity())
                .create();

        alert.setTitle("Completed!!!");
        alert.setMessage("Your Task is Completed SuccessFully!!!");
        alert.setButton("Dismiss", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        alert.show();
    }

    protected void postCharting() {
        // Get the data
        int percent = 0;
        Cursor cursorCharting = getActivity().getContentResolver().query(StatusProvider.CONTENT_URI_CHARTING, null, StatusData.KEY_CHARTING_PROC + " is null " , null, null);

        cursorCharting.moveToFirst();

        if (cursorCharting.getCount()>0 && cursorCharting!=null) {
            Log.i("PROJECTCARUSO","Que'd Charting Information Found");
            while (cursorCharting.isAfterLast() == false) 
            {
                if (isCancelled()) {
                    break;
                }
                percent += 100/cursorCharting.getCount();
                Log.i("PROJECTCARUSO","percent: " + percent);
                publishProgress(percent);

                ArrayList<NameValuePair> httpParams;

                httpParams = new ArrayList<NameValuePair>();                        
                httpParams.add(new BasicNameValuePair(StatusData.KEY_CHARTING_DATE, cursorCharting.getString(cursorCharting.getColumnIndex(StatusData.KEY_CHARTING_DATE))));
                httpParams.add(new BasicNameValuePair(StatusData.KEY_CHARTING_TEMPERATURE, cursorCharting.getString(cursorCharting.getColumnIndex(StatusData.KEY_CHARTING_TEMPERATURE))));
                httpParams.add(new BasicNameValuePair(StatusData.KEY_CHARTING_STAMPS, cursorCharting.getString(cursorCharting.getColumnIndex(StatusData.KEY_CHARTING_STAMPS))));
                httpParams.add(new BasicNameValuePair(StatusData.KEY_CHARTING_FERTILE, cursorCharting.getString(cursorCharting.getColumnIndex(StatusData.KEY_CHARTING_FERTILE))));
                httpParams.add(new BasicNameValuePair(StatusData.KEY_CHARTING_PERIOD, cursorCharting.getString(cursorCharting.getColumnIndex(StatusData.KEY_CHARTING_PERIOD))));
                httpParams.add(new BasicNameValuePair(StatusData.KEY_CHARTING_INTERCORSE, cursorCharting.getString(cursorCharting.getColumnIndex(StatusData.KEY_CHARTING_INTERCORSE))));
                httpParams.add(new BasicNameValuePair(StatusData.KEY_CHARTING_CERVIX, cursorCharting.getString(cursorCharting.getColumnIndex(StatusData.KEY_CHARTING_CERVIX))));
                httpParams.add(new BasicNameValuePair(StatusData.KEY_CHARTING_MOOD, cursorCharting.getString(cursorCharting.getColumnIndex(StatusData.KEY_CHARTING_MOOD))));
                httpParams.add(new BasicNameValuePair(StatusData.KEY_CHARTING_HEADACHE, cursorCharting.getString(cursorCharting.getColumnIndex(StatusData.KEY_CHARTING_HEADACHE))));
                httpParams.add(new BasicNameValuePair(StatusData.KEY_CHARTING_TEST, cursorCharting.getString(cursorCharting.getColumnIndex(StatusData.KEY_CHARTING_TEST))));
                httpParams.add(new BasicNameValuePair(StatusData.KEY_CHARTING_ENERGY, cursorCharting.getString(cursorCharting.getColumnIndex(StatusData.KEY_CHARTING_ENERGY))));
                httpParams.add(new BasicNameValuePair(StatusData.KEY_CHARTING_NOTES, cursorCharting.getString(cursorCharting.getColumnIndex(StatusData.KEY_CHARTING_NOTES))));

                try {
                    SERVICE_URL = new URL("http://www.projectcaruso.com/android/com.projectcaruso/naturalfamilyplaning/postCharting.php");
                } catch (MalformedURLException e) {
                    Log.i("PROJECTCARUSO", "MalformedURLException: " + e.toString());
                    e.printStackTrace();
                }


                String response= doPost(SERVICE_URL, httpParams);

                // First split the input String into an array,
                // each element containing a String to be parse as an int
                String[] intsToParse = response.split("\"");

                int[] info = new int[intsToParse.length];
                int _id = 0;

                // Now just parse each part in turn
                for (int i = 0; i < info.length; i++)
                {

                    if (isNumeric(intsToParse[i].toString())) {
                        _id = Integer.parseInt(intsToParse[i]);
                    }
                }

                if (_id >= 0) {
                    Log.i("PROJECTCARUSO", "Insert Successful: " + _id);
                    ContentValues values = new ContentValues();
                    values.put(StatusData.KEY_CHARTING_PROC, "Y");
                    getActivity().getContentResolver().update(StatusProvider.CONTENT_URI_CHARTING, values, " " + StatusData.KEY_CHARTING_DATE + " = " + cursorCharting.getString(cursorCharting.getColumnIndex(StatusData.KEY_CHARTING_DATE)), null);
                }

                cursorCharting.moveToNext();
            } 
        } else {
            Log.i("PROJECTCARUSO","No que'd Charting Information Found");
        }
    }


    protected String postUser() {
        String userID = null;

        //Get the user
        Cursor cursorUser = getActivity().getContentResolver().query(StatusProvider.CONTENT_URI_USER, null, null, null, null);

        cursorUser.moveToFirst();

        if (cursorUser.getCount()>0 && cursorUser!=null) {
            // Record found
            if (cursorUser.getString(cursorUser.getColumnIndex(StatusData.KEY_USER_ID)) == null) {
                Log.i("PROJECTCARUSO","KEY_USER_ID is null, need to upload the user information");
                //this user has logged in with facebook but has not be synced before.
                //Push user information to my online database.

                ArrayList<NameValuePair> httpParams;

                httpParams = new ArrayList<NameValuePair>();                        
                httpParams.add(new BasicNameValuePair("fbid", cursorUser.getString(cursorUser.getColumnIndex(StatusData.KEY_USER_ROWID))));
                httpParams.add(new BasicNameValuePair("social", cursorUser.getString(cursorUser.getColumnIndex(StatusData.KEY_USER_SOCIAL))));
                httpParams.add(new BasicNameValuePair("name", cursorUser.getString(cursorUser.getColumnIndex(StatusData.KEY_USER_NAME))));
                httpParams.add(new BasicNameValuePair("fname", cursorUser.getString(cursorUser.getColumnIndex(StatusData.KEY_USER_FNAME))));
                httpParams.add(new BasicNameValuePair("username", cursorUser.getString(cursorUser.getColumnIndex(StatusData.KEY_USER_USERNAME))));
                httpParams.add(new BasicNameValuePair("email", cursorUser.getString(cursorUser.getColumnIndex(StatusData.KEY_USER_EMAIL))));
                httpParams.add(new BasicNameValuePair("picture", cursorUser.getString(cursorUser.getColumnIndex(StatusData.KEY_USER_PICTURE))));
                httpParams.add(new BasicNameValuePair("other", cursorUser.getString(cursorUser.getColumnIndex(StatusData.KEY_USER_OTHER))));

                try {
                    SERVICE_URL = new URL("http://www.projectcaruso.com/android/com.projectcaruso/naturalfamilyplaning/postUser.php");
                } catch (MalformedURLException e) {
                    Log.i("PROJECTCARUSO", "MalformedURLException: " + e.toString());
                    e.printStackTrace();
                }

                String response = doPost(SERVICE_URL, httpParams);


                // First split the input String into an array,
                // each element containing a String to be parse as an int
                String[] intsToParse = response.split("\"");

                int[] info = new int[intsToParse.length];
                int _id = 0;

                // Now just parse each part in turn
                for (int i = 0; i < info.length; i++)
                {

                    if (isNumeric(intsToParse[i].toString())) {
                        _id = Integer.parseInt(intsToParse[i]);
                    }
                }

                if (_id > 0) {

                    Log.i("PROJECTCARUSO", "Found id: " + _id);
                    ContentValues values = new ContentValues();
                    values.put(StatusData.KEY_USER_ID, _id);
                    getActivity().getContentResolver().update(StatusProvider.CONTENT_URI_USER, values, " 1 = 1 ", null);


                    Cursor cursorUser2 = getActivity().getContentResolver().query(StatusProvider.CONTENT_URI_USER, null, null, null, null);

                    cursorUser2.moveToFirst();

                    userID = cursorUser2.getString(cursorUser2.getColumnIndex(StatusData.KEY_USER_ID));
                }

            } else {
                while (cursorUser.isAfterLast() == false) 
                {
                    //this User is already set up to send/receive charting updates 
                    Log.i("PROJECTCARUSO","User found and has been connected before");
                    userID = cursorUser.getString(cursorUser.getColumnIndex(StatusData.KEY_USER_ID));

                    cursorUser.moveToNext();
                } 
            }
        } else {
            //This user has not been set up to send/receive charting updates
            Log.i("PROJECTCARUSO","User profile not set up, please login via facebook");
            Log.i("PROJECTCARUSO", "userID: " + userID);
        }
        return userID;
    }

    protected String doPost(URL url,ArrayList<NameValuePair> httpParams) {
        String response = null;

        try {
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getQuery(httpParams));
            writer.close();
            os.close();

            conn.connect();

            //start listening to the stream
            Scanner inStream = new Scanner(conn.getInputStream());

            //process the stream and store it in StringBuilder
            while(inStream.hasNextLine())
            response+=(inStream.nextLine());

            Log.i("PROJECTCARUSO","response: " + response);

        } catch (ProtocolException e) {
            Log.i("PROJECTCARUSO", "Error: " + e.toString());
        }

         catch (IOException e) {
             Log.i("PROJECTCARUSO", e.toString());
        }

        return response;
    }

    public boolean isNumeric(String str)  {  
          try  
          {  
            double d = Double.parseDouble(str);  
          }  
          catch(NumberFormatException nfe)  
          {  
            return false;  
          }  
          return true;  
        }

    private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;

        for (NameValuePair pair : params)
        {
            if (pair.getValue() == null) {
                Log.i("PROJECTCARUSO", "Null value pair for: " + pair.getName());
            } else {

                if (first)
                    first = false;
                else
                    result.append("&");
                    result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
                    result.append("=");
                    result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
                    }
            }

            return result.toString();
        }

logcat的:

08-05 09:54:45.182: E/AndroidRuntime(317): FATAL EXCEPTION: main
08-05 09:54:45.182: E/AndroidRuntime(317): java.lang.NullPointerException
08-05 09:54:45.182: E/AndroidRuntime(317):  at com.projectcaruso.naturalfamilyplaning.ChartingFragment$WebPageAsync$1.onClick(ChartingFragment.java:617)
08-05 09:54:45.182: E/AndroidRuntime(317):  at android.view.View.performClick(View.java:4192)
08-05 09:54:45.182: E/AndroidRuntime(317):  at android.view.View$PerformClick.run(View.java:17254)
08-05 09:54:45.182: E/AndroidRuntime(317):  at android.os.Handler.handleCallback(Handler.java:615)
08-05 09:54:45.182: E/AndroidRuntime(317):  at android.os.Handler.dispatchMessage(Handler.java:92)
08-05 09:54:45.182: E/AndroidRuntime(317):  at android.os.Looper.loop(Looper.java:137)
08-05 09:54:45.182: E/AndroidRuntime(317):  at android.app.ActivityThread.main(ActivityThread.java:4950)
08-05 09:54:45.182: E/AndroidRuntime(317):  at java.lang.reflect.Method.invokeNative(Native Method)
08-05 09:54:45.182: E/AndroidRuntime(317):  at java.lang.reflect.Method.invoke(Method.java:511)
08-05 09:54:45.182: E/AndroidRuntime(317):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
08-05 09:54:45.182: E/AndroidRuntime(317):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
08-05 09:54:45.182: E/AndroidRuntime(317):  at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:1)

什么是objMyTask?我认为这是触发null的{​​{1}}。

如果NullPointerExceptionobjMyTask的实例,我强烈建议您使用WebPageAsync代替WebPageAsync.this.cancel(true)