Getting Null Pointer Exception in AsyncTask? - java

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

Related

ASyncTask with progressdialog and button

I am beginner and I had a test. I did all tasks, but I have a problem -
public class HttpTask extends AsyncTask<Integer, String, String> {####
ProgressDialog dialog;
Context context;
public HttpTask(Activity activity) {
//init progress dialog
dialog = new ProgressDialog(context);****
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
protected void onPreExecute() {
// show progress dialog
dialog.setMessage("Loading...");
dialog.setCancelable(false);
}
protected String doInBackground(Integer... params) {
//freeze system to 5 seconds
try {
int seconds = params[0]*5;####
TimeUnit.SECONDS.sleep(seconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String success) {
// if there is progress dialog hide it
dialog.dismiss();
}
}
It crashes, when I try to compile it (I showed where are problems with * sign):
08-03 10:43:10.873 29441-29441/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:142)
at android.app.AlertDialog.<init>(AlertDialog.java:98)
at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
at net.joerichard.androidtest.main.f.HttpTask.<init>(HttpTask.java:26)
at net.joerichard.androidtest.main.f.F_Networking_Activity$1.onClick(F_Networking_Activity.java:27)
at android.view.View.performClick(View.java:4107)
at android.view.View$PerformClick.run(View.java:17166)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5559)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1074)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:841)
at dalvik.system.NativeStart.main(Native Method)
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ App crashed! Process: net.joerichard.androidtest
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ App crashed! Package: net.joerichard.androidtest v1 (1.0)
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ Application Label: AndroidTest
This is class of main activity.
public class F_Networking_Activity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_f__networking_);
// bDownload: start HttpTask
Button bDownload = (Button) findViewById(R.id.bDownload);
bDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HttpTask task = new HttpTask(F_Networking_Activity.this);****
task.execute();
}
});
}
Thank you for your answers. Now I have another problem (I showed with # sign of second problems)
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ App crashed! Process: net.joerichard.androidtest'
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ App crashed! Package: net.joerichard.androidtest v1 (1.0)
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ Application Label: AndroidTest
08-03 11:28:18.292 30544-30726/? E/AndroidRuntime﹕ 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$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at net.joerichard.androidtest.main.f.HttpTask.doInBackground(HttpTask.java:40)
at net.joerichard.androidtest.main.f.HttpTask.doInBackground(HttpTask.java:20)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
Actually, your context is null because you didn't initialize it.
Add one extra line inside your HttpTask:
public HttpTask(Activity activity) {
this.context = activity;
dialog = new ProgressDialog(context);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
and change Context to Activity like this:
Activity context;
Now call this context anywhere in your class.
Yes you must get NullPointer. Because your context is null.
Change this like
public HttpTask(Context _context) {
context = _context;
//init progress dialog
dialog = new ProgressDialog(context);****
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}

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

AsyncTask#1 an error occured while executing doInBackgroud

I got this error whenever I change my URL to my online hosting, but if I change to 10.0.2.2 everything seems fine and running.
LogCat
02-01 23:02:18.302 17643-18052/com.example.jithea.testlogin E/JSON Parser﹕ Error parsing data org.json.JSONException: Value <br><table of type java.lang.String cannot be converted to JSONObject
02-01 23:02:18.303 17643-18052/com.example.jithea.testlogin W/dalvikvm﹕ threadid=12: thread exiting with uncaught exception (group=0x40d8d9a8)
02-01 23:02:18.303 17643-18052/com.example.jithea.testlogin W/dalvikvm﹕ threadid=12: uncaught exception occurred
02-01 23:02:18.304 17643-18052/com.example.jithea.testlogin W/System.err﹕ java.lang.RuntimeException: An error occured while executing doInBackground()
02-01 23:02:18.304 17643-18052/com.example.jithea.testlogin W/System.err﹕ at android.os.AsyncTask$3.done(AsyncTask.java:299)
02-01 23:02:18.304 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
02-01 23:02:18.305 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
02-01 23:02:18.305 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:239)
02-01 23:02:18.305 17643-18052/com.example.jithea.testlogin W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
02-01 23:02:18.305 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.lang.Thread.run(Thread.java:838)
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ Caused by: java.lang.NullPointerException
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ at com.example.jithea.testlogin.NewsActivity$LoadAllProducts.doInBackground(NewsActivity.java:132)
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ at com.example.jithea.testlogin.NewsActivity$LoadAllProducts.doInBackground(NewsActivity.java:107)
02-01 23:02:18.307 17643-18052/com.example.jithea.testlogin W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
02-01 23:02:18.307 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:234)
02-01 23:02:18.307 17643-18052/com.example.jithea.testlogin W/System.err﹕ ... 4 more
02-01 23:02:18.307 17643-18052/com.example.jithea.testlogin W/dalvikvm﹕ threadid=12: calling UncaughtExceptionHandler
02-01 23:02:18.315 17643-18052/com.example.jithea.testlogin E/AndroidRuntime﹕ 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:838)
Caused by: java.lang.NullPointerException
at com.example.jithea.testlogin.NewsActivity$LoadAllProducts.doInBackground(NewsActivity.java:132)
at com.example.jithea.testlogin.NewsActivity$LoadAllProducts.doInBackground(NewsActivity.java:107)
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:838)
02-01 23:02:18.371 17643-17659/com.example.jithea.testlogin I/SurfaceTextureClient﹕ [STC::queueBuffer] (this:0x528dc150) fps:43.08, dur:1044.57, max:73.51, min:6.02
And here's my NewsActivity.java
public class NewsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParserNews jParser = new JSONParserNews();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://agustiniancampusevents.site40.net/newsDB/get_all_news.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_NEWS = "news";
private static final String TAG_PID = "pid";
private static final String TAG_NEWSTITLE = "newstitle";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
ViewNewsActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
*/
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
*/
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_NEWS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String newstitle = c.getString(TAG_NEWSTITLE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NEWSTITLE, newstitle);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
ViewNewsActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
NewsActivity.this, productsList,
R.layout.news_list_item, new String[]{TAG_PID,
TAG_NEWSTITLE},
new int[]{R.id.pid, R.id.newstitle});
// updating listview
setListAdapter(adapter);
}
});
}
}
}

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

Categories