简体   繁体   English

强制关闭我的Android应用程序

[英]Force close in my android application

I have made an android application where there are a login form, an update details form, etc. 我已经制作了一个android应用程序,其中有一个登录表单,一个更新详细信息表单等。

Whenever I enter a wrong detail, the app stops working and a force close dialog box appears. 每当我输入错误的详细信息时,该应用程序就会停止工作,并显示“强制关闭”对话框。

This is my code: 这是我的代码:

Login.java Login.java

   public class AllProductsActivity extends ListActivity
   {
       private ProgressDialog pDialog;
       JSONParser jParser = new JSONParser();
       ArrayList<HashMap<String, String>> productsList;
       private static String url_all_products = "http://192.168.1.4/android_connect/get_all_products.php";

       // JSON Node names
       private static final String TAG_SUCCESS = "success";
       private static final String TAG_PRODUCTS = "products";
       private static final String TAG_PID = "pid";
       private static final String TAG_NAME = "name";

       // products JSONArray
       JSONArray products = null;

       @Override
       public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.all_products);

    // Hashmap for ListView
    productsList = new ArrayList<HashMap<String, String>>();

    // Loading products in Background Thread
    new LoadAllProducts().execute();

    // Get listview
    ListView lv = getListView();

    // on seleting single product
    // launching Edit Product Screen
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                    .toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(),
                    EditProductActivity.class);
            // sending pid to next activity
            in.putExtra(TAG_PID, pid);

            // starting new activity and expecting some response back
            startActivityForResult(in, 100);
        }
    });

}

// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // if result code 100
    if (resultCode == 100) {
        // if result code 100 is received 
        // means user edited/deleted product
        // reload this screen again
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

}

/**
 * Background Async Task to Load all product by making HTTP Request
 * */
class LoadAllProducts extends AsyncTask<String, String, String> 
    {
         /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(AllProductsActivity.this);
        pDialog.setMessage("Loading products. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Products: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_PRODUCTS);

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

                    // Storing each json item in variable
                    String id = c.getString(TAG_PID);
                    String name = c.getString(TAG_NAME);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_PID, id);
                    map.put(TAG_NAME, name);

                    // adding HashList to ArrayList
                    productsList.add(map);
                }
            } else {
                // no products found
                // Launch Add New product Activity
                Intent i = new Intent(getApplicationContext(),
                        NewProductActivity.class);
                // Closing all previous activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        AllProductsActivity.this, productsList,
                        R.layout.list_item, new String[] { TAG_PID,
                                TAG_NAME},
                        new int[] { R.id.pid, R.id.name });
                // updating listview
                setListAdapter(adapter);
            }
        });
    }
}
}

UpdateDetails.java UpdateDetails.java

   public class UpdateDetails extends Activity
   {

        EditText inputName;
        EditText inputAddress;
        EditText inputPassword;
        EditText confirmPassword;
        EditText inputEmailId, inputMobileno;

        // Progress Dialog
        private ProgressDialog pDialog;

    // JSON parser class
        JSONParser jsonParser = new JSONParser();

        // JSON Node names
        private static final String resp = "success";
        //private static final String Flag = "flag";

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.updatedetails);

        // Edit Text
        inputName = (EditText) findViewById(R.id.editName);
        inputAddress = (EditText) findViewById(R.id.editAddress);
        inputPassword = (EditText) findViewById(R.id.editPassword);
        confirmPassword=(EditText) findViewById(R.id.editConfirmPassword);
        inputEmailId=(EditText) findViewById(R.id.editText2_emailid);
        inputMobileno=(EditText) findViewById(R.id.editText1_mobile);

        // Create button
        Button update_details = (Button) findViewById(R.id.buttonUpdate);

        // button click event
        update_details.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                if (inputPassword == confirmPassword){
                // updating user in background thread
                new UpdateUserDetails().execute();
                }
                else {
                    //Some Sort Of Alert Box
                    Toast.makeText(getApplicationContext(), "Please Enter Valid Details", Toast.LENGTH_SHORT).show();
                    }
            }
        });
    }

    /**
     * Background Async Task to Create new product
     * */
    class UpdateUserDetails extends AsyncTask<String, String, String> {
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(UpdateDetails.this);
            pDialog.setMessage("Updating User Details.. Please wait");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * Updating User
         * */
        protected String doInBackground(String... args) {
            String name = inputName.getText().toString();
            String address = inputAddress.getText().toString();
            String password = inputPassword.getText().toString();
            String mobileno = inputMobileno.getText().toString();
            String emailid = inputEmailId.getText().toString();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name", name));
            params.add(new BasicNameValuePair("address", address));
            params.add(new BasicNameValuePair("password", password));
            params.add(new BasicNameValuePair("mobile_no", mobileno));
            params.add(new BasicNameValuePair("email_id",emailid));

            final String url_user = "http://"+ Login.serve +"/catxam/android_update.php";

            // getting JSON Object
            JSONObject json = jsonParser.makeHttpRequest(url_user,"POST", params);

            // check log cat from response
            Log.d("Update Response", json.toString());

            // check for success tag
            try {
                int success = json.getInt(resp);

                if (success == 1) {
                    // successfully update user
                    Intent i = new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(i);

                    // closing this screen
                    finish();
                } else {
                    Toast.makeText(getApplicationContext(), "Unsuccessful Updation", Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
        }

    }
}

Can anyone help me in identifying my mistake and help me in rectifying mistakes in my project. 谁能帮助我确定我的错误并帮助我纠正项目中的错误。

I appreciate your help. 我感谢您的帮助。 Thanks in advance 提前致谢

Here is the logCat window! 这是logCat窗口!

02-13 19:32:10.096: E/AndroidRuntime(7328): FATAL EXCEPTION: AsyncTask #2

02-13 19:32:10.096: E/AndroidRuntime(7328): java.lang.RuntimeException: An error occured while executing doInBackground()

02-13 19:32:10.096: E/AndroidRuntime(7328):     at android.os.AsyncTask$3.done(AsyncTask.java:299)

02-13 19:32:10.096: E/AndroidRuntime(7328):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)

02-13 19:32:10.096: E/AndroidRuntime(7328):     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)

02-13 19:32:10.096: E/AndroidRuntime(7328):     at java.util.concurrent.FutureTask.run(FutureTask.java:239)

02-13 19:32:10.096: E/AndroidRuntime(7328):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)

02-13 19:32:10.096: E/AndroidRuntime(7328):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)

02-13 19:32:10.096: E/AndroidRuntime(7328):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)

02-13 19:32:10.096: E/AndroidRuntime(7328):     at java.lang.Thread.run(Thread.java:838)

02-13 19:32:10.096: E/AndroidRuntime(7328): Caused by: java.lang.NullPointerException
02-13 19:32:10.096: E/AndroidRuntime(7328):     at 
com.example.catxam.Login$CreateNewUser.doInBackground(Login.java:146)

02-13 19:32:10.096: E/AndroidRuntime(7328):     at com.example.catxam.Login$CreateNewUser.doInBackground(Login.java:1)

02-13 19:32:10.096: E/AndroidRuntime(7328):     at android.os.AsyncTask$2.call(AsyncTask.java:287)

02-13 19:32:10.096: E/AndroidRuntime(7328):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)

02-13 19:32:10.096: E/AndroidRuntime(7328):     ... 4 more

Sorry not able to post images :( 抱歉,无法发布图片:(

Excecute this in postExecute. 在postExecute中执行此操作。 To display or pass to another activity, Use in postExecute. 要显示或传递给另一个活动,请在postExecute中使用。 Only main operation to be performed in doInBackground. 在doInBackground中仅执行主要操作。

        try {
            int success = json.getInt(resp);

            if (success == 1) {
                // successfully update user
                Intent i = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(i);

                // closing this screen
                finish();
            } else {
                Toast.makeText(getApplicationContext(), "Unsuccessful Updation", Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

You cannot make a call to Toast.makeText from the doInBackground method, as it needs to be done on the UI thread. 您不能从doInBackground方法调用Toast.makeText ,因为它需要在UI线程上完成。

Do this at the end of doInBackground : 在doInBackground的末尾执行此操作:

// check for success tag
try {
    int success = json.getInt(resp);
    String success = success == 1 ? "success" : null;
    return success;
} catch (JSONException e) {
    e.printStackTrace();
    return null;
}

and this in onPostExecute : 这在onPostExecute中:

protected void onPostExecute(String result) {
    if (result!= null) {
        // successfully update user
        Intent i = new Intent(getApplicationContext(), MainActivity.class);
        startActivity(i);
        // closing this screen
        finish();
    } else {
        Toast.makeText(getApplicationContext(), "Unsuccessful Updation", Toast.LENGTH_SHORT).show();
    }
    pDialog.dismiss();
}

Additionally, you should not do this in LoadAllProducts : 此外,您不应在LoadAllProducts执行此LoadAllProducts

// updating UI from Background Thread
runOnUiThread(new Runnable()

onPostExecute is designed for you to update the UI at the end of your background task, so you don't need to create an additional Thread to execute that code. onPostExecute是专为您在后台任务结束时更新UI而设计的,因此您无需创建其他线程即可执行该代码。

As in other answers, your error (althought without logcat....) is that you call: 像其他答案一样,您的错误(尽管没有logcat...。)是您致电:

Toast.makeText(getApplicationContext(), "Unsuccessful Updation", Toast.LENGTH_SHORT).show();

in doInBackground , UI operations are permitted only on UI thread. doInBackground ,仅在UI线程上允许UI操作。 On the other hand you dont need: 另一方面,您不需要:

runOnUiThread(new Runnable() {

in onPostExecute because it is already executed on UI thread, so you should use onPostExecute for your toast message. onPostExecute因为它已经在UI线程上执行,所以您应该将onPostExecute用于Toast消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM