I have made an android application where there are a login form, an update details form, etc.
Whenever I enter a wrong detail, the app stops working and a force close dialog box appears.
This is my code:
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
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!
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. To display or pass to another activity, Use in postExecute. Only main operation to be performed in 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.
Do this at the end of 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 :
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
:
// 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.
As in other answers, your error (althought without logcat....) is that you call:
Toast.makeText(getApplicationContext(), "Unsuccessful Updation", Toast.LENGTH_SHORT).show();
in doInBackground
, UI operations are permitted only on UI thread. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.