I'm struggling with this error since 2 days now and I can't figure out how to fix it.
I have an order method for a product that calls a webservice, I parse the response and if the response is negative I have to show an AlertDialog inside the onPostExecute method. This is the code i'm using:
private class test extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("deviceOS", "Android"));
String jsonStr = sh.makeServiceCall(urlTest, ServiceHandler.POST, params);
if (jsonStr != null) {
try {
JSONObject obj = new JSONObject(jsonStr);
error = obj.getBoolean("Error");
if(!error)
{
test = true;
JSONObject array = obj.getJSONObject("Response");
token = array.getString("Token");
}
else
{
test = false;
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
//checkResult();
AlertDialog.Builder reorder = new AlertDialog.Builder(myActivity.this);
reorder.setMessage("test");
reorder.setCancelable(true);
reorder.setPositiveButton("ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog orderError = reorder.create();
orderError.show();
}
}
When the app reaches the onPostExecute method it crashes and the log is this:
07-13 11:58:31.074: E/AndroidRuntime(2529): FATAL EXCEPTION: main
07-13 11:58:31.074: E/AndroidRuntime(2529): Process: com.test.Test, PID: 2529
07-13 11:58:31.074: E/AndroidRuntime(2529): java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
07-13 11:58:31.074: E/AndroidRuntime(2529): at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:148)
07-13 11:58:31.074: E/AndroidRuntime(2529): at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:99)
07-13 11:58:31.074: E/AndroidRuntime(2529): at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:154)
07-13 11:58:31.074: E/AndroidRuntime(2529): at android.app.AlertDialog$Builder.<init>(AlertDialog.java:379)
07-13 11:58:31.074: E/AndroidRuntime(2529): at test.test$login.onPostExecute(test.java:575)
07-13 11:58:31.074: E/AndroidRuntime(2529): at test.test$test.onPostExecute(test.java:1)
07-13 11:58:31.074: E/AndroidRuntime(2529): at android.os.AsyncTask.finish(AsyncTask.java:632)
07-13 11:58:31.074: E/AndroidRuntime(2529): at android.os.AsyncTask.access$600(AsyncTask.java:177)
07-13 11:58:31.074: E/AndroidRuntime(2529): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
07-13 11:58:31.074: E/AndroidRuntime(2529): at android.os.Handler.dispatchMessage(Handler.java:102)
07-13 11:58:31.074: E/AndroidRuntime(2529): at android.os.Looper.loop(Looper.java:135)
07-13 11:58:31.074: E/AndroidRuntime(2529): at android.app.ActivityThread.main(ActivityThread.java:5312)
07-13 11:58:31.074: E/AndroidRuntime(2529): at java.lang.reflect.Method.invoke(Native Method)
07-13 11:58:31.074: E/AndroidRuntime(2529): at java.lang.reflect.Method.invoke(Method.java:372)
07-13 11:58:31.074: E/AndroidRuntime(2529): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
07-13 11:58:31.074: E/AndroidRuntime(2529): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Does anyone know what the error could be?
Why are you create 2 times AlertDialog? Using Builder you can show it. Change Below code and Works fine.
Replace
AlertDialog.Builder reorder = new AlertDialog.Builder(myActivity.this);
with
AlertDialog.Builder reorder = new AlertDialog.Builder(myActivity.this).create();
and
Remove
AlertDialog orderError = reorder.create();
orderError.show();
and add
reorder.show();
Thats it...
Make sure you have initialised "urlTest" before you are using it.
Try this.
private class test extends AsyncTask<Void, Void, Void> {
WeakReference<Activity> weakActivity;
public test(Activity activity) {
weakActivity = activity;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
//blah blah code!
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Activity activity = weakActivity.get();
if (activity != null) {
// Dismiss the progress dialog
//checkResult();
AlertDialog.Builder reorder = new AlertDialog.Builder(activity);
reorder.setMessage("test");
reorder.setCancelable(true);
reorder.setPositiveButton("ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog orderError = reorder.create();
orderError.show();
}
}
}
Related
I am closing an activity via finish().
It works fine on several devices but on a Samsung Galaxy S3 Neo running Android 4.4 I get the following issue:
java.lang.RuntimeException
android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3706)
android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3724)
android.app.ActivityThread.access$1500(ActivityThread.java:169)
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1330)
android.os.Handler.dispatchMessage(Handler.java:102)
android.os.Looper.loop(Looper.java:136)
android.app.ActivityThread.main(ActivityThread.java:5476)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:515)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
dalvik.system.NativeStart.main(Native Method)
Caused by: android.util.Log.println_native(Native Method)
android.util.Log.e(Log.java:307)
com.ads.adstimer.fragment.Registration.RegistrationActivity.onDestroy(RegistrationActivity.java:214)
android.app.Activity.performDestroy(Activity.java:5623)
android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1123)
android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3693)
android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3724)
android.app.ActivityThread.access$1500(ActivityThread.java:169)
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1330)
android.os.Handler.dispatchMessage(Handler.java:102)
android.os.Looper.loop(Looper.java:136)
android.app.ActivityThread.main(ActivityThread.java:5476)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:515)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
dalvik.system.NativeStart.main(Native Method)
I have found two posts about that subject: First, Second
But they did not help me.
My activity code. Note that I am using AppIntro:
public class RegistrationActivity extends AppIntro {
private AsyncTaskRegisterInBackground registerPushToken;
(...)
#Override
public void onDonePressed() {
(...)
if (regid.isEmpty()) {
registerPushToken = new AsyncTaskRegisterInBackground();
registerPushToken.setParams(activity, gcm, regid);
registerPushToken.execute();
}
(...)
}
#Override
public void onTaskCompleted(String responseRegid) {
try {
// load authToken from Server: JsonObjectRequest
builderOnFailureDialog = new MaterialDialog.Builder(activity)
.title(getResources().getString(R.string.registrierung_dialog_registrieren_failure_retry_title))
.content(onFailureDialogContent)
.positiveText(getResources().getString(R.string.registrierung_dialog_registrieren_failure_retry_positive_text))
.negativeText(getResources().getString(R.string.registrierung_dialog_registrieren_failure_retry_negative_text))
.onNegative(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
activity.finish();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
onFailureDialog.dismiss();
onSuccessDialog.dismiss();
} catch (Exception e) {
Log.e("Activity.onDestroy()", e.getMessage());
}
}
}
Or is the reason for the problem the async task running in background?
call finish() inside runOnUiThread().
i.e.
replace
finish();
with
runOnUiThread(new Runnable() {
public void run() {
finish()
}
});
I have successfully sent an email in the background and displayed a progress dialog to the user as said email is sent. However when the user flips the screen while the dialog is up I get an IllegalArgumentException. I have tried using a WeakReference object and it doesn't seem to be fixing the problem. This is my AsyncTask class.
private class SendMailTask extends AsyncTask<Mail, String, EmailStatusResponce> {
private final WeakReference<ProgressDialog> weakReference;
public SendMailTask() {
ProgressDialog progressDialog = new ProgressDialog(SendReportActivity.this);
progressDialog.setMessage("Sending...");
progressDialog.setCancelable(false);
progressDialog.show();
weakReference = new WeakReference<>(progressDialog);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected EmailStatusResponce doInBackground(Mail... mail) {
return mail[0].send();
}
#Override
protected void onPostExecute(EmailStatusResponce result) {
super.onPostExecute(result);
if (result != null && weakReference != null) {
weakReference.get().dismiss(); // This is where the exception is thrown.
if (result.isSuccess()) {
Intent intent = new Intent(SendReportActivity.this, MainActivity.class);
startActivity(intent);
}
else {}
}
}
This is the exception
java.lang.IllegalArgumentException: View=com.android.internal.policy.PhoneWindow$DecorView{688d3e2 V.E...... R......D 0,0-1026,348} not attached to window manager
Thanks in advance for any and all help.
EDIT: More logcat
--------- beginning of crash
12-11 16:22:40.154 1976-1976/com.blazapps.allenfamilymedicine E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.blazapps.allenfamilymedicine, PID: 1976
java.lang.IllegalArgumentException: View=com.android.internal.policy.PhoneWindow$DecorView{f89e667 V.E...... R......D 0,0-760,232} not attached to window manager
at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:424)
at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:350)
at android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:116)
at android.app.Dialog.dismissDialog(Dialog.java:362)
at android.app.Dialog.dismiss(Dialog.java:345)
at com.blazapps.allenfamilymedicine.SendReportActivity$SendMailTask.onPostExecute(SendReportActivity.java:168)
at com.blazapps.allenfamilymedicine.SendReportActivity$SendMailTask.onPostExecute(SendReportActivity.java:138)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I still do no know why the exception is being thrown but because I save lots of information in EmailStatusResponse I can just surround the exception with a try catch and if the task was complete I get the result I expected.
try {
weakReference.get().dismiss();
} catch (Exception e) {}
If anyone can figure a better solution I would really appreciate it. I hate just catching exceptions. There is usually a better way.
I have an asyncTask and I want to show an alertDialog when the onPostExecute method is fired.
I declared a Context variable and I initialized it inside the OnCreate method like:
mContext = this;
Then in order to show the alertDialog on the onPostExecute method I used the following code:
AlertDialog.Builder goLogin = new AlertDialog.Builder(mContext);
goLogin.setMessage("test");
goLogin.setCancelable(false);
goLogin.setPositiveButton("ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertLogin = goLogin.create();
alertLogin.show();
But what I get is the following error:
07-10 14:42:09.710: E/AndroidRuntime(12963): java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
07-10 14:42:09.710: E/AndroidRuntime(12963): at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:148)
07-10 14:42:09.710: E/AndroidRuntime(12963): at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:99)
07-10 14:42:09.710: E/AndroidRuntime(12963): at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:154)
07-10 14:42:09.710: E/AndroidRuntime(12963): at android.app.AlertDialog$Builder.<init>(AlertDialog.java:379)
07-10 14:42:09.710: E/AndroidRuntime(12963): at test.test.showAlert(test.java:671)
07-10 14:42:09.710: E/AndroidRuntime(12963): at test.test.checkResult(test.java:656)
07-10 14:42:09.710: E/AndroidRuntime(12963): at test.test$login.onPostExecute(test.java:585)
07-10 14:42:09.710: E/AndroidRuntime(12963): at test.test$login.onPostExecute(test.java:1)
07-10 14:42:09.710: E/AndroidRuntime(12963): at android.os.AsyncTask.finish(AsyncTask.java:632)
07-10 14:42:09.710: E/AndroidRuntime(12963): at android.os.AsyncTask.access$600(AsyncTask.java:177)
07-10 14:42:09.710: E/AndroidRuntime(12963): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
07-10 14:42:09.710: E/AndroidRuntime(12963): at android.os.Handler.dispatchMessage(Handler.java:102)
07-10 14:42:09.710: E/AndroidRuntime(12963): at android.os.Looper.loop(Looper.java:135)
07-10 14:42:09.710: E/AndroidRuntime(12963): at android.app.ActivityThread.main(ActivityThread.java:5312)
07-10 14:42:09.710: E/AndroidRuntime(12963): at java.lang.reflect.Method.invoke(Native Method)
07-10 14:42:09.710: E/AndroidRuntime(12963): at java.lang.reflect.Method.invoke(Method.java:372)
07-10 14:42:09.710: E/AndroidRuntime(12963): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
07-10 14:42:09.710: E/AndroidRuntime(12963): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
What am I doing wrong? Do I need to pass the context in a different way?
EDIT:
Whole AsyncTask code:
private class login extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
}
#SuppressWarnings("deprecation")
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userName", "test"));
String jsonStr = sh.makeServiceCall(urlTest, ServiceHandler.POST, params);
if (jsonStr != null) {
try {
JSONObject obj = new JSONObject(jsonStr);
error = obj.getBoolean("Error");
if(!error)
{
loginResult = true;
JSONObject array = obj.getJSONObject("Response");
name = array.getString("Name");
}
else
{
loginResult = false;
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
//checkResult();
AlertDialog.Builder reorder = new AlertDialog.Builder(context);
reorder.setMessage("error");
reorder.setCancelable(true);
reorder.setPositiveButton("ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog orderError = reorder.create();
orderError.show();
}
}
Create constructor of your AsyncTask and do something like this:
private class DemoTask extends AsyncTask<Void, Void, Void> {
Context context;
public DemoTask(Context mContext) {
this.context = mContext;
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
AlertDialog.Builder goLogin = new AlertDialog.Builder(context);
goLogin.setMessage("test");
goLogin.setCancelable(false);
goLogin.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertLogin = goLogin.create();
alertLogin.show();
}
}
Here mContext is inside onCreate Method:
public class MyActivity extends Activity {
private Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
new DemoTask(mContext).execute();
}
Before you get your servis callback in onPostExecute of your AsyncTask, user can send your app to background and your activity can be destroyed. In this case your context will be null and cannot show an alert dialog.
I think it's not a good solution to show an alert dialog on AsyncTask results. You can show a Toast message. Dialogs use activity context and you can get this error.
Also can get BadTokenException in this kind of usage. To avoid these kind of errors check if your activity null and show dialog in a try catch blog.
onPostExecute() is called on main thread. mContext has Activity's context.
Regardless of the fact Activity is destroyed or not, onPostExecute() will be called. When Activity is destroyed, the NPE error will occur while creating Alert Dialog Box. Make sure that Activity is on foreground.
update:
code:
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(getActivity() == null)
{
return; //since activity is in background!
}
AlertDialog.Builder goLogin = new AlertDialog.Builder(context);
goLogin.setMessage("test");
goLogin.setCancelable(false);
goLogin.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertLogin = goLogin.create();
alertLogin.show();
}
Remove last two line of code and add the below line :
Instead of this line
AlertDialog alertLogin = goLogin.create();
alertLogin.show();
Use this line:
goLogin.show();
I have implemented a JSON Parser on a background thread and then am trying to write the data to a series of TableRows on the UI Thread using some embedded code which includes a handler to put me back on the normal UI Thread. The code continually comes back with this stack trace
Process: webmd.mmu.ac.uk.wmfinal3, PID: 6123
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:3562)
at android.view.ViewGroup.addView(ViewGroup.java:3415)
at android.widget.TableLayout.addView(TableLayout.java:429)
at android.view.ViewGroup.addView(ViewGroup.java:3360)
at android.widget.TableLayout.addView(TableLayout.java:411)
at android.view.ViewGroup.addView(ViewGroup.java:3336)
at android.widget.TableLayout.addView(TableLayout.java:402)
at webmd.mmu.ac.uk.wmfinal3.MainActivity$ProgressTask$1$1.run(MainActivity.java:244)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
04-21 14:58:08.506 6199-6199/webmd.mmu.ac.uk.wmfinal3 D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
04-21 14:58:11.316 6199-6215/webmd.mmu.ac.uk.wmfinal3 D/dalvikvm﹕ GC_FOR_ALLOC freed 209K, 10% free 3129K/3460K, paused 2ms, total 2ms
04-21 14:58:11.336 6199-6199/webmd.mmu.ac.uk.wmfinal3 D/AndroidRuntime﹕ Shutting down VM
04-21 14:58:11.336 6199-6199/webmd.mmu.ac.uk.wmfinal3 W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb0cb3b20)
04-21 14:58:11.336 6199-6199/webmd.mmu.ac.uk.wmfinal3 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: webmd.mmu.ac.uk.wmfinal3, PID: 6199
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:3562)
at android.view.ViewGroup.addView(ViewGroup.java:3415)
at android.widget.TableLayout.addView(TableLayout.java:429)
at android.view.ViewGroup.addView(ViewGroup.java:3360)
at android.widget.TableLayout.addView(TableLayout.java:411)
at android.view.ViewGroup.addView(ViewGroup.java:3336)
at android.widget.TableLayout.addView(TableLayout.java:402)
at webmd.mmu.ac.uk.wmfinal3.MainActivity$ProgressTask$1$1.run(MainActivity.java:245)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
I tried moving all the code into the AsyncTask but it then demands to be on the UI Thread.
Here is my code. Any help would be much appreciated.
protected Boolean doInBackground(final String... args) {
final TableLayout tl = (TableLayout) findViewById(R.id.table);
final TableRow v1 = new TableRow(MainActivity.this);
JSONParser jParser = new JSONParser();
String temp = "http://sandbox.kriswelsh.com/hygieneapi/hygiene.php?op=nearest&lat=" + latitude + "&long=" + longitude;
JSONArray json = jParser.getJSONFromUrl(temp);
int [] test = new int [10];
for (int i = 0; i < 10; i++) {
try {
JSONObject c = json.getJSONObject(i);
String vid = c.getString(id);
String vbn = c.getString(BusinessName);
String va1 = c.getString(Add1);
String va2 = c.getString(Add2);
String va3 = c.getString(Add3);
String vpost = c.getString(Post);
String vlong = c.getString(longitudej);
String vrate = c.getString(RatingDate);
String vratestar = c.getString(Rating);
String vlat = c.getString(latitudej);
if (vratestar.contentEquals("-1")) {
vratestar = "Exempt";
}
//testing(vbn,va1,va2,va3,vpost,vratestar);
//TableLayout tl = (TableLayout) findViewById(R.id.table);
isRunning = true;
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (isRunning) {
try {
// Thread.sleep(10000);
mHandler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
tl.addView(v1);
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
isRunning = false;
//jsonlist.add(map);
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
UPDATE: Now shows v1 initialization
Looking at your while (isRunning) loop I suppose you are trying to add the same v1 TableRow view to the TableLayout on each iteration (however, it is just a guess, because you didn't post v1 declaration). Of course, at the second time it will give you an error as it is already has parent, you should create new TableRow object each time. Going deeper, you don't need Handler which is connected to UI thread, because you are using AsyncTask, you can take advantage of the fact, that onPostExecute method is executed on the main thread. Considering it, you can write the following AsyncTask implementation:
class MyAsyncTask extends AsyncTask<Void, Void, JSONArray>{
#Override
protected JSONArray doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
String temp = "http://sandbox.kriswelsh.com/hygieneapi/hygiene.php?op=nearest&lat=" + latitude + "&long=" + longitude;
JSONArray json = jParser.getJSONFromUrl(temp);
return json;
}
#Override
protected void onPostExecute(JSONArray json) {
TableLayout tl = (TableLayout) findViewById(R.id.table);
for (int i = 0; i < 10; i++) {
try {
JSONObject c = json.getJSONObject(i);
String vid = c.getString(id);
String vbn = c.getString(BusinessName);
String va1 = c.getString(Add1);
String va2 = c.getString(Add2);
String va3 = c.getString(Add3);
String vpost = c.getString(Post);
String vlong = c.getString(longitudej);
String vrate = c.getString(RatingDate);
String vratestar = c.getString(Rating);
String vlat = c.getString(latitudej);
if (vratestar.contentEquals("-1")) {
vratestar = "Exempt";
}
TableRow tableRow = new TableRow(context);
//configuring row, setting layout params
tl.addView(tableRow);
} catch (JSONException ex){
//error handling
}
}
}
}
I know this is quite a common question, but I have searched around and my attempts to solve the below issue have been unsuccessful.
In particular, below are the messages that I am receiving from logcat.
08-03 17:55:53.885: E/AndroidRuntime(1286): FATAL EXCEPTION: main
08-03 17:55:53.885: E/AndroidRuntime(1286): Process: com.dooba.beta, PID: 1286
08-03 17:55:53.885: E/AndroidRuntime(1286): java.lang.RuntimeException: Unable to resume activity {com.dooba.beta/com.dooba.beta.MatchingActivity}: java.lang.NullPointerException
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2788)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2817)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.app.ActivityThread.access$800(ActivityThread.java:135)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.os.Handler.dispatchMessage(Handler.java:102)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.os.Looper.loop(Looper.java:136)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.app.ActivityThread.main(ActivityThread.java:5017)
08-03 17:55:53.885: E/AndroidRuntime(1286): at java.lang.reflect.Method.invokeNative(Native Method)
08-03 17:55:53.885: E/AndroidRuntime(1286): at java.lang.reflect.Method.invoke(Method.java:515)
08-03 17:55:53.885: E/AndroidRuntime(1286): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-03 17:55:53.885: E/AndroidRuntime(1286): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-03 17:55:53.885: E/AndroidRuntime(1286): at dalvik.system.NativeStart.main(Native Method)
08-03 17:55:53.885: E/AndroidRuntime(1286): Caused by: java.lang.NullPointerException
08-03 17:55:53.885: E/AndroidRuntime(1286): at com.dooba.beta.MatchingActivity.onResume(MatchingActivity.java:82)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1192)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.app.Activity.performResume(Activity.java:5310)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2778)
08-03 17:55:53.885: E/AndroidRuntime(1286): ... 12 more
Below is the code for the activity
public class MatchingActivity extends Activity {
protected ParseRelation<ParseUser> mFriendsRelation;
protected ParseUser mCurrentUser;
protected List<ParseUser> mUsers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.matching);
// Show the Up button in the action bar.
}
#Override
protected void onResume() {
super.onResume();
mCurrentUser = ParseUser.getCurrentUser();
setProgressBarIndeterminateVisibility(true);
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> users, ParseException e) {
if (e == null) {
mUsers = users;
} else {
// Something went wrong.
}
}
});
//This give you a list of users. Then to access one user you need to know the index the user is at.
ParseUser user = mUsers.get(5);
//then you can access that user's information
user.getString("name");
user.getNumber("age");
user.getString("headline");
}
}
Below is the code for the xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
Any assistance would be greatly appreciated.
Thanks in advance.
Updated code:
Error received
for the line
mUsers = new List<ParseUser>();
I receive the following messages:
"Cannot instantiate the type List<ParseUser>"
for the lines
user.getString("name");
user.getNumber("age");
user.getString("headline");
I receive the following error:
"user cannot be resolved"
Thanks in advance, and below is the complete updated code.
public class MatchingActivity extends Activity {
protected ParseRelation<ParseUser> mFriendsRelation;
protected ParseUser mCurrentUser;
protected List<ParseUser> mUsers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.matching);
// Show the Up button in the action bar.
//create list variable
mUsers = new List<ParseUser>();
}
#Override
protected void onResume() {
super.onResume();
mCurrentUser = ParseUser.getCurrentUser();
setProgressBarIndeterminateVisibility(true);
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> users, ParseException e) {
if (e == null) {
//add all the users to your list variable
mUsers.addAll(users);
} else {
// Something went wrong.
}
}
});
//check the size of your list to see how big it is before accessing it
final int size = mUsers.size();
//or use a loop to loop through each one
for(ParseUser mParseUser : mUsers) {
//skip over the current user
if(mParseUser == ParseUser.getCurrentUser())
continue;
user.getString("name");
user.getNumber("age");
user.getString("headline");
}
}
}
I think your problem is in the following line of code
ParseUser user = mUsers.get(5);
mUsers.get(5) is probably null, or doesn't exist. There is nothing in your code which guarantees that the list has to be at least size 5.
Try this instead
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.matching);
//create list variable
mUsers = new List<ParseUser>();
}
#Override
protected void onResume() {
...
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.findInBackground(new FindCallback<ParseUser>()
{
public void done(List<ParseUser> users, ParseException e)
{
if (e == null)
{
//add all the users to your list variable
mUsers.addAll(users);
//check the size of your list to see how big it is before accessing it
final int size = mUsers.size();
//or use a loop to loop through each one
for(ParseUser mParseUser : mUsers)
{
//skip over the current user
if(mParseUser == ParseUser.getCurrentUser())
continue;
//use the correct type when getting
final String mName = user.getString("name");
final int mNumber = user.getNumber("age");
final String mHeadLine = user.getString("headline");
}
}
else
{
// Something went wrong.
}
}
});
}