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();
}
}
}
Related
I am trying to create list view with json .
And this is the Logcat Stacktrace
1215-1239/com.skripsi.mazdamobil 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:841)
Caused by: java.lang.NullPointerException
at com.skripsi.mazdamobil.Data_Tipsntrick$DownloadList.doInBackground(Data_Tipsntrick.java:186)
at com.skripsi.mazdamobil.Data_Tipsntrick$DownloadList.doInBackground(Data_Tipsntrick.java:164)
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:841)
Data_Tipsntrick.java:164
private class DownloadList extends AsyncTask<Void,Void,Void> <- line 164
{
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(Data_Tipsntrick.this);
pDialog.setMessage("Tunggu Sebentar...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
Data_Tipsntrick.java:186
protected Void doInBackground(Void... unused)
{
String url_param;
url_param="fungsi.php?pl="+filepl+"&kategori="+filekategori;
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url+url_param);
Log.d("log", "url:" + url + url_param);
try
{
JSONArray result = json.getJSONArray("result"); <<-- line 186
for (int i = 0; i < result.length(); i++)
{
JSONObject c = result.getJSONObject(i);
String id = c.getString("id");
String pesan = c.getString("pesan");
String nama_tipsntrick = c.getString("nama");
String kategori_tipsntrick= c.getString("kategori");
HashMap<String,String> map = new HashMap<String,String>();
map.put(in_id,id);
map.put(in_pesan,pesan);
map.put(in_nama,nama_tipsntrick);
map.put(in_kategori,kategori_tipsntrick);
resultList.add(map);
}
Log.d("log", "bla:" + resultList);
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
}
next
05-05 11:06:11.299 1215-1215/com.skripsi.mazdamobil E/WindowManager﹕ Activity com.skripsi.mazdamobil.Data_Tipsntrick has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{416ef190 V.E..... R.....ID 0,0-304,96} that was originally added here
android.view.WindowLeaked: Activity com.skripsi.mazdamobil.Data_Tipsntrick has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{416ef190 V.E..... R.....ID 0,0-304,96} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:345)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:239)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:281)
at com.skripsi.mazdamobil.Data_Tipsntrick$DownloadList.onPreExecute(Data_Tipsntrick.java:173)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.skripsi.mazdamobil.Data_Tipsntrick.onCreate(Data_Tipsntrick.java:66)
at android.app.Activity.performCreate(Activity.java:5133)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Data_Tipsntrick.java:173
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(Data_Tipsntrick.this);
pDialog.setMessage("Tunggu Sebentar...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show(); <-- line 173
}
Data_Tipsntrick.java:66
new DownloadList().execute();
What am i doing wrong.Granted i don't know much java.
JSON Response
{"result":[{"id":"7","nama":"sadasdas","kategori":"berkendara","pesan":"dasdasdasdasd"},{"id":"5","nama":"Menggati Ban Bocor","kategori":"berkendara","pesan":"asdsadasdas"}]}
Well you can try this way if you are getting proper JSON response:
...
...
try {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url+url_param);
JSONArray result = json.getJSONArray("result");
if(result!=null) {
for (int i = 0; i < result.length(); i++) {
JSONObject c = (JSONObject) result.get(i);
String id = "", pesan = "", nama_tipsntrick = "", kategori_tipsntrick = "";
if (c.has("id"))
id = c.getString("id");
if (c.has("pesan"))
pesan = c.getString("pesan");
if (c.has("nam"))
nama_tipsntrick = c.getString("nama");
if (c.has("kategori"))
kategori_tipsntrick = c.getString("kategori");
HashMap<String, String> map = new HashMap<String, String>();
map.put(in_id, id);
map.put(in_pesan, pesan);
map.put(in_nama, nama_tipsntrick);
map.put(in_kategori, kategori_tipsntrick);
resultList.add(map);
}
}
Log.d("log", "bla:" + resultList);
} catch (JSONException e) {
e.printStackTrace();
}
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);
}
});
}
}
}
Immersed in the development of my program, I encounter an error that seems to me not really speaking.
So here's my logcat in the order and the java code:
When I click on the item in my listview it should return me the contact information for the update.
public class MajContactActivity extends Activity {
EditText txtNom;
EditText txtPrenom;
EditText txtNummobile;
EditText txtNumfixe;
EditText txtEmail;
EditText txtAdresse;
EditText txtProfession;
Button btnSav;
Button btnSup;
String idCONTACT;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single contact url
private static final String url_detail_contact = "http://10.0.2.2/contactCloud/detail_contact.php";
// url to update contact
private static final String url_update_contact = "http://10.0.2.2/contactCloud/update_contact.php";
// url to delete contact
private static final String url_delete_contact = "http://10.0.2.2/contactCloud/delete_contact.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_CONTACT = "personne";
private static final String TAG_IDCONTACT = "idCONTACT";
private static final String TAG_NOM = "nom";
private static final String TAG_PRENOM = "prenom";
private static final String TAG_NUMMOBILE = "numero_mobile";
private static final String TAG_NUMFIXE = "numero_fixe";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADRESSE = "adresse";
private static final String TAG_PROFESSION = "profession";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maj_contact);
// save button
btnSav = (Button) findViewById(R.id.btnSav);
btnSup = (Button) findViewById(R.id.btnSup);
// getting contact details from intent
Intent i = getIntent();
// getting contact id (idCONTACT) from intent
idCONTACT = i.getStringExtra(TAG_IDCONTACT);
// Getting complete contact details in background thread
new GetDetailContact().execute();
// save button click event
btnSav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// starting background task to update contact
new SavDetailContact().execute();
}
});
// Delete button click event
btnSup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// deleting contact in background thread
new SupContact().execute();
}
});
}
/**
* Background Async Task to Get complete contact details
* */
class GetDetailContact extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MajContactActivity.this);
pDialog.setMessage("Chargement du contact. Veuillez patientez...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting contact details in background thread
* */
protected String doInBackground(String... params) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("idCONTACT", idCONTACT));
// getting contact details by making HTTP request
// Note that contact details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(url_detail_contact, "GET", params1);
// check your log for json response
Log.d("Detail contact unique", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received contact details
JSONArray personneObj = json.getJSONArray(TAG_CONTACT); // JSON Array
// get first contact object from JSON Array
JSONObject personne = personneObj.getJSONObject(0);
// contact with this idCONTACT found
// Edit Text
txtNom = (EditText) findViewById(R.id.inputNom);
txtPrenom = (EditText) findViewById(R.id.inputPrenom);
txtNummobile = (EditText) findViewById(R.id.inputNumMobile);
txtNumfixe = (EditText) findViewById(R.id.inputNumFixe);
txtEmail = (EditText) findViewById(R.id.inputEmail);
txtAdresse = (EditText) findViewById(R.id.inputAdresse);
txtProfession = (EditText) findViewById(R.id.inputProfession);
// display contact data in EditText
txtNom.setText(personne.getString(TAG_NOM));
txtPrenom.setText(personne.getString(TAG_PRENOM));
txtNummobile.setText(personne.getString(TAG_NUMMOBILE));
txtNumfixe.setText(personne.getString(TAG_NUMFIXE));
txtEmail.setText(personne.getString(TAG_EMAIL));
txtAdresse.setText(personne.getString(TAG_ADRESSE));
txtProfession.setText(personne.getString(TAG_PROFESSION));
}else{
// contact with idCONTACT not found
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
/**
* Background Async Task to Save contact Details
* */
class SavDetailContact extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MajContactActivity.this);
pDialog.setMessage("Sauvegarde du contact ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Saving contact
* */
protected String doInBackground(String... args) {
// getting updated data from EditTexts
String nom = txtNom.getText().toString();
String prenom = txtPrenom.getText().toString();
String numero_mobile = txtNummobile.getText().toString();
String numero_fixe = txtNumfixe.getText().toString();
String email = txtEmail.getText().toString();
String adresse = txtAdresse.getText().toString();
String profession = txtProfession.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_IDCONTACT, idCONTACT));
params.add(new BasicNameValuePair(TAG_NOM, nom));
params.add(new BasicNameValuePair(TAG_PRENOM, prenom));
params.add(new BasicNameValuePair(TAG_NUMMOBILE, numero_mobile));
params.add(new BasicNameValuePair(TAG_NUMFIXE, numero_fixe));
params.add(new BasicNameValuePair(TAG_EMAIL, email));
params.add(new BasicNameValuePair(TAG_ADRESSE, adresse));
params.add(new BasicNameValuePair(TAG_PROFESSION, profession));
// sending modified data through http request
// Notice that update contact url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_update_contact,"POST", params);
// check json success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully updated
Intent i = getIntent();
// send result code 100 to notify about contact update
setResult(100, i);
finish();
} else {
// failed to update contact
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once contact uupdated
pDialog.dismiss();
}
}
/*****************************************************************
* Background Async Task to Delete Product
* */
class SupContact extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MajContactActivity.this);
pDialog.setMessage("Suppression du contact...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Deleting contact
* */
protected String doInBackground(String... args) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("idCONTACT", idCONTACT));
// getting contact details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(url_delete_contact, "POST", params);
// check your log for json response
Log.d("Suppression du contact", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// contact successfully deleted
// notify previous activity by sending code 100
Intent i = getIntent();
// send result code 100 to notify about contact deletion
setResult(100, i);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once contact deleted
pDialog.dismiss();
}
}
}
12-05 19:46:28.287: E/AndroidRuntime(1161): FATAL EXCEPTION: AsyncTask #
212-05 19:46:28.287: E/AndroidRuntime(1161): java.lang.RuntimeException: An error occured while executing doInBackground()
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.os.AsyncTask$3.done(AsyncTask.java:299)
12-05 19:46:28.287: E/AndroidRuntime(1161): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
12-05 19:46:28.287: E/AndroidRuntime(1161): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
12-05 19:46:28.287: E/AndroidRuntime(1161): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
12-05 19:46:28.287: E/AndroidRuntime(1161): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
12-05 19:46:28.287: E/AndroidRuntime(1161): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
12-05 19:46:28.287: E/AndroidRuntime(1161): at java.lang.Thread.run(Thread.java:841)
12-05 19:46:28.287: E/AndroidRuntime(1161): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:5908)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:869)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.view.ViewGroup.invalidateChild(ViewGroup.java:4253)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.view.View.invalidate(View.java:10482)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.widget.TextView.invalidateRegion(TextView.java:4591)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.widget.TextView.invalidateCursor(TextView.java:4534)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.widget.TextView.spanChange(TextView.java:7412)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.widget.TextView$ChangeWatcher.onSpanAdded(TextView.java:9103)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.text.SpannableStringBuilder.sendSpanAdded(SpannableStringBuilder.java:979)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:688)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:588)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.text.Selection.setSelection(Selection.java:76)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.text.Selection.setSelection(Selection.java:87)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.text.method.ArrowKeyMovementMethod.initialize(ArrowKeyMovementMethod.java:302)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.widget.TextView.setText(TextView.java:3759)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.widget.TextView.setText(TextView.java:3629)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.widget.EditText.setText(EditText.java:80)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.widget.TextView.setText(TextView.java:3604)
12-05 19:46:28.287: E/AndroidRuntime(1161): at fr.paris8.contactcloud.MajContactActivity$GetDetailContact.doInBackground(MajContactActivity.java:162)
12-05 19:46:28.287: E/AndroidRuntime(1161): at fr.paris8.contactcloud.MajContactActivity$GetDetailContact.doInBackground(MajContactActivity.java:1)
12-05 19:46:28.287: E/AndroidRuntime(1161): at android.os.AsyncTask$2.call(AsyncTask.java:287)
12-05 19:46:28.287: E/AndroidRuntime(1161): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
12-05 19:46:28.287: E/AndroidRuntime(1161): ... 4 more
12-05 19:46:36.289: E/WindowManager(1161): Activity fr.paris8.contactcloud.MajContactActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41803700 V.E..... R.....ID 0,0-480,144} that was originally added here
12-05 19:46:36.289: E/WindowManager(1161): android.view.WindowLeaked: Activity fr.paris8.contactcloud.MajContactActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41803700 V.E..... R.....ID 0,0-480,144} that was originally added here
12-05 19:46:36.289: E/WindowManager(1161): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:345)
12-05 19:46:36.289: E/WindowManager(1161): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:239)
12-05 19:46:36.289: E/WindowManager(1161): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
12-05 19:46:36.289: E/WindowManager(1161): at android.app.Dialog.show(Dialog.java:281)
12-05 19:46:36.289: E/WindowManager(1161): at fr.paris8.contactcloud.MajContactActivity$GetDetailContact.onPreExecute(MajContactActivity.java:120)
12-05 19:46:36.289: E/WindowManager(1161): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
12-05 19:46:36.289: E/WindowManager(1161): at android.os.AsyncTask.execute(AsyncTask.java:534)
12-05 19:46:36.289: E/WindowManager(1161): at fr.paris8.contactcloud.MajContactActivity.onCreate(MajContactActivity.java:81)
12-05 19:46:36.289: E/WindowManager(1161): at android.app.Activity.performCreate(Activity.java:5133)
12-05 19:46:36.289: E/WindowManager(1161): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
12-05 19:46:36.289: E/WindowManager(1161): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
12-05 19:46:36.289: E/WindowManager(1161): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
12-05 19:46:36.289: E/WindowManager(1161): at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-05 19:46:36.289: E/WindowManager(1161): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
12-05 19:46:36.289: E/WindowManager(1161): at android.os.Handler.dispatchMessage(Handler.java:99)
12-05 19:46:36.289: E/WindowManager(1161): at android.os.Looper.loop(Looper.java:137)
12-05 19:46:36.289: E/WindowManager(1161): at android.app.ActivityThread.main(ActivityThread.java:5103)
12-05 19:46:36.289: E/WindowManager(1161): at java.lang.reflect.Method.invokeNative(Native Method)
12-05 19:46:36.289: E/WindowManager(1161): at java.lang.reflect.Method.invoke(Method.java:525)
12-05 19:46:36.289: E/WindowManager(1161): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-05 19:46:36.289: E/WindowManager(1161): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-05 19:46:36.289: E/WindowManager(1161): at dalvik.system.NativeStart.main(Native Method)
I do not see or just wrong?
thank you for the help!
Try this..
You cannot do the initialize inside doInBackground you need to with in the onCreate. Same like that you cannot set the text inside the doInBackground need to in onPostExecute.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maj_contact);
// save button
btnSav = (Button) findViewById(R.id.btnSav);
btnSup = (Button) findViewById(R.id.btnSup);
// Edit Text
txtNom = (EditText) findViewById(R.id.inputNom);
txtPrenom = (EditText) findViewById(R.id.inputPrenom);
txtNummobile = (EditText) findViewById(R.id.inputNumMobile);
txtNumfixe = (EditText) findViewById(R.id.inputNumFixe);
txtEmail = (EditText) findViewById(R.id.inputEmail);
txtAdresse = (EditText) findViewById(R.id.inputAdresse);
txtProfession = (EditText) findViewById(R.id.inputProfession);
// getting contact details from intent
Intent i = getIntent();
// getting contact id (idCONTACT) from intent
idCONTACT = i.getStringExtra(TAG_IDCONTACT);
// Getting complete contact details in background thread
new GetDetailContact().execute();
// save button click event
btnSav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// starting background task to update contact
new SavDetailContact().execute();
}
});
// Delete button click event
btnSup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// deleting contact in background thread
new SupContact().execute();
}
});
}
/**
* Background Async Task to Get complete contact details
* */
class GetDetailContact extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MajContactActivity.this);
pDialog.setMessage("Chargement du contact. Veuillez patientez...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting contact details in background thread
* */
protected String doInBackground(String... params) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("idCONTACT", idCONTACT));
// getting contact details by making HTTP request
// Note that contact details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(url_detail_contact, "GET", params1);
// check your log for json response
Log.d("Detail contact unique", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received contact details
JSONArray personneObj = json.getJSONArray(TAG_CONTACT); // JSON Array
// get first contact object from JSON Array
JSONObject personne = personneObj.getJSONObject(0);
// contact with this idCONTACT found
}else{
// contact with idCONTACT not found
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
// display contact data in EditText
txtNom.setText(personne.getString(TAG_NOM));
txtPrenom.setText(personne.getString(TAG_PRENOM));
txtNummobile.setText(personne.getString(TAG_NUMMOBILE));
txtNumfixe.setText(personne.getString(TAG_NUMFIXE));
txtEmail.setText(personne.getString(TAG_EMAIL));
txtAdresse.setText(personne.getString(TAG_ADRESSE));
txtProfession.setText(personne.getString(TAG_PROFESSION));
}
}
/**
* Background Async Task to Save contact Details
* */
class SavDetailContact extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MajContactActivity.this);
pDialog.setMessage("Sauvegarde du contact ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Saving contact
* */
protected String doInBackground(String... args) {
// getting updated data from EditTexts
String nom = txtNom.getText().toString();
String prenom = txtPrenom.getText().toString();
String numero_mobile = txtNummobile.getText().toString();
String numero_fixe = txtNumfixe.getText().toString();
String email = txtEmail.getText().toString();
String adresse = txtAdresse.getText().toString();
String profession = txtProfession.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_IDCONTACT, idCONTACT));
params.add(new BasicNameValuePair(TAG_NOM, nom));
params.add(new BasicNameValuePair(TAG_PRENOM, prenom));
params.add(new BasicNameValuePair(TAG_NUMMOBILE, numero_mobile));
params.add(new BasicNameValuePair(TAG_NUMFIXE, numero_fixe));
params.add(new BasicNameValuePair(TAG_EMAIL, email));
params.add(new BasicNameValuePair(TAG_ADRESSE, adresse));
params.add(new BasicNameValuePair(TAG_PROFESSION, profession));
// sending modified data through http request
// Notice that update contact url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_update_contact,"POST", params);
// check json success tag
try {
int success = json.getInt(TAG_SUCCESS);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once contact uupdated
pDialog.dismiss();
if (success == 1) {
// successfully updated
Intent i = getIntent();
// send result code 100 to notify about contact update
setResult(100, i);
finish();
} else {
// failed to update contact
}
}
}
EDIT :
class GetDetailContact extends AsyncTask<String, void, JSONObject> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MajContactActivity.this);
pDialog.setMessage("Chargement du contact. Veuillez patientez...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting contact details in background thread
* */
protected JSONObject doInBackground(String... params) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("idCONTACT", idCONTACT));
// getting contact details by making HTTP request
// Note that contact details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(url_detail_contact, "GET", params1);
// check your log for json response
Log.d("Detail contact unique", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received contact details
JSONArray personneObj = json.getJSONArray(TAG_CONTACT); // JSON Array
// get first contact object from JSON Array
JSONObject personne = personneObj.getJSONObject(0);
// contact with this idCONTACT found
return personne;
}else{
// contact with idCONTACT not found
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(JSONObject personne) {
// dismiss the dialog once got all details
pDialog.dismiss();
// display contact data in EditText
txtNom.setText(personne.getString(TAG_NOM));
txtPrenom.setText(personne.getString(TAG_PRENOM));
txtNummobile.setText(personne.getString(TAG_NUMMOBILE));
txtNumfixe.setText(personne.getString(TAG_NUMFIXE));
txtEmail.setText(personne.getString(TAG_EMAIL));
txtAdresse.setText(personne.getString(TAG_ADRESSE));
txtProfession.setText(personne.getString(TAG_PROFESSION));
}
}
Hey guys can you look at my errors, my logcat says it is because i am getting null pointer exception. i don't understand why. I just added a String variable which is "Email" and make the value of my eadd which stands for email address equals to it, then i have these errors now. can you point to me the problem guys?
These are my codes:
**
public class LoginSub extends Activity {
public static String Email;
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputEmail;
EditText inputPassword;
TextView TextView1;
// url to create new product
//private static String url_create_product = "http://student-thesis.netii.net/log_in.php";
private static String url_create_product = "http://10.0.2.2/TheCalling/log_in.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Edit Text
inputEmail = (EditText) findViewById(R.id.inputEmail);
inputPassword = (EditText) findViewById(R.id.inputPassword);
// Create button
Button btnLogin = (Button) findViewById(R.id.btnLogin);
// button click event
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new phpconnect().execute();
}
});
Button btnReg = (Button) findViewById(R.id.btnReg);
// button click event
btnReg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Register.class);
startActivity(i);
}
});
}
/**
* Background Async Task to Create new product
* */
class phpconnect extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginSub.this);
pDialog.setMessage("Logging in..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String eadd = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("eadd", eadd));
params.add(new BasicNameValuePair("password", password));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
Email.equals(eadd);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), Mapping.class);
startActivity(i);
// closing this screen
finish();
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
**
and here's my logcat errors:
**
03-06 22:21:16.428: E/AndroidRuntime(1417): FATAL EXCEPTION: AsyncTask #1
03-06 22:21:16.428: E/AndroidRuntime(1417): java.lang.RuntimeException: An error occured while executing doInBackground()
03-06 22:21:16.428: E/AndroidRuntime(1417): at android.os.AsyncTask$3.done(AsyncTask.java:278)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
03-06 22:21:16.428: E/AndroidRuntime(1417): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.lang.Thread.run(Thread.java:856)
03-06 22:21:16.428: E/AndroidRuntime(1417): Caused by: java.lang.NullPointerException
03-06 22:21:16.428: E/AndroidRuntime(1417): at com.example.projectthesis.LoginSub$phpconnect.doInBackground(LoginSub.java:129)
03-06 22:21:16.428: E/AndroidRuntime(1417): at com.example.projectthesis.LoginSub$phpconnect.doInBackground(LoginSub.java:1)
03-06 22:21:16.428: E/AndroidRuntime(1417): at android.os.AsyncTask$2.call(AsyncTask.java:264)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
**
Thank you guys.
Remove this block from doInBackGround()
if (success == 1) {
// successfully created product
Intent i = new Intent(LoginSub.this, Mapping.class);
startActivity(i);
// closing this screen
finish();
} else {
}
And add it in onPostExecute() section
protected void onPostExecute(String file_url)
{
// dismiss the dialog once done
pDialog.dismiss();
if (success == 1)
{
// successfully created product
Intent i = new Intent(getApplicationContext(), Mapping.class);
startActivity(i);
// closing this screen
finish();
}
else
{
}
}
Some times getApplicationContext() wont provide the exact context values. So pass the
Context context; //declare
context=this;// assigning next line after setcontextview.
then pass the context instead of getApplicationContext() . and check it and also if you want to do any UI updates you are not supposed to do in doinBackground(). You have to do in post execute.
Hope this will help you.
I think because this line
new phpconnect().execute();
and
class phpconnect extends AsyncTask<String, String, String> {
You declare AsyncTask with <String, String, String> but you didn't pass any parameter in .exeute();
Moreover that, from your code you don't want any parameter for AsyncTask so you should declare your Asynctask like this
class phpconnect extends AsyncTask<Void, Void, Void> {
My edit text serves as a search box, and I am getting movies from rotten tomatoes API, using the text inside my edit text, problem is. when a space is inserted the application crashes, I am assuming that I need to convert the spaces into +'s, but I have no clue how where to add this code or how exactly, I hope someone here will be able to help me.
this is my code:
private TextView searchBox;
private Button bGo, bCancelAddFromWeb;
private ListView moviesList;
public final static int ACTIVITY_WEB_ADD = 3;
public List<String> movieTitles;
public List<String> movieSynopsis;
public List<String> movieImgUrl;
private ProgressDialog pDialog;
// the Rotten Tomatoes API key
private static final String API_KEY = "8q6wh77s65a54w433cab9rbsq";
// the number of movies to show
private static final int MOVIE_PAGE_LIMIT = 8;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_add_from_web);
InitializeVariables();
}
/*
* Initializing the variables and creating the bridge between the views from
* the xml file and this class
*/
private void InitializeVariables() {
searchBox = (EditText) findViewById(R.id.etSearchBox);
bGo = (Button) findViewById(R.id.bGo);
bCancelAddFromWeb = (Button) findViewById(R.id.bCancelAddFromWeb);
moviesList = (ListView) findViewById(R.id.list_movies);
bGo.setOnClickListener(this);
bCancelAddFromWeb.setOnClickListener(this);
moviesList.setOnItemClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bGo:
new RequestTask()
.execute("http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey="
+ API_KEY
+ "&q="
+ searchBox.getText()
+ "&page_limit=" + MOVIE_PAGE_LIMIT);
break;
case R.id.bCancelAddFromWeb:
finish();
break;
}
}
private void refreshMoviesList(List<String> movieTitles) {
moviesList.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, movieTitles
.toArray(new String[movieTitles.size()])));
}
private class RequestTask extends AsyncTask<String, String, String> {
// make a request to the specified url
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
// make a HTTP request
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else {
// close connection
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (Exception e) {
Log.d("Test", "Couldn't make a successful request!");
}
return responseString;
}
// if the request above completed successfully, this method will
// automatically run so you can do something with the response
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MovieAddFromWeb.this);
pDialog.setMessage("Searching...");
pDialog.show();
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
try {
// convert the String response to a JSON object
JSONObject jsonResponse = new JSONObject(response);
// fetch the array of movies in the response
JSONArray jArray = jsonResponse.getJSONArray("movies");
// add each movie's title to a list
movieTitles = new ArrayList<String>();
// newly added
movieSynopsis = new ArrayList<String>();
movieImgUrl = new ArrayList<String>();
for (int i = 0; i < jArray.length(); i++) {
JSONObject movie = jArray.getJSONObject(i);
movieTitles.add(movie.getString("title"));
movieSynopsis.add(movie.getString("synopsis"));
movieImgUrl.add(movie.getJSONObject("posters").getString(
"profile"));
}
// refresh the ListView
refreshMoviesList(movieTitles);
} catch (JSONException e) {
Log.d("Test", "Couldn't successfully parse the JSON response!");
}
pDialog.dismiss();
}
}
#Override
public void onItemClick(AdapterView<?> av, View view, int position, long id) {
Intent openMovieEditor = new Intent(this, MovieEditor.class);
openMovieEditor.putExtra("movieTitle", movieTitles.get(position));
// newly added
openMovieEditor.putExtra("movieSynopsis", movieSynopsis.get(position));
openMovieEditor.putExtra("movieImgUrl", movieImgUrl.get(position));
openMovieEditor.putExtra("callingActivity", ACTIVITY_WEB_ADD);
startActivityForResult(openMovieEditor, ACTIVITY_WEB_ADD);
}
}
this is the log with the error:
01-14 20:19:19.591: D/Test(907): Couldn't make a successful request!
01-14 20:19:19.690: D/AndroidRuntime(907): Shutting down VM
01-14 20:19:19.700: W/dalvikvm(907): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
01-14 20:19:19.801: E/AndroidRuntime(907): FATAL EXCEPTION: main
01-14 20:19:19.801: E/AndroidRuntime(907): java.lang.NullPointerException
01-14 20:19:19.801: E/AndroidRuntime(907): at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
01-14 20:19:19.801: E/AndroidRuntime(907): at org.json.JSONTokener.nextValue(JSONTokener.java:94)
01-14 20:19:19.801: E/AndroidRuntime(907): at org.json.JSONObject.<init>(JSONObject.java:154)
01-14 20:19:19.801: E/AndroidRuntime(907): at org.json.JSONObject.<init>(JSONObject.java:171)
01-14 20:19:19.801: E/AndroidRuntime(907): at il.jb.projectpart2.MovieAddFromWeb$RequestTask.onPostExecute(MovieAddFromWeb.java:152)
01-14 20:19:19.801: E/AndroidRuntime(907): at il.jb.projectpart2.MovieAddFromWeb$RequestTask.onPostExecute(MovieAddFromWeb.java:1)
01-14 20:19:19.801: E/AndroidRuntime(907): at android.os.AsyncTask.finish(AsyncTask.java:631)
01-14 20:19:19.801: E/AndroidRuntime(907): at android.os.AsyncTask.access$600(AsyncTask.java:177)
01-14 20:19:19.801: E/AndroidRuntime(907): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
01-14 20:19:19.801: E/AndroidRuntime(907): at android.os.Handler.dispatchMessage(Handler.java:99)
01-14 20:19:19.801: E/AndroidRuntime(907): at android.os.Looper.loop(Looper.java:137)
01-14 20:19:19.801: E/AndroidRuntime(907): at android.app.ActivityThread.main(ActivityThread.java:4745)
01-14 20:19:19.801: E/AndroidRuntime(907): at java.lang.reflect.Method.invokeNative(Native Method)
01-14 20:19:19.801: E/AndroidRuntime(907): at java.lang.reflect.Method.invoke(Method.java:511)
01-14 20:19:19.801: E/AndroidRuntime(907): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-14 20:19:19.801: E/AndroidRuntime(907): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-14 20:19:19.801: E/AndroidRuntime(907): at dalvik.system.NativeStart.main(Native Method)
You should use standard URL encoding as follows:
case R.id.bGo:
new RequestTask()
.execute("http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey="
+ API_KEY
+ "&q="
+ URLEncoder.encode(searchBox.getText(), "UTF-8")
+ "&page_limit=" + MOVIE_PAGE_LIMIT);
This will replace spaces and all other non-URL-friendly characters with allowed characters (as defined by RFC 1738 and the HTML spec)
Need to see your logcat to make sure that's the actual problem, but from your code it looks like it is at least one of your issues.
Ideally you'd do something like
String search = searchBox.getText();
search = search.replace(" ", "+");
and then use that variable to send to your RequestTask
Source: Android Developers
Conversely, you may be better off doing a full encoding on the string returned instead of just replacing spaces... as other characters will cause you issues as well (?, &, etc)
EDIT: See EJK's answer for the URLEncoding version.