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
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.
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.
I am trying to delete an item in my listview but keep getting an ArrayOutOfBoundException yet my LOG shows successful deletion from my Localhost and if you open it back it reflects the changes...
Not to sure how to fix the Exception that causes my app to crash? Any Ideas?
Class with Async Tasks:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all_locations);
// Hashmap for ListView
profileList = new ArrayList<HashMap<String, String>>();
deleteLocation = (Button) findViewById(R.id.deleteLocation);
locationCount = (TextView) findViewById(R.id.locationCount);
lo = (ListView) findViewById(android.R.id.list);
//setup adapter first //now no items, after getting items (LoadAllLocations) will update it
adapter = new SimpleAdapter(
ViewAllLocations.this, profileList,
R.layout.locationitem, new String[]{TAG_ID,
TAG_LATITUDE, TAG_LONGITUDE},
new int[]{R.id.id, R.id.latitude, R.id.longitude});
// updating listview
setListAdapter(adapter);
// Loading products in Background Thread
new LoadAllLocation().execute();
// getting product details from intent
Intent i = getIntent();
// getting product id (pid) from intent
id = i.getStringExtra(TAG_ID);
// Get listview
ListView lo = getListView();
lo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
new DeleteLocation(position).execute();
Map<String, String> item = profileList.get(position);
String selectedItemId = item.get(TAG_ID);
new DeleteLocation(position).execute(selectedItemId);
}
});
}
/**
* **************************************************************
* Background Async Task to Delete Product
*/
class DeleteLocation extends AsyncTask<String, String, Integer> {
int deleteItemPosition;
public DeleteLocation(int position) {
// TODO Auto-generated constructor stub
this.deleteItemPosition = position;
}
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
//pDialog = new ProgressDialog(ViewAllLocations.this);
//pDialog.setMessage("Deleting Location...");
//pDialog.setIndeterminate(false);
//pDialog.setCancelable(true);
// pDialog.show();
}
/**
* Deleting product
*/
protected Integer doInBackground(String... args) {
String selectedId = args[0];
// Check for success tag
int success = 0; //0=failed 1=success
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", selectedId));
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
url_delete_profile, "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);
//you cant update UI on worker thread, it must be done on UI thread
// Toast.makeText(getApplicationContext(), "Location Deleted",
// Toast.LENGTH_SHORT).show();
//finish();
// }
} catch (JSONException e) {
e.printStackTrace();
}
return success;
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(Integer result) {
// dismiss the dialog once product deleted
if (result == 1) {
//success
//delete from list and update listview
profileList.remove(deleteItemPosition);
adapter.notifyDataSetChanged();
//pDialog.dismiss();
} else {
//failed
}
}
}
/**
* Background Async Task to Load all product by making HTTP Request
*/
class LoadAllLocation extends AsyncTask<String, String, Integer> {
int success;
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewAllLocations.this);
pDialog.setMessage("Loading Locations. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
*/
protected Integer doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(url_all_profile, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Profiles: ", json.toString());
try {
// Checking for SUCCESS TAG
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
userprofile = json.getJSONArray(TAG_LOCATION);
// looping through All Products
for (int i = 0; i < userprofile.length(); i++) {
JSONObject c = userprofile.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String latitude = c.getString(TAG_LATITUDE);
String longitude = c.getString(TAG_LONGITUDE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_LATITUDE, latitude);
map.put(TAG_LONGITUDE, longitude);
// adding HashList to ArrayList
profileList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
//Intent i = new Intent(getApplicationContext(),
// UserLocation.class);
// Closing all previous activities
// i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return success;
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(Integer result) {
// dismiss the dialog after getting all products
pDialog.dismiss();
locationCount.setText("" + profileList.size());
if (result == 1) {
//success
//update adapter items
adapter.notifyDataSetChanged();
} else {
//failed
//launch activity here
}
}
}
LOG: Delete Successful but still an error?
04-25 20:08:32.463 22736-23492/com.example.ankhit.saveme E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
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)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at com.example.ankhit.saveme.ViewAllLocations$DeleteLocation.doInBackground(ViewAllLocations.java:144)
at com.example.ankhit.saveme.ViewAllLocations$DeleteLocation.doInBackground(ViewAllLocations.java:117)
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)
04-25 20:08:32.713 22736-22736/com.example.ankhit.saveme D/AbsListView﹕ unregisterIRListener() is called
04-25 20:08:32.733 22736-23498/com.example.ankhit.saveme D/Delete Product﹕ {"message":"Profile successfully deleted","success":1}
Your problem is originating from here
new DeleteLocation(position).execute();
Map<String, String> item = profileList.get(position);
String selectedItemId = item.get(TAG_ID);
new DeleteLocation(position).execute(selectedItemId);
You are running two separate tasks, but only the second task is given a parameter. Therefore, the first task
new DeleteLocation(position).execute();
throws an exception, here
protected Integer doInBackground(String... args) {
String selectedId = args[0];
...
}
args[0] is out-of-bounds because no args were passed to execute.
The second task is done in a different thread and manages to finish before the exception from the first task is passed back up the call stack, which is why it still "works".
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));
}
}
Hey guys can you look at my errors, my logcat says it is because i am getting null pointer exception. i don't understand why. I just added a String variable which is "Email" and make the value of my eadd which stands for email address equals to it, then i have these errors now. can you point to me the problem guys?
These are my codes:
**
public class LoginSub extends Activity {
public static String Email;
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputEmail;
EditText inputPassword;
TextView TextView1;
// url to create new product
//private static String url_create_product = "http://student-thesis.netii.net/log_in.php";
private static String url_create_product = "http://10.0.2.2/TheCalling/log_in.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Edit Text
inputEmail = (EditText) findViewById(R.id.inputEmail);
inputPassword = (EditText) findViewById(R.id.inputPassword);
// Create button
Button btnLogin = (Button) findViewById(R.id.btnLogin);
// button click event
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new phpconnect().execute();
}
});
Button btnReg = (Button) findViewById(R.id.btnReg);
// button click event
btnReg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Register.class);
startActivity(i);
}
});
}
/**
* Background Async Task to Create new product
* */
class phpconnect extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginSub.this);
pDialog.setMessage("Logging in..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String eadd = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("eadd", eadd));
params.add(new BasicNameValuePair("password", password));
// getting JSON Object
// Note that create product url accepts POST method
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);
Email.equals(eadd);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), Mapping.class);
startActivity(i);
// closing this screen
finish();
} else {
}
} 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();
}
}
}
**
and here's my logcat errors:
**
03-06 22:21:16.428: E/AndroidRuntime(1417): FATAL EXCEPTION: AsyncTask #1
03-06 22:21:16.428: E/AndroidRuntime(1417): java.lang.RuntimeException: An error occured while executing doInBackground()
03-06 22:21:16.428: E/AndroidRuntime(1417): at android.os.AsyncTask$3.done(AsyncTask.java:278)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
03-06 22:21:16.428: E/AndroidRuntime(1417): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.lang.Thread.run(Thread.java:856)
03-06 22:21:16.428: E/AndroidRuntime(1417): Caused by: java.lang.NullPointerException
03-06 22:21:16.428: E/AndroidRuntime(1417): at com.example.projectthesis.LoginSub$phpconnect.doInBackground(LoginSub.java:129)
03-06 22:21:16.428: E/AndroidRuntime(1417): at com.example.projectthesis.LoginSub$phpconnect.doInBackground(LoginSub.java:1)
03-06 22:21:16.428: E/AndroidRuntime(1417): at android.os.AsyncTask$2.call(AsyncTask.java:264)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
**
Thank you guys.
Remove this block from doInBackGround()
if (success == 1) {
// successfully created product
Intent i = new Intent(LoginSub.this, Mapping.class);
startActivity(i);
// closing this screen
finish();
} else {
}
And add it in onPostExecute() section
protected void onPostExecute(String file_url)
{
// dismiss the dialog once done
pDialog.dismiss();
if (success == 1)
{
// successfully created product
Intent i = new Intent(getApplicationContext(), Mapping.class);
startActivity(i);
// closing this screen
finish();
}
else
{
}
}
Some times getApplicationContext() wont provide the exact context values. So pass the
Context context; //declare
context=this;// assigning next line after setcontextview.
then pass the context instead of getApplicationContext() . and check it and also if you want to do any UI updates you are not supposed to do in doinBackground(). You have to do in post execute.
Hope this will help you.
I think because this line
new phpconnect().execute();
and
class phpconnect extends AsyncTask<String, String, String> {
You declare AsyncTask with <String, String, String> but you didn't pass any parameter in .exeute();
Moreover that, from your code you don't want any parameter for AsyncTask so you should declare your Asynctask like this
class phpconnect extends AsyncTask<Void, Void, Void> {