after the crashing problem been solved now the application is not executing the update or deleting
when i update it crashes immediately but when i delete it shows me the toast and nothing happens then
this is the class
public class EditCard extends Activity {
EditText txtName;
EditText txtPosition;
EditText txtCollege;
EditText txtPhone;
Button btnSave;
Button btnDelete;
String cid;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single product url
private static final String url_card_details = "http://XXX";
// url to update product
private static final String url_update_card = "http://XXX";
// url to delete product
private static final String url_delete_card = "http://XXX";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_CARDS = "cards";
private static final String TAG_CID = "cid";
private static final String TAG_CNAME = "name";
private static final String TAG_POSITION = "position";
private static final String TAG_COLLEGE = "college";
private static final String TAG_PHONE = "phone";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_card);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
// save button
btnSave = (Button) findViewById(R.id.SaveCard);
btnDelete = (Button) findViewById(R.id.DeleteCard);
// getting product details from intent
Intent i = getIntent();
// getting product id (pid) from intent
cid = i.getStringExtra(TAG_CID);
// Getting complete product details in background thread
new GetCardDetails().execute();
// save button click event
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// starting background task to update product
new SaveCardDetails().execute();
}
});
// Delete button click event
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// deleting product in background thread
new DeleteCard().execute();
}
});
}
/**
* Background Async Task to Get complete product details
* */
class GetCardDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditCard.this);
pDialog.setMessage("Loading card details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("cid", cid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_card_details, "GET", params);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray cardObj = json
.getJSONArray(TAG_CARDS); // JSON Array
// get first product object from JSON Array
JSONObject card = cardObj.getJSONObject(0);
// product with this pid found
// Edit Text
txtName = (EditText) findViewById(R.id.editCard1);
txtPosition = (EditText) findViewById(R.id.editCard2);
txtCollege= (EditText) findViewById(R.id.editCard3);
txtPhone= (EditText) findViewById(R.id.editCard4);
// display product data in EditText
txtName.setText(card.getString(TAG_CNAME));
txtPosition.setText(card.getString(TAG_POSITION));
txtCollege.setText(card.getString(TAG_COLLEGE));
txtPhone.setText(card.getString(TAG_PHONE));
}else{
// product with pid not found
}
} 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 got all details
pDialog.dismiss();
}
}
/**
* Background Async Task to Save product Details
* */
class SaveCardDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditCard.this);
pDialog.setMessage("Saving Card ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Saving product
* */
protected String doInBackground(String... args) {
// getting updated data from EditTexts
String name = txtName.getText().toString();
String position = txtPosition.getText().toString();
String college = txtCollege.getText().toString();
String phone = txtPhone.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("position", position));
params.add(new BasicNameValuePair("college", college));
params.add(new BasicNameValuePair("phone", phone));
// sending modified data through http request
// Notice that update product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_update_card,
"POST", params);
// check json success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully updated
Intent i = getIntent();
// send result code 100 to notify about product update
setResult(100, i);
finish();
} else {
// failed to update product
}
} 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 product uupdated
Toast.makeText(getApplicationContext(), "The Student Card Updated sucessfully", Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
}
/*****************************************************************
* Background Async Task to Delete Product
* */
class DeleteCard extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditCard.this);
pDialog.setMessage("Deleting Card...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Deleting product
* */
protected String doInBackground(String... args) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("cid", cid));
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
url_delete_card, "POST", params);
// check your log for json response
Log.d("Delete Card", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// product successfully deleted
// notify previous activity by sending code 100
Intent i = getIntent();
// send result code 100 to notify about product deletion
setResult(100, i);
finish();
}
} 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 product deleted
Toast.makeText(getApplicationContext(), "The Student Card deleted sucessfully", Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
}
}
and this is the LogCat when i update
07-18 01:15:53.053: W/dalvikvm(8740): threadid=11: thread exiting with uncaught exception (group=0x40a71930)
07-18 01:15:53.383: E/AndroidRuntime(8740): FATAL EXCEPTION: AsyncTask #1
07-18 01:15:53.383: E/AndroidRuntime(8740): java.lang.RuntimeException: An error occured while executing doInBackground()
07-18 01:15:53.383: E/AndroidRuntime(8740): at android.os.AsyncTask$3.done(AsyncTask.java:299)
07-18 01:15:53.383: E/AndroidRuntime(8740): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
07-18 01:15:53.383: E/AndroidRuntime(8740): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
07-18 01:15:53.383: E/AndroidRuntime(8740): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
07-18 01:15:53.383: E/AndroidRuntime(8740): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
07-18 01:15:53.383: E/AndroidRuntime(8740): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
07-18 01:15:53.383: E/AndroidRuntime(8740): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
07-18 01:15:53.383: E/AndroidRuntime(8740): at java.lang.Thread.run(Thread.java:856)
07-18 01:15:53.383: E/AndroidRuntime(8740): Caused by: java.lang.NullPointerException
07-18 01:15:53.383: E/AndroidRuntime(8740): at com.example.ahliaevents.EditCard$SaveCardDetails.doInBackground(EditCard.java:210)
07-18 01:15:53.383: E/AndroidRuntime(8740): at com.example.ahliaevents.EditCard$SaveCardDetails.doInBackground(EditCard.java:1)
07-18 01:15:53.383: E/AndroidRuntime(8740): at android.os.AsyncTask$2.call(AsyncTask.java:287)
07-18 01:15:53.383: E/AndroidRuntime(8740): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
07-18 01:15:53.383: E/AndroidRuntime(8740): ... 4 more
and this is the LogCat when i delete
07-18 01:18:01.584: E/JSON Parser(8850): Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
For your delete crash, you're not getting JSON back from the server, you're probably getting an error page. The parser is expecting to see JSON and it sees what appears to be the beginning of an XML/XHTML document.
For your other crash, just look at your source at line 210. You're getting a NullPointerException, which means that you expect something to be an object, but it's a null reference.
Most alarming is your use of runOnUiThread() within a doInBackground() the whole point of doInBackground is to avoid the UI Thread.
Related
In AllProductActivity.java where data is view in list form. On onItemClick depending on pid data move to next EditProductActivity.
Following code is working fine in eclipse but while working in Android Studio activity unfortunately stopped. why I just don't get it if anyone know it.
Logcat for error
Please help me.
AllProductActivity.java
public class AllProductsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://192.168.1.2/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);
}
});
}
}
}
EditProductActivity.java
public class EditProductActivity extends Activity {
EditText txtName;
EditText txtPrice;
EditText txtDesc;
EditText txtCreatedAt;
Button btnSave;
Button btnDelete;
String pid;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single product url
private static final String url_product_detials = "http://192.168.1.2/android_connect/get_product_details.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_DESCRIPTION = "description";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_product);
// save button
btnSave = (Button) findViewById(R.id.btnSave);
btnDelete = (Button) findViewById(R.id.btnDelete);
// getting product details from intent
Intent i = getIntent();
// getting product id (pid) from intent
pid = i.getStringExtra(TAG_PID);
// Getting complete product details in background thread
new GetProductDetails().execute();
// save button click event
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// starting background task to update product
}
});
// Delete button click event
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// deleting product in background thread
}
});
}
/**
* Background Async Task to Get complete product details
*/
class GetProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditProductActivity.this);
pDialog.setMessage("Loading product details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
*/
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", pid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray productObj = json
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
txtName = (EditText) findViewById(R.id.inputName);
txtPrice = (EditText) findViewById(R.id.inputPrice);
txtDesc = (EditText) findViewById(R.id.inputDesc);
// display product data in EditText
txtName.setText(product.getString(TAG_NAME));
txtPrice.setText(product.getString(TAG_PRICE));
txtDesc.setText(product.getString(TAG_DESCRIPTION));
} else {
// product with pid not found
}
} 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 got all details
pDialog.dismiss();
}
}
}
Logcat error:-
Process: info.androidhive.androidphpconnection, PID: 10068
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:110)
at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
at libcore.io.IoBridge.connect(IoBridge.java:122)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:452)
at java.net.Socket.connect(Socket.java:884)
at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:124)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:149)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:169)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:124)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:366)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:560)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:492)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:470)
at info.androidhive.androidphpconnection.JSONParser.makeHttpRequest(JSONParser.java:62)
at info.androidhive.androidphpconnection.EditProductActivity$GetProductDetails$1.run(EditProductActivity.java:131)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Reason : Calling networking stuff on UI thread. This line
JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
1.runOnUiThread runs on UI thread and where you never ever make HTTP/networking stuff.
2.
doInBackGround runs on worker thread where you can make http/networking stuff.
3. No need to call runOnUiThread inside onPreExecute and onPostExecute because these method run on UI thread only.
you code changes go like this.
protected String doInBackground(String... args) {
// Check for success tag
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", pid));
final JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
final int success = json.getInt(TAG_SUCCESS);
//below code runs on UI thread.
runOnUiThread(new Runnable() {
public void run() {
if (success == 1) {
// successfully received product details
try {
JSONArray productObj = json.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
txtName = (EditText) findViewById(R.id.inputName);
txtPrice = (EditText) findViewById(R.id.inputPrice);
txtDesc = (EditText) findViewById(R.id.inputDesc);
// display product data in EditText
txtName.setText(product.getString(TAG_NAME));
txtPrice.setText(product.getString(TAG_PRICE));
txtDesc.setText(product.getString(TAG_DESCRIPTION));
} catch (JSONException e) {
}
} else {
// product with pid not found
}
}
});
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Hi I am building a login app in where the details of the users will be shown using JSON PHP and MYSQL but whenever the profile would show up it crashes what Am I doing wrong? What's weird is that this was working few days ago
logcat report
10-05 18:55:34.088: E/AndroidRuntime(3173): FATAL EXCEPTION: main
10-05 18:55:34.088: E/AndroidRuntime(3173): java.lang.NullPointerException
10-05 18:55:34.088: E/AndroidRuntime(3173): at com.example.itmaproject.EditContactsActivity$GetProductDetails$1.run(EditContactsActivity.java:144)
10-05 18:55:34.088: E/AndroidRuntime(3173): at android.os.Handler.handleCallback(Handler.java:725)
10-05 18:55:34.088: E/AndroidRuntime(3173): at android.os.Handler.dispatchMessage(Handler.java:92)
10-05 18:55:34.088: E/AndroidRuntime(3173): at android.os.Looper.loop(Looper.java:137)
10-05 18:55:34.088: E/AndroidRuntime(3173): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-05 18:55:34.088: E/AndroidRuntime(3173): at java.lang.reflect.Method.invokeNative(Native Method)
10-05 18:55:34.088: E/AndroidRuntime(3173): at java.lang.reflect.Method.invoke(Method.java:511)
10-05 18:55:34.088: E/AndroidRuntime(3173): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-05 18:55:34.088: E/AndroidRuntime(3173): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-05 18:55:34.088: E/AndroidRuntime(3173): at dalvik.system.NativeStart.main(Native Method)
my codepackage com.example.itmaproject;
public class EditContactsActivity extends Activity {
TextView txtName;
TextView txtNumber;
TextView txtAbout;
TextView txtDate;
Button btnSave;
Button btnDelete;
TextView txtDepart;
TextView fullname;
TextView txtUser;
Button btnLogout;
String username;
SessionManager session;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single product url
private static final String url_contact_details = "http://10.0.3.2/sunshine-ems/login/get_contact_details.php";
// url to update product
private static final String url_update_contact = "http://10.0.3.2/sunshine-ems/login/get_contact_details.php";
// url to delete product
private static final String url_delete_contact = "http://10.0.3.2/sunshine-ems/delete_contact.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_CONTACT = "contacts";
private static final String TAG_USERNAME = "username";
private static final String TAG_FIRSTNAME = "firstname";
private static final String TAG_DEPART = "department";
private static final String TAG_LASTNAME = "lastname";
private static final String TAG_ID = "user_id";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_contact);
btnLogout = (Button) findViewById(R.id.btnLogout);
// save button
// getting product details from intent
//Intent i = getIntent();
// getting product id (pid) from intent
//pid = i.getStringExtra(TAG_USERNAME);
session = new SessionManager(getApplicationContext());
username = session.getUsername();
// Getting complete product details in background thread
new GetProductDetails().execute();
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Launching All products Activity
session.logoutUser();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
}
/**
* Background Async Task to Get complete product details
* */
class GetProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditContactsActivity.this);
pDialog.setMessage("Loading contact details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_contact_details, "GET", params);
// check your log for json response
Log.d("Single Contact Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray contactObj = json.getJSONArray(TAG_CONTACT); // JSON Array
// get first product object from JSON Array
JSONObject contact = contactObj.getJSONObject(0);
// product with this pid found
// Edit Text
txtName = (TextView) findViewById(R.id.inputName);
txtDepart = (TextView) findViewById(R.id.department);
//txtAbout = (TextView) findViewById(R.id.inputDesc);
txtUser = (TextView) findViewById(R.id.inputPrice);
// display product data in EditText
String fullname = contact.getString(TAG_LASTNAME)+' '+ contact.getString(TAG_FIRSTNAME);
txtName.setText(fullname);
txtDepart.setText(contact.getString(TAG_DEPART));
//txtAbout.setText(contact.getString(TAG_LASTNAME));
txtUser.setText(contact.getString(TAG_ID));
Log.v("blahhhhh", "blah hhhhblah");
}else{
// product with pid not found
Log.v("blah", "blah blah");
}
} 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 got all details
pDialog.dismiss();
}
}
/**
* Background Async Task to Save product Details
* */
class SaveProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditContactsActivity.this);
pDialog.setMessage("Saving contact ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Saving product
* */
protected String doInBackground(String... args) {
// getting updated data from EditTexts
String name = txtName.getText().toString();
//String number = txtNumber.getText().toString();
//String about = txtAbout.getText().toString();
String user = txtUser.getText().toString();
String depart = txtDepart.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_USERNAME, username));
params.add(new BasicNameValuePair(TAG_FIRSTNAME, name));
params.add(new BasicNameValuePair(TAG_DEPART, depart));
//params.add(new BasicNameValuePair(TAG_LASTNAME, about));
params.add(new BasicNameValuePair(TAG_ID, user));
// sending modified data through http request
// Notice that update product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_update_contact,
"POST", params);
// check json success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully updated
Intent i = getIntent();
// send result code 100 to notify about product update
setResult(100, i);
finish();
} else {
// failed to update product
}
} 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 product uupdated
pDialog.dismiss();
}
}
/*****************************************************************
* Background Async Task to Delete Product
* */
class DeleteProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditContactsActivity.this);
pDialog.setMessage("Deleting Contact...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Deleting product
* */
protected String doInBackground(String... args) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
url_delete_contact, "POST", params);
// check your log for json response
Log.d("Delete Contact", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// product successfully deleted
// notify previous activity by sending code 100
Intent i = getIntent();
// send result code 100 to notify about product deletion
setResult(100, i);
finish();
}
} 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 product deleted
pDialog.dismiss();
}
}
}
Line 141
Log.d("Single Contact Details", json.toString());
Please check your url JSON may be null because of it
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();
}
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.
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.
I have this login Activity that contains async task class which perform a parsing method(Post) everything is going right and my data is posted but when the user enters a wrong email and password i just need to Toast him that his email and password are wrong so my code look like this:
public class ActivityLogin extends Activity
{
// Progress Dialog
private ProgressDialog pDialog;
private static String login_tag = "login";
PostParser jsonParser = new PostParser();
// UI references.
private EditText email;
private EditText password;
static String Email="";
static String Password="";
// url to create new product
private static String login_URL = "jhdakjhdakj";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
email=(EditText)findViewById(R.id.email);
password=(EditText)findViewById(R.id.password1);
Button login=(Button)findViewById(R.id.sign_in_button);
login.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Email=email.getText().toString();
Password=password.getText().toString();
(new LoginInTask()).execute();
}
});
}
class LoginInTask extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ActivityLogin.this);
pDialog.setMessage("Logging IN..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args)
{
String Email = email.getText().toString();
String Password = password.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("Email", Email));
params.add(new BasicNameValuePair("Password", Password));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(login_URL,"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
int success=0;
try
{
success = json.getInt(TAG_SUCCESS);
} catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(int success)
{
if (success==1)
{
// successfully created product
Intent i = new Intent(getApplicationContext(), ActivitySignUp.class);
startActivity(i);
// closing this screen
pDialog.dismiss();
finish();
}
else
{
Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_SHORT).show();
}
pDialog.dismiss();
finish();
}
}
}
your help would be appreciated. Thank you
here is my logcat
11-05 16:16:46.536: E/AndroidRuntime(5807): FATAL EXCEPTION: AsyncTask #1
11-05 16:16:46.536: E/AndroidRuntime(5807): java.lang.RuntimeException: An error occured while executing doInBackground()
11-05 16:16:46.536: E/AndroidRuntime(5807): at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-05 16:16:46.536: E/AndroidRuntime(5807): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
11-05 16:16:46.536: E/AndroidRuntime(5807): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
11-05 16:16:46.536: E/AndroidRuntime(5807): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
11-05 16:16:46.536: E/AndroidRuntime(5807): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-05 16:16:46.536: E/AndroidRuntime(5807): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-05 16:16:46.536: E/AndroidRuntime(5807): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-05 16:16:46.536: E/AndroidRuntime(5807): at java.lang.Thread.run(Thread.java:849)
11-05 16:16:46.536: E/AndroidRuntime(5807): Caused by: java.lang.NullPointerException
11-05 16:16:46.536: E/AndroidRuntime(5807): at com.asap.ActivityLogin$LoginInTask.doInBackground(ActivityLogin.java:108)
11-05 16:16:46.536: E/AndroidRuntime(5807): at com.asap.ActivityLogin$LoginInTask.doInBackground(ActivityLogin.java:1)
11-05 16:16:46.536: E/AndroidRuntime(5807): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-05 16:16:46.536: E/AndroidRuntime(5807): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-05 16:16:46.536: E/AndroidRuntime(5807): ... 4 more
please change your code with this one I've fixed many things to you taged with <--jack
public class ActivityLogin extends Activity
{
// Progress Dialog
private ProgressDialog pDialog;
private static String login_tag = "login";
PostParser jsonParser;//<-- placed in doinbackground <-- jack
// UI references.
private EditText email;
private EditText password;
static String Email="";
static String Password="";
// url to create new product
private static String login_URL = "jhdakjhdakj";
// JSON Node names
private static final String TAG_SUCCESS = "success";
//Query login <<- jack
LoginInTask query;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
email=(EditText)findViewById(R.id.email);
password=(EditText)findViewById(R.id.password1);
Button login=(Button)findViewById(R.id.sign_in_button);
login.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Email=email.getText().toString();
Password=password.getText().toString();
//Cancel if already runing or dont excute its up to you <-- jack
if( query != null )
{
query.cancel(true);
}
query = ( LoginInTask ) new LoginInTask().execute();
}
});
}
class LoginInTask extends AsyncTask<String, String, String> {
//Register success here <-- jack
int success=0;
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ActivityLogin.this);
pDialog.setMessage("Logging IN..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* if canceled <-- jack
* */
#Override
protected void onCancelled() {
if ( pDialog != null )
{
pDialog.dismiss();
}
}
/**
* Creating product
* */
protected String doInBackground(String... args)
{
String Email = email.getText().toString();
String Password = password.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("Email", Email));
params.add(new BasicNameValuePair("Password", Password));
//Try from here coz you are working with JSON <<-- jack
try
{
// getting JSON Object
// Note that create product url accepts POST method
//Start new Session <-- jack
jsonParse = new PostParser();
JSONObject json = jsonParser.makeHttpRequest(login_URL,"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
success = json.getInt(TAG_SUCCESS);
} catch (JSONException e)
{
Log.d("Create Response", "Faild");//<-- tag faild to parse JSON
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(int success)
{
//Check if dialog still runing dismiss <<-- jack
if ( pDialog != null)
{
pDialog.dismiss();
}
if (success==1)
{
// successfully created product
Intent i = new Intent(getApplicationContext(), ActivitySignUp.class);
startActivity(i);
}
else
{
Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_SHORT).show();
}
//finish current activity call it on time only <<-- jack
finish();
}
}
}
I am working in android platform and want to send some signup details to a php page for that i created an activity named as 'ContinueRegister' it contains an AsyncTask class. while running my project it shows unfortunately has stopped and there is some errors in logcat like
Activity com.opz.ContinueRegister has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#41269db8
error opening trace file: No such file or directory
at android.os.Looper.loop(Looper.java:137)
at android.os.Handler.handleCallback(Handler.java:615)
atcom.opz.ContinueRegister$CreateNewUser.onPreExecute(ContinueRegister.java:76)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at java.lang.reflect.Method.invokeNative(Native Method)
this is my class file
public class ContinueRegister extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText firstname;
EditText lastname;
EditText dob;
EditText gender;
RegisterActivity ra= new RegisterActivity();
// url to create new product
private static String url_create_product = "http://localhost/login_api/create_account.php/";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set View to register.xml
setContentView(R.layout.registerfinsh);
Button bt=(Button)findViewById(R.id.btnRegister);
// Listening to Login Screen link
bt.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0) {
new CreateNewUser().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ContinueRegister.this);
pDialog.setMessage("Creating New User..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating User
* */
protected String doInBackground(String... args) {
String Username = ra.username.getText().toString();
String Email = ra.email.getText().toString();
String Password =ra.password.getText().toString();
firstname = (EditText)findViewById(R.id.first_name);
lastname =(EditText)findViewById(R.id.last_name);
dob =(EditText)findViewById(R.id.date_of_birth);
gender = (EditText)findViewById(R.id.gender);
String Firstname = firstname.getText().toString();
String Lastname = lastname.getText().toString();
String Dob =dob.getText().toString();
String Gender =gender.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Username", Username));
params.add(new BasicNameValuePair("Email", Email));
params.add(new BasicNameValuePair("Password", Password));
params.add(new BasicNameValuePair("Firstname", Firstname));
params.add(new BasicNameValuePair("Lastname", Lastname));
params.add(new BasicNameValuePair("Dob", Dob));
params.add(new BasicNameValuePair("Gender", Gender));
// getting JSON Object
// Note that create user url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat for response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created user
Intent i = new Intent(getApplicationContext(), FinishSignupActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create user
}
} 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();
TextView loginScreen = (TextView) findViewById(R.id.link_to_login2);
loginScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent m = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(m);
}
});
}
}
}
please help me to fix this errors
String url_create_product = "http://10.0.2.2/login_api/create_account.php/";
OR
Use your local IP Like 192.168.0.1
String url_create_product = "http://192.168.0.1/login_api/create_account.php/";
Also check your login_api folder have file which name is create_account.php
One more thing is Never Access Any view inside doinBackGround(...)
Because doinBackGround method is non-UI thread.
we must give complete url like 192.10.1.000.
you can check in windows by using localhost.but you must provide complete url in the above line.
To know ur ipaddress open cmd prompt. and type ipconfig.
Put the code for calling intent onPostexecute
going to another activity is never a background task