使用try和catch android处理Asynctask JSON错误

时间:2014-04-23 03:46:57

标签: android json exception-handling android-asynctask

我的应用程序出现问题,当我的应用程序刷新或加载缓慢的互联网连接时...活动总是销毁,或者#34;不幸(姓名)停止"我怎样才能阻止Force关闭我的活动。我使用Asynctask和JSON文件从PHP中获取数据。这是我的代码:

    package com.example.this;


    import android.app.Activity;
    import android.app.ActivityManager;
    import android.app.AlertDialog;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.KeyEvent;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import java.util.ArrayList;
    import java.util.HashMap;

    public class Frontpane extends Activity {

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)  {
        if ( keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

            onBackPressed();
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {

        return;
    }

    Button Loginbutton;
    Button exitButton;

    EditText username=null;
    EditText password=null;
    EditText checker;

    String Username1;
    String Password1;

    /** For database connection**/
        private static String url = "http://1.1.1.1/radarMonitoring/api/retrieveacc.php";
        private static final String TAG_REGISTEREDACCOUNTS = "RegisteredAccounts";
        private static final String TAG_ACCNUM = "Acc_Num";
        private static final String TAG_USEREG = "User_NameReg";
        private static final String TAG_PASSREG = "Pass_WordReg";
        JSONArray accnt = null;
        String cntb;
        String cnta;
        String can;
        String cbn;
        int usncnt;
        int pswcnt;
        ArrayList<HashMap<String, String>> accntList;


     /** For database connection**/

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.front);
        Toast.makeText(Frontpane.this, "Please Login to Continue.", Toast.LENGTH_SHORT).show();
        exitButton = (Button) findViewById(R.id.button);
        username=(EditText)findViewById(R.id.username);
        password=(EditText)findViewById(R.id.password);
       // checker=(EditText)findViewById(R.id.editText1);
        exitButton.setOnClickListener(button);

        addButtonListener();
        /**array of usernames and pw **/
        accntList = new ArrayList<HashMap<String, String>>();
        /**array of usernames and pw **/


    }

    private class GetContacts extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();
            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    accnt = jsonObj.getJSONArray(TAG_REGISTEREDACCOUNTS);

                    // looping through All Contacts
                    for (int i = 0; i < accnt.length(); i++) {
                        int l;
                        JSONObject c = accnt.getJSONObject(i);

                       // String an = c.getString(TAG_ACCNUM);
                        String unr = c.getString(TAG_USEREG);
                       // String pwr = c.getString(TAG_PASSREG);

                        // tmp hashmap for single contac
                        HashMap<String, String> acc = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                    //   acc.put(TAG_ACCNUM, an);
                       acc.put(TAG_USEREG, unr);
                     //   acc.put(TAG_PASSREG, pwr);

                      if(unr.equals(Username1)){
                           usncnt = i;
                           can = unr;

                       }   
                        // adding contact to contact list
                       accntList.add(acc);



                    }
                } catch (JSONException e) {
                    e.printStackTrace();

                }
            } else {

               Log.e("ServiceHandler", "Couldn't get any data from the url");
                Toast.makeText(Frontpane.this,"Please Check Your Internet Connection", Toast.LENGTH_SHORT).show();

            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog

            /**
             * Updating parsed JSON data into ListView
             * */

            cnta = can;
            if(Username1.isEmpty()==false){
                if(Password1.isEmpty()){
                    Toast.makeText(Frontpane.this, "Please Enter Password!", Toast.LENGTH_SHORT).show();
                    username.setText(null, null);
                    password.setText(null, null);

                }
                else{
                    if(cnta!=null){
                    new GetPAss().execute();
                    }
                    else{
                        Toast.makeText(Frontpane.this, "Not Registered or Check your Internet Connection..", Toast.LENGTH_SHORT).show();
                        username.setText(null, null);
                        password.setText(null, null);
                    }

                }
            }
            else{


                    Toast.makeText(Frontpane.this, "Please Enter Username!", Toast.LENGTH_SHORT).show();
                    username.setText(null, null);
                    password.setText(null, null);

            }

        }

    }
    private class GetPAss extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();
            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    accnt = jsonObj.getJSONArray(TAG_REGISTEREDACCOUNTS);

                    // looping through All Contacts
                    for (int i = 0; i < accnt.length(); i++) {
                        int l;
                        JSONObject c = accnt.getJSONObject(i);

                       // String an = c.getString(TAG_ACCNUM);
                        //String unr = c.getString(TAG_USEREG);
                        String pwr = c.getString(TAG_PASSREG);

                        // tmp hashmap for single contac
                        HashMap<String, String> acc = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                    //   acc.put(TAG_ACCNUM, an);
                     //  acc.put(TAG_USEREG, unr);
                        acc.put(TAG_PASSREG, pwr);

                      if(pwr.equals(Password1)){
                           pswcnt = i;
                           cbn = pwr;

                       }   
                        // adding contact to contact list
                       accntList.add(acc);



                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
                Toast.makeText(Frontpane.this,"Please Check Your Internet Connection", Toast.LENGTH_SHORT).show();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog

            /**
             * Updating parsed JSON data into ListView
             * */

            cntb = cbn;

            if(Username1.isEmpty()){
                Toast.makeText(Frontpane.this, "Please Enter Username!", Toast.LENGTH_SHORT).show();
                username.setText(null, null);
                password.setText(null, null);

            }
            else{

                /*  Toast.makeText(Frontpane.this, "meron", Toast.LENGTH_SHORT).show();
                    username.setText(null, null);
                    password.setText(null, null); */
                if(cntb!=null){
                    if((pswcnt>=0)&&(usncnt>=0)){
                        if(pswcnt==usncnt){

                            Intent intent = new Intent(Frontpane.this,MyActivity.class);
                            startActivity(intent);

                           Toast.makeText(Frontpane.this, "Login Successful!", Toast.LENGTH_SHORT).show();
                            username.setText(null, null);
                            password.setText(null, null);
                        }
                        else{
                            Toast.makeText(Frontpane.this, "Username and Password does not match, Please Try Again! ", Toast.LENGTH_SHORT).show();
                            username.setText(null, null);
                            password.setText(null, null);
                        }

                    }
                }
                else{
                Toast.makeText(Frontpane.this, "Wrong Password, Please Try Again! ", Toast.LENGTH_SHORT).show();
                username.setText(null, null);
                password.setText(null, null);
                }
            }




        }

    }
    DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch (which){
                case DialogInterface.BUTTON_POSITIVE:
                    ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
                    activityManager.killBackgroundProcesses("com.example.RadarOperationMonitoringSystem");
                    int pid = android.os.Process.myPid();
                    android.os.Process.killProcess(pid);
                    // Method 2
                    System.exit(0);
                    break;

                case DialogInterface.BUTTON_NEGATIVE:

                    break;
            }
        }


    };
    public void addButtonListener() {

        Loginbutton = (Button) findViewById(R.id.buttonLogin);
        Loginbutton.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                   Username1 = username.getText().toString();
                     Password1 = password.getText().toString();

                  new GetContacts().execute();
                Toast.makeText(Frontpane.this, "Please Wait.. Verifying User Log-in. ", Toast.LENGTH_SHORT).show();

            }
        });


    }
    OnClickListener button = new OnClickListener() {
        public void onClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(Frontpane.this);
            builder.setMessage("Are you sure want to exit?").setPositiveButton("Yes", dialogClickListener)
                    .setNegativeButton("No", dialogClickListener).show();


        }
    };



}

2 个答案:

答案 0 :(得分:1)

通过从doInBackground方法返回适当的值,在后执行中执行此操作。所有与UI相关的代码都应该在ui线程中运行。

Toast.makeText(Frontpane.this,"Please Check Your Internet Connection", Toast.LENGTH_SHORT).show();

更新

你必须做这样的事情

 private class GetContacts extends AsyncTask<Void, Void, Boolean> {
  @Override
  protected Boolean doInBackground(Void... arg0) {
    // Creating service handler class instance
    ServiceHandler sh = new ServiceHandler();
    // Making a request to url and getting response
    String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

    Log.d("Response: ", "> " + jsonStr);

    if (jsonStr != null) {
        try {
            JSONObject jsonObj = new JSONObject(jsonStr);

            // Getting JSON Array node
            accnt = jsonObj.getJSONArray(TAG_REGISTEREDACCOUNTS);

            // looping through All Contacts
            for (int i = 0; i < accnt.length(); i++) {
                int l;
                JSONObject c = accnt.getJSONObject(i);

               // String an = c.getString(TAG_ACCNUM);
                String unr = c.getString(TAG_USEREG);
               // String pwr = c.getString(TAG_PASSREG);

                // tmp hashmap for single contac
                HashMap<String, String> acc = new HashMap<String, String>();

                // adding each child node to HashMap key => value
            //   acc.put(TAG_ACCNUM, an);
               acc.put(TAG_USEREG, unr);
             //   acc.put(TAG_PASSREG, pwr);

              if(unr.equals(Username1)){
                   usncnt = i;
                   can = unr;

               }   
                // adding contact to contact list
               accntList.add(acc);



            }
        } catch (JSONException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    } else {

       Log.e("ServiceHandler", "Couldn't get any data from the url");
        ///Toast.makeText(Frontpane.this,"Please Check Your Internet Connection", Toast.LENGTH_SHORT).show();
        return false;
    }

}

@Override
protected void onPostExecute(Boolean result) {
    super.onPostExecute(result);
    // Dismiss the progress dialog

    /**
     * Updating parsed JSON data into ListView
     * */

    if(!result)
    {
        // add here your message
        Toast.makeText(Frontpane.this,"Please Check Your Internet Connection", Toast.LENGTH_SHORT).show();
        return;
    }
    cnta = can;
    if(Username1.isEmpty()==false){
        if(Password1.isEmpty()){
            Toast.makeText(Frontpane.this, "Please Enter Password!", Toast.LENGTH_SHORT).show();
            username.setText(null, null);
            password.setText(null, null);

        }
        else{
            if(cnta!=null){
            new GetPAss().execute();
            }
            else{
                Toast.makeText(Frontpane.this, "Not Registered or Check your Internet Connection..", Toast.LENGTH_SHORT).show();
                username.setText(null, null);
                password.setText(null, null);
            }

        }
    }
    else{


            Toast.makeText(Frontpane.this, "Please Enter Username!", Toast.LENGTH_SHORT).show();
            username.setText(null, null);
            password.setText(null, null);

    }

}

答案 1 :(得分:0)

执行asynctask的工作流程如下

onPreExecute()
doInBackground(Params...)
onProgressUpdate(Progress...)
onPostExecute(Result)

除了doInBackground(Params ...)之外,可以在这些方法上调用UI代码。 UI工作应该推迟到onPostExecute(Result)。

似乎doInbackground中的toast消息是在代码中的异常之后触发的。