Still stuck on JSONParsing issue - java

I am stuck and gone crazy to resolve this issue but no luck with me. I tried all the guidelines that SO member giving me as i had asked this question before:( Thank all of you who respond. I search alot to resolve it but never succeed last hope is SO, so Kindly guide me where I go wrong and how can I resolve this JSONParsing? I posted data from PHP and want to get it on android EditText boxes. I code it but there are some issue which exist from the day one and not resolved yet. I got different LogCat errors on emulator and on Phone. I have posed you my java code and LogCat errors. Any guide will be precious for me.
my Java code is where i got errors:
// save button
btnSave = (Button) findViewById(R.id.btnSave);
// getting product details from intent
Intent i = getIntent();
// getting product id (pid) from intent
cid = i.getStringExtra(TAG_CID);
// save button click event
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// starting background task to update product
new SaveTaskDetails().execute();
}
});
}
#Override
protected void onStart() {
super.onStart();
// Getting complete product details in background thread
new GetTaskDetails().execute();
}
/**
* Background Async Task to Get complete product details
* */
class GetTaskDetails extends AsyncTask<String, String, JSONObject> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
tDialog = new ProgressDialog(My_Task.this);
tDialog.setTitle("Please Wait");
tDialog.setMessage("Retrieving Task Details.");
tDialog.setIndeterminate(false);
tDialog.setCancelable(true);
tDialog.show();
}
/**
* Getting task details in background thread
* #return
**/
protected JSONObject doInBackground(String... params1) {
JSONObject my_task = null;
// updating UI from Background Thread
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("cid", cid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = JSONParser.makeHttpRequest(
url_read_mytask, "GET", params);
// check your log for json response
// Log.d("Single Task Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray my_taskObj = json
.getJSONArray(TAG_MYTASK); // JSON Array
// get first product object from JSON Array
my_task = my_taskObj.getJSONObject(0);
}
else
{
// task with cid not found
}
}
catch (JSONException e) {
e.printStackTrace();
}
return my_task;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(JSONObject my_task) {
// dismiss the dialog once got all details
cus_name_txtbx = (EditText) findViewById(R.id.cus_name_txtbx);
try {
cus_name_txtbx.setText(my_task.getString(TAG_NAME));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
contact_no_txtbx = (EditText) findViewById(R.id.contact_no_txtbx);
try {
contact_no_txtbx.setText(my_task.getString(TAG_CONTACT));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ticket_no_txtbx = (EditText) findViewById(R.id.ticket_no_txtbx);
try {
ticket_no_txtbx.setText(my_task.getString(TAG_TICKET));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
task_detail_txtbx = (EditText) findViewById(R.id.task_detail_txtbx);
try {
task_detail_txtbx.setText(my_task.getString(TAG_TASKDETAIL));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tDialog.dismiss();
}
}
/**
* Background Async Task to Save product Details
* */
class SaveTaskDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
tDialog = new ProgressDialog(My_Task.this);
tDialog.setTitle("Please Wait");
tDialog.setMessage("Saving Task");
tDialog.setIndeterminate(false);
tDialog.setCancelable(true);
tDialog.show();
}
/**
* Saving product
* */
protected String doInBackground(String... args) {
// getting updated data from EditTexts
String cus_name = cus_name_txtbx.getText().toString();
String contact_no = contact_no_txtbx.getText().toString();
String ticket_no = ticket_no_txtbx.getText().toString();
String task_detail = task_detail_txtbx.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_CID, cid));
params.add(new BasicNameValuePair(TAG_NAME, cus_name));
params.add(new BasicNameValuePair(TAG_CONTACT, contact_no));
params.add(new BasicNameValuePair(TAG_TICKET, ticket_no));
params.add(new BasicNameValuePair(TAG_TASKDETAIL, task_detail));
// sending modified data through http request
// Notice that update product url accepts POST method
JSONObject json = JSONParser.makeHttpRequest(url_update_mytask,
"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
tDialog.dismiss();
}
}
My Logcat errors are:
01-01 11:28:52.549: E/WindowManager(31782): at java.lang.reflect.Method.invokeNative(Native Method)
01-01 11:38:15.149: E/WindowManager(1133): Activity com.example.visit.record.My_Task has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#4054ce88 that was originally added here
01-01 11:38:15.149: E/WindowManager(1133): android.view.WindowLeaked: Activity com.example.visit.record.My_Task has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#4054ce88 that was originally added here
01-01 11:38:15.149: E/WindowManager(1133): at android.view.ViewRoot.<init>(ViewRoot.java:277)
01-01 11:38:15.149: E/WindowManager(1133): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
01-01 11:38:15.149: E/WindowManager(1133): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
01-01 11:38:15.149: E/WindowManager(1133): at android.view.Window$LocalWindowManager.addView(Window.java:433)
01-01 11:38:15.149: E/WindowManager(1133): at android.app.Dialog.show(Dialog.java:288)
01-01 11:38:15.149: E/WindowManager(1133): at com.example.visit.record.My_Task$GetTaskDetails.onPreExecute(My_Task.java:139)
01-01 11:38:15.149: E/WindowManager(1133): at android.os.AsyncTask.execute(AsyncTask.java:391)
01-01 11:38:15.149: E/WindowManager(1133): at com.example.visit.record.My_Task.onStart(My_Task.java:118)
01-01 11:38:15.149: E/WindowManager(1133): at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1225)
01-01 11:38:15.149: E/WindowManager(1133): at android.app.Activity.performStart(Activity.java:3941)
01-01 11:38:15.149: E/WindowManager(1133): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1794)
01-01 11:38:15.149: E/WindowManager(1133): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1842)
01-01 11:38:15.149: E/WindowManager(1133): at android.app.ActivityThread.access$1500(ActivityThread.java:132)
01-01 11:38:15.149: E/WindowManager(1133): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1038)
01-01 11:38:15.149: E/WindowManager(1133): at android.os.Handler.dispatchMessage(Handler.java:99)
01-01 11:38:15.149: E/WindowManager(1133): at android.os.Looper.loop(Looper.java:143)
01-01 11:38:15.149: E/WindowManager(1133): at android.app.ActivityThread.main(ActivityThread.java:4268)
01-01 11:38:15.149: E/WindowManager(1133): at java.lang.reflect.Method.invokeNative(Native Method)
01-01 11:38:15.149: E/WindowManager(1133): at java.lang.reflect.Method.invoke(Method.java:507)
01-01 11:38:15.149: E/WindowManager(1133): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-01 11:38:15.149: E/WindowManager(1133): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-01 11:38:15.149: E/WindowManager(1133): at dalvik.system.NativeStart.main(Native Method)
Kindly guide.
I got an error on new GetTaskDetails().execute(); and on **tDialog.show();** on PreExecute of GetTaskDetails Class

The solution is to call dismiss() on the Dialog you created in
viewP.java:183 before exiting the Activity, e.g. in onPause().
Views have a reference to their parent Context (taken from constructor argument). If you leave an Activity without destroying Dialogs and other dynamically created Views, they still hold this reference to your Activity (if you created with this as
Context: like new ProgressDialog(this),
so, it cannot be collected by the GC, causing a memory leak.

you run your UI in background remove from them and in post execute you
can set (e.gcus_name_txtbx.setText(my_task.getString(TAG_NAME));) you
are not set them in doIn romove every UI into the doIn..

Related

Activity leaked window exception on Dialog.show() when starting a Fragment transaction from an Activity class

When I click on the CreateWorkout button, it goes to the fragment UserWorkoutPlanFragment() class specified in the FragmentTransaction. But the moment transaction starts I get an error.
I get this error:
05-22 19:23:35.873: E/WindowManager(1042): Activity com.fitserv.user.profilemenu.NewWorkout has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{4170dd80 V.E..... R.....ID 0,0-308,96} that was originally added here
05-22 19:23:35.873: E/WindowManager(1042): android.view.WindowLeaked: Activity com.fitserv.user.profilemenu.NewWorkout has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{4170dd80 V.E..... R.....ID 0,0-308,96} that was originally added here
05-22 19:23:35.873: E/WindowManager(1042): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354)
05-22 19:23:35.873: E/WindowManager(1042): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
05-22 19:23:35.873: E/WindowManager(1042): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
05-22 19:23:35.873: E/WindowManager(1042): at android.app.Dialog.show(Dialog.java:281)
05-22 19:23:35.873: E/WindowManager(1042): at com.fitserv.user.profilemenu.NewWorkout$NewWorkoutPlan.onPreExecute(NewWorkout.java:90)
05-22 19:23:35.873: E/WindowManager(1042): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
05-22 19:23:35.873: E/WindowManager(1042): at android.os.AsyncTask.execute(AsyncTask.java:534)
05-22 19:23:35.873: E/WindowManager(1042): at com.fitserv.user.profilemenu.NewWorkout$1.onClick(NewWorkout.java:70)
05-22 19:23:35.873: E/WindowManager(1042): at android.view.View.performClick(View.java:4204)
05-22 19:23:35.873: E/WindowManager(1042): at android.view.View$PerformClick.run(View.java:17355)
05-22 19:23:35.873: E/WindowManager(1042): at android.os.Handler.handleCallback(Handler.java:725)
05-22 19:23:35.873: E/WindowManager(1042): at android.os.Handler.dispatchMessage(Handler.java:92)
05-22 19:23:35.873: E/WindowManager(1042): at android.os.Looper.loop(Looper.java:137)
05-22 19:23:35.873: E/WindowManager(1042): at android.app.ActivityThread.main(ActivityThread.java:5041)
05-22 19:23:35.873: E/WindowManager(1042): at java.lang.reflect.Method.invokeNative(Native Method)
05-22 19:23:35.873: E/WindowManager(1042): at java.lang.reflect.Method.invoke(Method.java:511)
05-22 19:23:35.873: E/WindowManager(1042): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-22 19:23:35.873: E/WindowManager(1042): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-22 19:23:35.873: E/WindowManager(1042): at dalvik.system.NativeStart.main(Native Method)
This is my code:
public class NewWorkout extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputWorkoutName;
EditText inputWorkoutDate;
EditText inputExceriseName;
EditText inputSets;
EditText inputKg;
EditText inputReps;
EditText inputNotes;
// url to create new product
private static String url_create_workout = "http://ec2-54-77-51-119.eu-west-1.compute.amazonaws.com/android_connect/create_workout.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_addworkout);
// Edit Text
inputWorkoutName = (EditText) findViewById(R.id.inputWorkoutName);
inputWorkoutDate = (EditText) findViewById(R.id.inputWorkoutDate);
inputExceriseName = (EditText) findViewById(R.id.inputExceriseName);
inputSets = (EditText) findViewById(R.id.inputSets);
inputKg = (EditText) findViewById(R.id.inputKg);
inputReps = (EditText) findViewById(R.id.inputReps);
inputNotes = (EditText) findViewById(R.id.inputNotes);
// Create button
Button btnCreateWorkout = (Button) findViewById(R.id.btnCreateWorkout);
// button click event
btnCreateWorkout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new NewWorkoutPlan().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
class NewWorkoutPlan extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewWorkout.this);
pDialog.setMessage("Creating Your Workout Plan..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String workout_name = inputWorkoutName.getText().toString();
String workout_date = inputWorkoutDate.getText().toString();
String exercise_name = inputExceriseName.getText().toString();
String sets = inputSets.getText().toString();
String weight_kg = inputKg.getText().toString();
String reps = inputReps.getText().toString();
String notes = inputNotes.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("workout_name", workout_name));
params.add(new BasicNameValuePair("workout_date", workout_date));
params.add(new BasicNameValuePair("exercise_name", exercise_name));
params.add(new BasicNameValuePair("sets", sets));
params.add(new BasicNameValuePair("weight_kg", weight_kg));
params.add(new BasicNameValuePair("reps", reps));
params.add(new BasicNameValuePair("notes", notes));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_workout,
"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(), UserProfileActivity.class);
startActivity(i);
//closing this screen
finish();
**/
Fragment newFragment = new UserWorkoutPlanFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, newFragment);
transaction.commit();
UserWorkoutPlanFragment fd = new UserWorkoutPlanFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.frame_container, fd);
// content_frame is your FrameLayout container
ft.addToBackStack(null);
ft.commit();
} 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();
}
}
}
Can someone please help me out?
Thanks!
pDialog is causing the window leak. That is happening because you are doing the fragment transaction in in doInBackground and calling the dismiss method onPostExecute.
You should post the transaction code in onPostExecute after calling dismiss
I know that you are new in Android, but maybe you have already developed in other language, haven't you? Anyway, you should code using design patterns and do what you wanna do in its own specific class. Doing so, you'll avoid many errors like that one.
Take a look this website about design patterns: http://pt.slideshare.net/PedroVicenteGmezSnch/software-design-patterns-on-android
You need to execute the FragmentTransaction in the UI thread. It can be done from within doInBackground method by calling runOnUiThread:
runOnUiThread(new Runnable() {
#Override
public void run() {
Fragment newFragment = new UserWorkoutPlanFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, newFragment);
transaction.commit();
UserWorkoutPlanFragment fd = new UserWorkoutPlanFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.frame_container, fd);
// content_frame is your FrameLayout container
ft.addToBackStack(null);
ft.commit();
}
});
In the logcat error, there is:
at
com.fitserv.user.profilemenu.NewWorkout$NewWorkoutPlan.onPreExecute(NewWorkout.java:90)
05-22 19:23:35.873: E/WindowManager(1042): at
android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
So the problem is at onPreExecute method. I have not used ProgressDialog before but the issue is on the context parameter. in this case NewWorkout.this. It's not the correct context.
Code suggestions:
pDialog = new ProgressDialog( getApplicationContext() );
pDialog = new ProgressDialog( getActivity() );
pDialog = new
ProgressDialog( MainActivity.this );
Note: For MainActivity, you can use this code if it is declared as static.
The main issue, I think, is the context.
FYI: I find it interesting that the posted answers are somewhat different but some are concentrating on the dialog.

Android.os.NetworkOnMainThreadException Error [duplicate]

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

Async task crashing during doInBackground() [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am having a problem with my android app that i'm trying to develo,apparently it crushes when it's to execute doInBackground,my logcat looks like this:
08-19 04:40:57.046: D/request!(4766): starting
08-19 04:40:57.125: W/dalvikvm(4766): threadid=9: thread exiting with uncaught exception (group=0x40018578)
08-19 04:40:57.132: E/AndroidRuntime(4766): FATAL EXCEPTION: AsyncTask #1
08-19 04:40:57.132: E/AndroidRuntime(4766): java.lang.RuntimeException: An error occured while executing doInBackground()
08-19 04:40:57.132: E/AndroidRuntime(4766): at android.os.AsyncTask$3.done(AsyncTask.java:200)
08-19 04:40:57.132: E/AndroidRuntime(4766): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
08-19 04:40:57.132: E/AndroidRuntime(4766): at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
08-19 04:40:57.132: E/AndroidRuntime(4766): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
08-19 04:40:57.132: E/AndroidRuntime(4766): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
08-19 04:40:57.132: E/AndroidRuntime(4766): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
08-19 04:40:57.132: E/AndroidRuntime(4766): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
08-19 04:40:57.132: E/AndroidRuntime(4766): at java.lang.Thread.run(Thread.java:1019)
08-19 04:40:57.132: E/AndroidRuntime(4766): Caused by: java.lang.IllegalStateException: Target host must not be null, or set in parameters.
08-19 04:40:57.132: E/AndroidRuntime(4766): at org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.java:577)
08-19 04:40:57.132: E/AndroidRuntime(4766): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:292)
08-19 04:40:57.132: E/AndroidRuntime(4766): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-19 04:40:57.132: E/AndroidRuntime(4766): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-19 04:40:57.132: E/AndroidRuntime(4766): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-19 04:40:57.132: E/AndroidRuntime(4766): at com.example.prova1.JSONParser.makeHttpRequest(JSONParser.java:110)
08-19 04:40:57.132: E/AndroidRuntime(4766): at com.example.prova1.Login$AttemptLogin.doInBackground(Login.java:159)
08-19 04:40:57.132: E/AndroidRuntime(4766): at com.example.prova1.Login$AttemptLogin.doInBackground(Login.java:1)
08-19 04:40:57.132: E/AndroidRuntime(4766): at android.os.AsyncTask$2.call(AsyncTask.java:185)
08-19 04:40:57.132: E/AndroidRuntime(4766): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
08-19 04:40:57.132: E/AndroidRuntime(4766): ... 4 more
08-19 04:41:04.726: E/WindowManager(4766): Activity com.example.prova1.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#4054b1a8 that was originally added here
08-19 04:41:04.726: E/WindowManager(4766): android.view.WindowLeaked: Activity com.example.prova1.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#4054b1a8 that was originally added here
08-19 04:41:04.726: E/WindowManager(4766): at android.view.ViewRoot.<init>(ViewRoot.java:263)
08-19 04:41:04.726: E/WindowManager(4766): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:171)
08-19 04:41:04.726: E/WindowManager(4766): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:114)
08-19 04:41:04.726: E/WindowManager(4766): at android.view.Window$LocalWindowManager.addView(Window.java:424)
08-19 04:41:04.726: E/WindowManager(4766): at android.app.Dialog.show(Dialog.java:241)
08-19 04:41:04.726: E/WindowManager(4766): at com.example.prova1.Login$AttemptLogin.onPreExecute(Login.java:126)
08-19 04:41:04.726: E/WindowManager(4766): at android.os.AsyncTask.execute(AsyncTask.java:391)
08-19 04:41:04.726: E/WindowManager(4766): at com.example.prova1.Login.onClick(Login.java:93)
08-19 04:41:04.726: E/WindowManager(4766): at android.view.View.performClick(View.java:2485)
08-19 04:41:04.726: E/WindowManager(4766): at android.view.View$PerformClick.run(View.java:9080)
08-19 04:41:04.726: E/WindowManager(4766): at android.os.Handler.handleCallback(Handler.java:587)
08-19 04:41:04.726: E/WindowManager(4766): at android.os.Handler.dispatchMessage(Handler.java:92)
08-19 04:41:04.726: E/WindowManager(4766): at android.os.Looper.loop(Looper.java:130)
08-19 04:41:04.726: E/WindowManager(4766): at android.app.ActivityThread.main(ActivityThread.java:3687)
08-19 04:41:04.726: E/WindowManager(4766): at java.lang.reflect.Method.invokeNative(Native Method)
08-19 04:41:04.726: E/WindowManager(4766): at java.lang.reflect.Method.invoke(Method.java:507)
08-19 04:41:04.726: E/WindowManager(4766): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
08-19 04:41:04.726: E/WindowManager(4766): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
08-19 04:41:04.726: E/WindowManager(4766): at dalvik.system.NativeStart.main(Native Method)
08-19 04:41:05.070: D/dalvikvm(4766): GC_CONCURRENT freed 235K, 48% free 2955K/5639K, external 507K/517K, paused 3ms+3ms
My java code is like this;
public class Login extends Activity implements OnClickListener{
private EditText user, pass;
private Button mSubmit, mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//php login script location:
//localhost :
//testing on your device
//put your local ip instead, on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1
//testing on Emulator:
private static final String LOGIN_URL = "login_url";
//testing from a real server:
//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//setup input fields
user = (EditText)findViewById(R.id.username);
pass = (EditText)findViewById(R.id.password);
//setup buttons
mSubmit = (Button)findViewById(R.id.button1);
mRegister = (Button)findViewById(R.id.button2);
//register listeners
mSubmit.setOnClickListener(this);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
new AttemptLogin().execute();
break;
case R.id.button2:
Intent i = new Intent(this, Register.class);
startActivity(i);
break;
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting login...");
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;
String username = user.getText().toString();//my app seems to be crushing here
String password = pass.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
Intent i = new Intent(Login.this, ReadComments.class);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} 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();
if (file_url != null){
Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
any assistance will be highly appreciated!!
Your log very clearly says:
Target host must not be null, or set in parameters.
As has been pointed out, LOGIN_URL may be malformed. I suggest you Log.v() it and see for yourself.
Try to save username and password in onPreExecute() because you can't do reference to interface component in doInBackground()
You cannot use directly your widgets like EditText, TextView, Buttons etc in doInBackground() preferable use these in onPreExecute() method. Secondly if you have to use these in doInBackground() method you should use runOnUIThread()
Another thing is you are calling another activity from doInBackground() and dismiss your dialog in onPostExecute() you should return your json.getString(TAG_MESSAGE) string from doInBackground() and after dialog.dismiss() start your next Activity see code below:
#Override
protected String doInBackground(String... args) {
String username, password;
// Check for success tag
int success;
runOnUiThread(new Runnable() {
#Override
public void run() {
username = user.getText().toString();
password = pass.getText().toString();
}
});
//do your other stuff
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
return json.getString(TAG_MESSAGE);
}else{
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url.equals("success message")){
Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
Intent i = new Intent(Login.this, ReadComments.class);
finish();
startActivity(i);
} else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
}
}
you can read about runOnUiThread() from here.
hope this will help you.
Use Below Code .
class LoginTask extends AsyncTask<String, Void, JSONObject> {
private ProgressDialog progressDialog;
String username;
String password;
#Override
protected void onPreExecute() {
username = user.getText().toString();
password = pass.getText().toString();
progressDialog = new ProgressDialog(mContext);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.setTitle(R.string.message_progress_title);
progressDialog.show();
}
#Override
protected JSONObject doInBackground(String... params) {
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);
return jsonObject;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
if(progressDialog.isShowing()) {
progressDialog.dismiss();
}
if(jsonObject != null) {
Log.i(TAG, "Login response : " + jsonObject);
try {
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Intent i = new Intent(Login.this, ReadComments.class);
startActivity(i);
finish();
}
else {
Toast.makeText(mContext, getResources().getString(R.string.login_failed), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else {
Toast.makeText(mContext, getResources().getString(R.string.connection_error), Toast.LENGTH_LONG).show();
}
}
You have the error named leaked window because you are trying to
open an Activity from doInBackground(...) and pDialog(ProgressDialog) is still
open you haven't dismiss that.
So, declare success variable globally(where you declare failure variable). Try to open new Activity or view update in onPostExecute(...)
code snippet for onPostExecute(...)
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
if(pDialog != null) {
pDialog.dismiss();
if (success == 1) {
Log.d("Login Successful!", json.toString());
Intent i = new Intent(Login.this, ReadComments.class);
finish();
startActivity(i);
}
if (file_url != null){
Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
}
}
}

ANDROID Updating a ListView via JSON with AsyncTask MySQL

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));
}
}

Getting Null Pointer Exception in AsyncTask?

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> {

Categories