I have a problem in sending data from and Android application to PHP using Restful Web services. I am getting "java.lang.RuntimeException: An error occurred while executing doInBackground()" error. Please advice me on what to do. Thanks.
This is the MainActivity.java class
package com.example.contactexchange;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText lastnameBox, firstnameBox, phonenoBox, addressBox;
Spinner salutationBox;
ImageView imageview;
Button addPhone, saveBox;
String lastname, firstname, phoneno, address, salutation;
JSONParser jsonParser = new JSONParser();
GetIPAddress getIPaddress = new GetIPAddress();
ProgressDialog pDialog;
private static String save_contact;
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
save_contact = getIPaddress.getIP()+"register.php";
lastnameBox = (EditText)findViewById(R.id.lastnameBox);
firstnameBox = (EditText)findViewById(R.id.firstnameBox);
phonenoBox = (EditText)findViewById(R.id.phonenoBox);
addressBox = (EditText)findViewById(R.id.addressBox);
salutationBox = (Spinner)findViewById(R.id.spinner1);
imageview = (ImageView)findViewById(R.id.imageView1);
addPhone = (Button)findViewById(R.id.button1);
saveBox = (Button)findViewById(R.id.saveBox);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getApplicationContext(),
R.array.salutation, R.layout.custom_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(R.layout.custom_spinner_dropdown_item);
// Apply the adapter to the spinner
salutationBox.setAdapter(adapter);
salutationBox.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
salutation = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}});
saveBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
/*lastname = lastnameBox.getText().toString();
firstname = firstnameBox.getText().toString();
phoneno = phonenoBox.getText().toString();
address = addressBox.getText().toString();
Toast.makeText(getApplicationContext(), salutation+" "+lastname+" "+firstname+" "+phoneno+" "+address, Toast.LENGTH_SHORT).show();
*/
new SaveContact().execute();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class SaveContact extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
// pDialog = new ProgressDialog(MainActivity.this);
// pDialog.setMessage("Saving Contact...");
// pDialog.setIndeterminate(false);
// pDialog.setCancelable(true);
// pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
lastname = lastnameBox.getText().toString();
firstname = firstnameBox.getText().toString();
phoneno = phonenoBox.getText().toString();
address = addressBox.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>(5);
params.add(new BasicNameValuePair("salutation", salutation));
params.add(new BasicNameValuePair("firstname", firstname));
params.add(new BasicNameValuePair("lastname", lastname));
params.add(new BasicNameValuePair("phoneno", phoneno));
params.add(new BasicNameValuePair("address", address));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(save_contact, "POST", params);
Log.d("Datae" ,salutation+ " " + firstname+" "+lastname+" "+phoneno+" "+address);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
//Toast.makeText(getApplicationContext(), "Sussess", Toast.LENGTH_SHORT).show();
// closing this screen
finish();
} else {
Toast.makeText(getApplicationContext(), "Failc", Toast.LENGTH_SHORT).show();
// failed to create 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 done
pDialog.dismiss();
}
}
}
This is the register.php
<?php
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['salutation']) && isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['phoneno']) && isset($_POST['address'])) {
$salutation = $_POST['salutation'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$phoneno = $_POST['phoneno'];
$address = $_POST['address'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO contact_info(salutation, first_name, last_name, phone_no, address) VALUES('$salutation', '$firstname', '$lastname', '$phoneno', '$address')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
This is the logcat error
07-27 15:16:44.125: E/AndroidRuntime(455): FATAL EXCEPTION: AsyncTask #1
07-27 15:16:44.125: E/AndroidRuntime(455): java.lang.RuntimeException: An error occured while executing doInBackground()
07-27 15:16:44.125: E/AndroidRuntime(455): at android.os.AsyncTask$3.done(AsyncTask.java:266)
07-27 15:16:44.125: E/AndroidRuntime(455): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
07-27 15:16:44.125: E/AndroidRuntime(455): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
07-27 15:16:44.125: E/AndroidRuntime(455): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
07-27 15:16:44.125: E/AndroidRuntime(455): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
07-27 15:16:44.125: E/AndroidRuntime(455): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1081)
07-27 15:16:44.125: E/AndroidRuntime(455): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:574)
07-27 15:16:44.125: E/AndroidRuntime(455): at java.lang.Thread.run(Thread.java:1020)
07-27 15:16:44.125: E/AndroidRuntime(455): Caused by: java.lang.NullPointerException
07-27 15:16:44.125: E/AndroidRuntime(455): at com.example.contactexchange.MainActivity$SaveContact.doInBackground(MainActivity.java:147)
07-27 15:16:44.125: E/AndroidRuntime(455): at com.example.contactexchange.MainActivity$SaveContact.doInBackground(MainActivity.java:1)
07-27 15:16:44.125: E/AndroidRuntime(455): at android.os.AsyncTask$2.call(AsyncTask.java:252)
07-27 15:16:44.125: E/AndroidRuntime(455): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
07-27 15:16:44.125: E/AndroidRuntime(455): ... 4 more
07-27 15:16:44.295: W/IInputConnectionWrapper(455): showStatusIcon on inactive InputConnection
07-27 15:16:46.645: E/InputQueue-JNI(455): channel '40fefa40 PopupWindow:408fcb78 (client)' ~ Publisher closed input channel or an error occurred. events=0x8
Please advice me on what to do. Thanks
I'm pretty sure your issue is with the EditTexts you're reading inside on doInBackground:
EditText lastnameBox, firstnameBox, phonenoBox, addressBox;
I would suggest you to get the values of these editText fields on button click listener, save these values as Strings and send these values as params to the doInBackground.
Your doInBackground is already ready to accept an array of String so you just need to get them as args values.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm getting NullPointerException while adding data from android app to MySQL database, so when I click to create a new product this exception occurs. This is my code to add new product in my database:
public class NewProductActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputPrice;
EditText inputDesc;
// url to create new product
private static String url_create_product = "http://192.168.56.1/products/create_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_product);
// Edit Text
inputName = (EditText) findViewById(R.id.inputName);
inputPrice = (EditText) findViewById(R.id.inputPrice);
inputDesc = (EditText) findViewById(R.id.inputDesc);
// Create button
Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);
// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = inputName.getText().toString();
String price = inputPrice.getText().toString();
String description = inputDesc.getText().toString();
// creating new product in background thread
new CreateNewProduct().execute(name,price,description);
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String name = args[0],
price = args[1],
description = args[2];
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("price", price));
params.add(new BasicNameValuePair("description", description));
// getting JSON Object
// Note that create product url accepts POST method
**line 102** JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create 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 done
pDialog.dismiss();
}
}
}
I checked out my PHP code and it works fine:
<?php
$con = mysql_connect('localhost', 'root','');
mysql_select_db('database',$con);
$name = $_POST['name'];
$price = $_POST['price'];
$description = $_POST['description'];
$sql = "insert into products(name, price, description)
values('$name','$price','$description')";
mysql_query($sql);
?>
Logcat:
FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:856)
aused by: java.lang.NullPointerException
at com.example.hanen.test1.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:102)
at com.example.hanen.test1.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:68)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:856)
I don't have the answer to your question, because you haven't included line numbers on your listing, and I'm not going to hand-number them. Finding and fixing this type of error, though, is dead simple. Here are the steps:
Turn on line numbers in your IDE
Find the line in your code that corresponds to the topmost line in the stacktrace that refers to a line in your code. In this case that is line 102 in the file NewProductActivity.java
On that line, there will be an expression that looks like variable.something.
When that line is executed variable is null. Find out why.
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 7 years ago.
When i ran my Android Application, I got an android.os.NetworkOnMainThreadException error. I have also added the INTERNET permissions to the manifest file but still it shows this error. Please help advice on what to do. Thanks.
This is my logcat
03-06 11:40:55.721: W/dalvikvm(2142): threadid=1: thread exiting with uncaught exception (group=0x40014760)
03-06 11:40:55.740: E/AndroidRuntime(2142): FATAL EXCEPTION: main
03-06 11:40:55.740: E/AndroidRuntime(2142): android.os.NetworkOnMainThreadException
03-06 11:40:55.740: E/AndroidRuntime(2142): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1077)
03-06 11:40:55.740: E/AndroidRuntime(2142): at dalvik.system.BlockGuard$WrappedNetworkSystem.connect(BlockGuard.java:368)
03-06 11:40:55.740: E/AndroidRuntime(2142): at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:208)
03-06 11:40:55.740: E/AndroidRuntime(2142): at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:431)
03-06 11:40:55.740: E/AndroidRuntime(2142): at java.net.Socket.connect(Socket.java:901)
03-06 11:40:55.740: E/AndroidRuntime(2142): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
03-06 11:40:55.740: E/AndroidRuntime(2142): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:143)
03-06 11:40:55.740: E/AndroidRuntime(2142): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
03-06 11:40:55.740: E/AndroidRuntime(2142): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
03-06 11:40:55.740: E/AndroidRuntime(2142): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
03-06 11:40:55.740: E/AndroidRuntime(2142): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
03-06 11:40:55.740: E/AndroidRuntime(2142): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
03-06 11:40:55.740: E/AndroidRuntime(2142): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
03-06 11:40:55.740: E/AndroidRuntime(2142): at com.example.testexternaldatabase.JSONParser.makeHttpRequest(JSONParser.java:62)
03-06 11:40:55.740: E/AndroidRuntime(2142): at com.example.testexternaldatabase.EditTicketActivity$GetProductDetails$1.run(EditTicketActivity.java:135)
03-06 11:40:55.740: E/AndroidRuntime(2142): at android.os.Handler.handleCallback(Handler.java:587)
03-06 11:40:55.740: E/AndroidRuntime(2142): at android.os.Handler.dispatchMessage(Handler.java:92)
03-06 11:40:55.740: E/AndroidRuntime(2142): at android.os.Looper.loop(Looper.java:132)
03-06 11:40:55.740: E/AndroidRuntime(2142): at android.app.ActivityThread.main(ActivityThread.java:4025)
03-06 11:40:55.740: E/AndroidRuntime(2142): at java.lang.reflect.Method.invokeNative(Native Method)
03-06 11:40:55.740: E/AndroidRuntime(2142): at java.lang.reflect.Method.invoke(Method.java:491)
03-06 11:40:55.740: E/AndroidRuntime(2142): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
03-06 11:40:55.740: E/AndroidRuntime(2142): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
03-06 11:40:55.740: E/AndroidRuntime(2142): at dalvik.system.NativeStart.main(Native Method)
This is my get_message_details.php file. This file is to accept input as a JSON Array and the messages table will be updated.
<?php
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
$_GET["pid"] = "1";
// check for post data
if (isset($_GET["pid"])) {
$message_id = $_GET['pid'];
// get a message from messages table
$result = mysql_query("SELECT *FROM messages WHERE message_id = '".$message_id."'");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$message = array();
$message["message_id"] = $result["message_id"];
$message["subject"] = $result["subject"];
$message["type"] = $result["type"];
$message["description"] = $result["description"];
$response["success"] = 1;
// user node
$response["message"] = array();
array_push($response["message"], $message);
// echoing JSON response
echo json_encode($response);
} else {
// no message found
$response["success"] = 0;
$response["message"] = "No message found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no message found
$response["success"] = 0;
$response["message"] = "No message found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
This is my EditTicketActivity.java class.
package com.example.testexternaldatabase;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;
public class EditTicketActivity extends Activity {
EditText txtSubject;
EditText txtType;
EditText txtDesc;
Button btnSave;
Button btnDelete;
String pid;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
static GetIPAddress getIPaddress = new GetIPAddress();
// single product url
private static String url_product_details = getIPaddress.getIP()+"get_message_details.php";;
// url to update product
private static String url_update_product = getIPaddress.getIP()+"update_message.php";
// url to delete product
private static String url_delete_product = getIPaddress.getIP()+"delete_message.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "message";
private static final String TAG_PID = "message_id";
private static final String TAG_NAME = "subject";
private static final String TAG_PRICE = "type";
private static final String TAG_DESCRIPTION = "description";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_ticket);
//url_product_details = getIPaddress.getIP()+"get_message_details.php";
//url_update_product = getIPaddress.getIP()+"update_message.php";
//url_delete_product = getIPaddress.getIP()+"delete_message.php";
// save button
btnSave = (Button)findViewById(R.id.editticket_save);
btnDelete = (Button)findViewById(R.id.editticket_delete);
// 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
new SaveProductDetails().execute();
}
});
// Delete button click event
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// deleting product in background thread
new DeleteProduct().execute();
}
});
}
/**
* 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(EditTicketActivity.this);
pDialog.setMessage("Loading Tickets. 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_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 messageObj = json
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject message = messageObj.getJSONObject(0);
// product with this pid found
// Edit Text
txtSubject = (EditText) findViewById(R.id.editticket_subject);
txtType = (EditText) findViewById(R.id.editticket_type);
txtDesc = (EditText) findViewById(R.id.editticket_description);
// display product data in EditText
txtSubject.setText(message.getString(TAG_NAME));
txtType.setText(message.getString(TAG_PRICE));
txtDesc.setText(message.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();
}
}
/**
* 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(EditTicketActivity.this);
pDialog.setMessage("Saving product ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Saving product
* */
protected String doInBackground(String... args) {
// getting updated data from EditTexts
String subject = txtSubject.getText().toString();
String type = txtType.getText().toString();
String description = txtDesc.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_PID, pid));
params.add(new BasicNameValuePair(TAG_NAME, subject));
params.add(new BasicNameValuePair(TAG_PRICE, type));
params.add(new BasicNameValuePair(TAG_DESCRIPTION, description));
// sending modified data through http request
// Notice that update product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_update_product,
"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(EditTicketActivity.this);
pDialog.setMessage("Deleting Product...");
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("pid", pid));
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
url_delete_product, "POST", params);
// check your log for json response
Log.d("Delete Product", 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();
}
}
}
What am I doing wrong here and how could I fix it? :) Thanks!!
You should not use UI element in Asynctask doInBackground() method. Move all UI updation code to onPostExecute() method of the AsyncTask
Example you can refer
AsyncTask Android example
Immersed in the development of my program, I encounter an error that seems to me not really speaking.
So here's my logcat in the order and the java code:
When I click on the item in my listview it should return me the contact information for the update.
public class MajContactActivity extends Activity {
EditText txtNom;
EditText txtPrenom;
EditText txtNummobile;
EditText txtNumfixe;
EditText txtEmail;
EditText txtAdresse;
EditText txtProfession;
Button btnSav;
Button btnSup;
String idCONTACT;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single contact url
private static final String url_detail_contact = "http://10.0.2.2/contactCloud/detail_contact.php";
// url to update contact
private static final String url_update_contact = "http://10.0.2.2/contactCloud/update_contact.php";
// url to delete contact
private static final String url_delete_contact = "http://10.0.2.2/contactCloud/delete_contact.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_CONTACT = "personne";
private static final String TAG_IDCONTACT = "idCONTACT";
private static final String TAG_NOM = "nom";
private static final String TAG_PRENOM = "prenom";
private static final String TAG_NUMMOBILE = "numero_mobile";
private static final String TAG_NUMFIXE = "numero_fixe";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADRESSE = "adresse";
private static final String TAG_PROFESSION = "profession";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maj_contact);
// save button
btnSav = (Button) findViewById(R.id.btnSav);
btnSup = (Button) findViewById(R.id.btnSup);
// getting contact details from intent
Intent i = getIntent();
// getting contact id (idCONTACT) from intent
idCONTACT = i.getStringExtra(TAG_IDCONTACT);
// Getting complete contact details in background thread
new GetDetailContact().execute();
// save button click event
btnSav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// starting background task to update contact
new SavDetailContact().execute();
}
});
// Delete button click event
btnSup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// deleting contact in background thread
new SupContact().execute();
}
});
}
/**
* Background Async Task to Get complete contact details
* */
class GetDetailContact extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MajContactActivity.this);
pDialog.setMessage("Chargement du contact. Veuillez patientez...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting contact details in background thread
* */
protected String doInBackground(String... params) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("idCONTACT", idCONTACT));
// getting contact details by making HTTP request
// Note that contact details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(url_detail_contact, "GET", params1);
// check your log for json response
Log.d("Detail contact unique", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received contact details
JSONArray personneObj = json.getJSONArray(TAG_CONTACT); // JSON Array
// get first contact object from JSON Array
JSONObject personne = personneObj.getJSONObject(0);
// contact with this idCONTACT found
// Edit Text
txtNom = (EditText) findViewById(R.id.inputNom);
txtPrenom = (EditText) findViewById(R.id.inputPrenom);
txtNummobile = (EditText) findViewById(R.id.inputNumMobile);
txtNumfixe = (EditText) findViewById(R.id.inputNumFixe);
txtEmail = (EditText) findViewById(R.id.inputEmail);
txtAdresse = (EditText) findViewById(R.id.inputAdresse);
txtProfession = (EditText) findViewById(R.id.inputProfession);
// display contact data in EditText
txtNom.setText(personne.getString(TAG_NOM));
txtPrenom.setText(personne.getString(TAG_PRENOM));
txtNummobile.setText(personne.getString(TAG_NUMMOBILE));
txtNumfixe.setText(personne.getString(TAG_NUMFIXE));
txtEmail.setText(personne.getString(TAG_EMAIL));
txtAdresse.setText(personne.getString(TAG_ADRESSE));
txtProfession.setText(personne.getString(TAG_PROFESSION));
}else{
// contact with idCONTACT 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 contact Details
* */
class SavDetailContact extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MajContactActivity.this);
pDialog.setMessage("Sauvegarde du contact ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Saving contact
* */
protected String doInBackground(String... args) {
// getting updated data from EditTexts
String nom = txtNom.getText().toString();
String prenom = txtPrenom.getText().toString();
String numero_mobile = txtNummobile.getText().toString();
String numero_fixe = txtNumfixe.getText().toString();
String email = txtEmail.getText().toString();
String adresse = txtAdresse.getText().toString();
String profession = txtProfession.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_IDCONTACT, idCONTACT));
params.add(new BasicNameValuePair(TAG_NOM, nom));
params.add(new BasicNameValuePair(TAG_PRENOM, prenom));
params.add(new BasicNameValuePair(TAG_NUMMOBILE, numero_mobile));
params.add(new BasicNameValuePair(TAG_NUMFIXE, numero_fixe));
params.add(new BasicNameValuePair(TAG_EMAIL, email));
params.add(new BasicNameValuePair(TAG_ADRESSE, adresse));
params.add(new BasicNameValuePair(TAG_PROFESSION, profession));
// sending modified data through http request
// Notice that update contact 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 contact update
setResult(100, i);
finish();
} else {
// failed to update contact
}
} 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 contact uupdated
pDialog.dismiss();
}
}
/*****************************************************************
* Background Async Task to Delete Product
* */
class SupContact extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MajContactActivity.this);
pDialog.setMessage("Suppression du contact...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Deleting contact
* */
protected String doInBackground(String... args) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("idCONTACT", idCONTACT));
// getting contact details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(url_delete_contact, "POST", params);
// check your log for json response
Log.d("Suppression du contact", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// contact successfully deleted
// notify previous activity by sending code 100
Intent i = getIntent();
// send result code 100 to notify about contact 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 contact deleted
pDialog.dismiss();
}
}
}
12-05 19:46:28.287: E/AndroidRuntime(1161): FATAL EXCEPTION: AsyncTask #
212-05 19:46:28.287: E/AndroidRuntime(1161): java.lang.RuntimeException: An error occured while executing doInBackground()
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.os.AsyncTask$3.done(AsyncTask.java:299)
12-05 19:46:28.287: E/AndroidRuntime(1161): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
12-05 19:46:28.287: E/AndroidRuntime(1161): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
12-05 19:46:28.287: E/AndroidRuntime(1161): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
12-05 19:46:28.287: E/AndroidRuntime(1161): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
12-05 19:46:28.287: E/AndroidRuntime(1161): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
12-05 19:46:28.287: E/AndroidRuntime(1161): at java.lang.Thread.run(Thread.java:841)
12-05 19:46:28.287: E/AndroidRuntime(1161): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:5908)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:869)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.view.ViewGroup.invalidateChild(ViewGroup.java:4253)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.view.View.invalidate(View.java:10482)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.widget.TextView.invalidateRegion(TextView.java:4591)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.widget.TextView.invalidateCursor(TextView.java:4534)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.widget.TextView.spanChange(TextView.java:7412)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.widget.TextView$ChangeWatcher.onSpanAdded(TextView.java:9103)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.text.SpannableStringBuilder.sendSpanAdded(SpannableStringBuilder.java:979)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:688)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:588)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.text.Selection.setSelection(Selection.java:76)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.text.Selection.setSelection(Selection.java:87)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.text.method.ArrowKeyMovementMethod.initialize(ArrowKeyMovementMethod.java:302)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.widget.TextView.setText(TextView.java:3759)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.widget.TextView.setText(TextView.java:3629)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.widget.EditText.setText(EditText.java:80)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.widget.TextView.setText(TextView.java:3604)
12-05 19:46:28.287: E/AndroidRuntime(1161): at fr.paris8.contactcloud.MajContactActivity$GetDetailContact.doInBackground(MajContactActivity.java:162)
12-05 19:46:28.287: E/AndroidRuntime(1161): at fr.paris8.contactcloud.MajContactActivity$GetDetailContact.doInBackground(MajContactActivity.java:1)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.os.AsyncTask$2.call(AsyncTask.java:287)
12-05 19:46:28.287: E/AndroidRuntime(1161): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
12-05 19:46:28.287: E/AndroidRuntime(1161): ... 4 more
12-05 19:46:36.289: E/WindowManager(1161): Activity fr.paris8.contactcloud.MajContactActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41803700 V.E..... R.....ID 0,0-480,144} that was originally added here
12-05 19:46:36.289: E/WindowManager(1161): android.view.WindowLeaked: Activity fr.paris8.contactcloud.MajContactActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41803700 V.E..... R.....ID 0,0-480,144} that was originally added here
12-05 19:46:36.289: E/WindowManager(1161): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:345)
12-05 19:46:36.289: E/WindowManager(1161): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:239)
12-05 19:46:36.289: E/WindowManager(1161): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
12-05 19:46:36.289: E/WindowManager(1161): at android.app.Dialog.show(Dialog.java:281)
12-05 19:46:36.289: E/WindowManager(1161): at fr.paris8.contactcloud.MajContactActivity$GetDetailContact.onPreExecute(MajContactActivity.java:120)
12-05 19:46:36.289: E/WindowManager(1161): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
12-05 19:46:36.289: E/WindowManager(1161): at android.os.AsyncTask.execute(AsyncTask.java:534)
12-05 19:46:36.289: E/WindowManager(1161): at fr.paris8.contactcloud.MajContactActivity.onCreate(MajContactActivity.java:81)
12-05 19:46:36.289: E/WindowManager(1161): at android.app.Activity.performCreate(Activity.java:5133)
12-05 19:46:36.289: E/WindowManager(1161): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
12-05 19:46:36.289: E/WindowManager(1161): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
12-05 19:46:36.289: E/WindowManager(1161): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
12-05 19:46:36.289: E/WindowManager(1161): at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-05 19:46:36.289: E/WindowManager(1161): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
12-05 19:46:36.289: E/WindowManager(1161): at android.os.Handler.dispatchMessage(Handler.java:99)
12-05 19:46:36.289: E/WindowManager(1161): at android.os.Looper.loop(Looper.java:137)
12-05 19:46:36.289: E/WindowManager(1161): at android.app.ActivityThread.main(ActivityThread.java:5103)
12-05 19:46:36.289: E/WindowManager(1161): at java.lang.reflect.Method.invokeNative(Native Method)
12-05 19:46:36.289: E/WindowManager(1161): at java.lang.reflect.Method.invoke(Method.java:525)
12-05 19:46:36.289: E/WindowManager(1161): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-05 19:46:36.289: E/WindowManager(1161): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-05 19:46:36.289: E/WindowManager(1161): at dalvik.system.NativeStart.main(Native Method)
I do not see or just wrong?
thank you for the help!
Try this..
You cannot do the initialize inside doInBackground you need to with in the onCreate. Same like that you cannot set the text inside the doInBackground need to in onPostExecute.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maj_contact);
// save button
btnSav = (Button) findViewById(R.id.btnSav);
btnSup = (Button) findViewById(R.id.btnSup);
// Edit Text
txtNom = (EditText) findViewById(R.id.inputNom);
txtPrenom = (EditText) findViewById(R.id.inputPrenom);
txtNummobile = (EditText) findViewById(R.id.inputNumMobile);
txtNumfixe = (EditText) findViewById(R.id.inputNumFixe);
txtEmail = (EditText) findViewById(R.id.inputEmail);
txtAdresse = (EditText) findViewById(R.id.inputAdresse);
txtProfession = (EditText) findViewById(R.id.inputProfession);
// getting contact details from intent
Intent i = getIntent();
// getting contact id (idCONTACT) from intent
idCONTACT = i.getStringExtra(TAG_IDCONTACT);
// Getting complete contact details in background thread
new GetDetailContact().execute();
// save button click event
btnSav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// starting background task to update contact
new SavDetailContact().execute();
}
});
// Delete button click event
btnSup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// deleting contact in background thread
new SupContact().execute();
}
});
}
/**
* Background Async Task to Get complete contact details
* */
class GetDetailContact extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MajContactActivity.this);
pDialog.setMessage("Chargement du contact. Veuillez patientez...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting contact details in background thread
* */
protected String doInBackground(String... params) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("idCONTACT", idCONTACT));
// getting contact details by making HTTP request
// Note that contact details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(url_detail_contact, "GET", params1);
// check your log for json response
Log.d("Detail contact unique", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received contact details
JSONArray personneObj = json.getJSONArray(TAG_CONTACT); // JSON Array
// get first contact object from JSON Array
JSONObject personne = personneObj.getJSONObject(0);
// contact with this idCONTACT found
}else{
// contact with idCONTACT 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();
// display contact data in EditText
txtNom.setText(personne.getString(TAG_NOM));
txtPrenom.setText(personne.getString(TAG_PRENOM));
txtNummobile.setText(personne.getString(TAG_NUMMOBILE));
txtNumfixe.setText(personne.getString(TAG_NUMFIXE));
txtEmail.setText(personne.getString(TAG_EMAIL));
txtAdresse.setText(personne.getString(TAG_ADRESSE));
txtProfession.setText(personne.getString(TAG_PROFESSION));
}
}
/**
* Background Async Task to Save contact Details
* */
class SavDetailContact extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MajContactActivity.this);
pDialog.setMessage("Sauvegarde du contact ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Saving contact
* */
protected String doInBackground(String... args) {
// getting updated data from EditTexts
String nom = txtNom.getText().toString();
String prenom = txtPrenom.getText().toString();
String numero_mobile = txtNummobile.getText().toString();
String numero_fixe = txtNumfixe.getText().toString();
String email = txtEmail.getText().toString();
String adresse = txtAdresse.getText().toString();
String profession = txtProfession.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_IDCONTACT, idCONTACT));
params.add(new BasicNameValuePair(TAG_NOM, nom));
params.add(new BasicNameValuePair(TAG_PRENOM, prenom));
params.add(new BasicNameValuePair(TAG_NUMMOBILE, numero_mobile));
params.add(new BasicNameValuePair(TAG_NUMFIXE, numero_fixe));
params.add(new BasicNameValuePair(TAG_EMAIL, email));
params.add(new BasicNameValuePair(TAG_ADRESSE, adresse));
params.add(new BasicNameValuePair(TAG_PROFESSION, profession));
// sending modified data through http request
// Notice that update contact url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_update_contact,"POST", params);
// check json success tag
try {
int success = json.getInt(TAG_SUCCESS);
} 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 contact uupdated
pDialog.dismiss();
if (success == 1) {
// successfully updated
Intent i = getIntent();
// send result code 100 to notify about contact update
setResult(100, i);
finish();
} else {
// failed to update contact
}
}
}
EDIT :
class GetDetailContact extends AsyncTask<String, void, JSONObject> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MajContactActivity.this);
pDialog.setMessage("Chargement du contact. Veuillez patientez...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting contact details in background thread
* */
protected JSONObject doInBackground(String... params) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("idCONTACT", idCONTACT));
// getting contact details by making HTTP request
// Note that contact details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(url_detail_contact, "GET", params1);
// check your log for json response
Log.d("Detail contact unique", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received contact details
JSONArray personneObj = json.getJSONArray(TAG_CONTACT); // JSON Array
// get first contact object from JSON Array
JSONObject personne = personneObj.getJSONObject(0);
// contact with this idCONTACT found
return personne;
}else{
// contact with idCONTACT not found
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(JSONObject personne) {
// dismiss the dialog once got all details
pDialog.dismiss();
// display contact data in EditText
txtNom.setText(personne.getString(TAG_NOM));
txtPrenom.setText(personne.getString(TAG_PRENOM));
txtNummobile.setText(personne.getString(TAG_NUMMOBILE));
txtNumfixe.setText(personne.getString(TAG_NUMFIXE));
txtEmail.setText(personne.getString(TAG_EMAIL));
txtAdresse.setText(personne.getString(TAG_ADRESSE));
txtProfession.setText(personne.getString(TAG_PROFESSION));
}
}
I crate app to check the database for login info by using jsonParser.makeHttpRequest
I try to make my app to stop after 10 second in case there is no internet connection or no response from the server. The code work however when the login button click for the second time the app crash
Could anyone please support why this happen
please see the below for the code
package com.example.pfms;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
private String id,pass,p,logincheck;
private EditText username,password;
private Button login;
private CheckLogin cl;
private ProgressDialog pDialog;
private SharedPreferences prefs;
JSONParser jsonParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
private static final String url = "http://192.168.1.11/pfm/get_id.php";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
cl= new CheckLogin();
username=(EditText)findViewById(R.id.editText1);
password=(EditText)findViewById(R.id.editText2);
login=(Button)findViewById(R.id.button1);
prefs = this.getSharedPreferences("com.example.pfms", MODE_PRIVATE);
logincheck=prefs.getString("com.example.pfms.login", "0");
if(!logincheck.equals("0")){
Intent i=new Intent(MainActivity.this,TechOption.class);
Bundle info=new Bundle();
info.putString("techid",logincheck);
i.putExtras(info);
startActivity(i);
}
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cl.execute();
}
});
}
class CheckLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Checking Login info. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
p="0";
pass="0";
Log.d("test", "dialog");
}
/**
* 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 {
Log.d("test", "run");
// Building Parameters
List<NameValuePair> params2 = new ArrayList<NameValuePair>();
id=username.getText().toString();
pass=password.getText().toString();
params2.add(new BasicNameValuePair("id",id));
// getting product details by making HTTP request
// Note that product details url will use GET request
// HttpParams httpParameters = new BasicHttpParams();
// HttpConnectionParams.setConnectionTimeout(httpParameters, 30000);
// HttpConnectionParams.setSoTimeout(httpParameters, 30000);
// DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
messageHandler.sendEmptyMessageDelayed(0, 10000);
Log.d("test", "before");
JSONObject json = jsonParser.makeHttpRequest(
url, "GET", params2);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
Log.d("test", "before success");
if (success == 1) {
// successfully received product details
JSONArray actiondetail = json
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject c = actiondetail.getJSONObject(0);
// Storing each json item in variable
p="";
p = c.getString("pass");
Log.d("info", "p="+p);
Log.d("info", "pass="+pass);
}else{
Toast.makeText(getBaseContext(), "Wrong Username", Toast.LENGTH_LONG).show();
}
Log.d("test", "after success");
} catch (JSONException e) {
//pDialog.dismiss();
//Toast.makeText(getBaseContext(), "Please check internet connection", Toast.LENGTH_LONG).show();
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();
Log.d("test", "dismiss dailog");
if(p.contentEquals(pass)){
Intent i=new Intent(MainActivity.this,TechOption.class);
Bundle info=new Bundle();
info.putString("techid",id);
i.putExtras(info);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("com.example.pfms.login",id);
editor.commit();
startActivity(i);
}
else{
Toast.makeText(getBaseContext(), "Wrong Password", Toast.LENGTH_LONG).show();
}
}
}
private Handler messageHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
pDialog.dismiss();
Toast.makeText(getBaseContext(), "Please check internet connection", Toast.LENGTH_LONG).show();
cl.cancel(true);
}
};
}
please see the below for Error :
11-05 09:37:09.053: D/AndroidRuntime(1398): Shutting down VM
11-05 09:37:09.053: W/dalvikvm(1398): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-05 09:37:09.123: E/AndroidRuntime(1398): FATAL EXCEPTION: main
11-05 09:37:09.123: E/AndroidRuntime(1398): java.lang.IllegalStateException: Cannot execute task: the task is already running.
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:575)
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.os.AsyncTask.execute(AsyncTask.java:534)
11-05 09:37:09.123: E/AndroidRuntime(1398): at com.example.pfms.MainActivity$2.onClick(MainActivity.java:79)
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.view.View.performClick(View.java:4240)
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.view.View$PerformClick.run(View.java:17721)
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.os.Handler.handleCallback(Handler.java:730)
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.os.Handler.dispatchMessage(Handler.java:92)
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.os.Looper.loop(Looper.java:137)
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-05 09:37:09.123: E/AndroidRuntime(1398): at java.lang.reflect.Method.invokeNative(Native Method)
11-05 09:37:09.123: E/AndroidRuntime(1398): at java.lang.reflect.Method.invoke(Method.java:525)
11-05 09:37:09.123: E/AndroidRuntime(1398): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-05 09:37:09.123: E/AndroidRuntime(1398): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-05 09:37:09.123: E/AndroidRuntime(1398): at dalvik.system.NativeStart.main(Native Method)
An object of an AsyncTask can be run only once. That is why you are getting the IllegalStateException.
Remove the object instantiation [cl= new CheckLogin()] from onCreate().
And instead,
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new CheckLogin.execute(); // creating an anonymous object of the AsyncTask makes sure that you never use it again which prevents any IllegalStateExceptions
}
});
i am the newbee in Android Development.
I had developed an app contains a login, the credentials must be passed in the text field and later it will call a webservice.
I am facing the issue as user and password is not getting copied at the required position.
Please help me out.
package com.authorwjf.http_get;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Main extends Activity implements OnClickListener {
EditText txtUserName;
EditText txtPassword;
#Override
public void onCreate(Bundle savedInstanceState) {
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
String user= txtUserName.getText().toString();
String pass= txtPassword.getText().toString();
System.out.println("USERRRR"+user);
System.out.println(pass);
//String user="at#ril.com";
//String pass= "123456";
String accessTokenQry = "{"+
"\"uid\":\""+user+"\","+
"\"password\":\""+pass+"\","+
"\"consumptionDeviceId\":\"fder-et3w-3adw2-2erf\","+
"\"consumptionDeviceName\":\"Samsung Tab\""+
"}";
HttpPost httpPost = new HttpPost("http://devssg01.ril.com:8080/v2/dip/auth/login");
httpPost.setHeader("Content-Type",
"application/json");
httpPost.setHeader("X-API-Key",
"l7xx7914b8704b2d4b029ab9c4b1b9c66dbf");
StringEntity input;
try {
input = new StringEntity(accessTokenQry);
httpPost.setEntity(input);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String text = null;
try {
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results!=null) {
EditText et = (EditText)findViewById(R.id.my_edit);
et.setText(results);
}
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(true);
}
}
}
The LogCat Output is:
08-10 01:20:23.977: W/dalvikvm(760): threadid=14: thread exiting with uncaught exception (group=0x414c4700)
08-10 01:20:23.984: E/AndroidRuntime(760): FATAL EXCEPTION: AsyncTask #4
08-10 01:20:23.984: E/AndroidRuntime(760): java.lang.RuntimeException: An error occured while executing doInBackground()
08-10 01:20:23.984: E/AndroidRuntime(760): at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.lang.Thread.run(Thread.java:841)
08-10 01:20:23.984: E/AndroidRuntime(760): Caused by: java.lang.NullPointerException
08-10 01:20:23.984: E/AndroidRuntime(760): at com.authorwjf.http_get.Main$LongRunningGetIO.doInBackground(Main.java:66)
08-10 01:20:23.984: E/AndroidRuntime(760): at com.authorwjf.http_get.Main$LongRunningGetIO.doInBackground(Main.java:1)
08-10 01:20:23.984: E/AndroidRuntime(760): at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
08-10 01:20:23.984: E/AndroidRuntime(760): ... 3 more
You are trying to initialize EditTexts before layout loaded.
If you want to get EditText on layout, you must initialize it after layout loaded.
Here is correct code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
}
use this
EditText textw3d =(EditText) findViewById(R.id.editText3d);
final String strd3d = textw3d.getText().toString();
I suggest following change in your code.
Just write following lines
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
above
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
Move the lines where you get the reference to text views after the setContentView function call:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
}
The fact is you need to call setContentView before initializing any widget in your layout because this is the call that "loads" your layout defined in layout_main.xml file into your activity.
Thanks a lot Guyz,
The issue is resolved now.
Special appreciation to JustWork
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
}