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();
Related
This question already has answers here:
How to prevent a dialog from closing when a button is clicked
(21 answers)
What does "java.lang.NullPointerException: Attempt to invoke virtual method '...' on a null object reference" mean, and how do I solve it? [duplicate]
(1 answer)
Closed 12 months ago.
After executing a http request in a DialogFragment, my screen comes to the main activity screen from the screen showing up the DialogFragment.
I want the screen not to move after above execution.
I hope you have some ideas about this.
This is the DialogFragment class
public class fragmentForRm extends DialogFragment {
String url3 ="http://192.168.3.3:8080/html/apiDelete.php";
#Override
#NonNull
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_for_delete)
.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
StringRequest stringRequest = new StringRequest(Request.Method.POST, url3,
new Response.Listener<String>(){
#Override
public void onResponse(String response){
Toast.makeText(getActivity().getApplicationContext(), response.trim(), Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity().getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams(){
Map<String, String> params = new HashMap<String, String>();
Bundle bundle = getArguments();
String t = bundle.getString("threadForDelete", "");
params.put("delete_thread_content", t);
return params;
}
};
queue.add(stringRequest);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
This is the method call for DialogFragment
private void rmThreadListViewListener(){
listView.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> adapter,
View view, int pos, long id){
String selectedThread = (String) adapter.getItemAtPosition(pos);
fragmentForRm dialogFragment = new fragmentForRm();
Bundle bundle = new Bundle();
bundle.putString("threadForDelete", selectedThread);
dialogFragment.setArguments(bundle);
FragmentManager fm = getSupportFragmentManager();
dialogFragment.show(fm, null);
return true;
}
}
);
}
This is an error code after executing the http request from the DialogFragment
W/Settings: Setting device_provisioned has moved from android.provider.Settings.Secure to android.provider.Settings.Global.
V/HiTouch_HiTouchSensor: User setup is finished.
V/AudioManager: querySoundEffectsEnabled...
W/libEGL: EGLNativeWindowType 0x7167100390 disconnect failed
D/OpenGLRenderer: endAllActiveAnimators on 0x70fa508600 (RippleDrawable) with handle 0x715a9da300
I/BlockMonitor: dispatchingThrewException In MainThread
D/AndroidRuntime: Shutting down VM
I/QarthLog: [PatchStore] createDisableExceptionQarthFile
[PatchStore] create disable file for com.example.testjsondisplay uid is 10270
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.testjsondisplay, PID: 11947
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context androidx.fragment.app.FragmentActivity.getApplicationContext()' on a null object reference
at com.example.testjsondisplay.fragmentForRm$2$1.onResponse(fragmentForRm.java:38)
at com.example.testjsondisplay.fragmentForRm$2$1.onResponse(fragmentForRm.java:35)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:82)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:29)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
at android.os.Handler.handleCallback(Handler.java:888)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:8147)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
I/Process: Sending signal. PID: 11947 SIG: 9
Connected to process 12222 on device 'huawei-mar_lx2j-QUR0219B14005574'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/testjsondispla: QarthPatchMonintor::Init
QarthPatchMonintor::StartWatch
QarthPatchMonintor::WatchPackage: /data/hotpatch/fwkhotpatch/
QarthPatchMonintor::CheckAndWatchPatch: /data/hotpatch/fwkhotpatch/com.example.testjsondisplay
QarthPatchMonintor::CheckAndWatchPatch: /data/hotpatch/fwkhotpatch/all
QarthPatchMonintor::Run
I/testjsondispla: QarthPatchMonintor::Reading
QarthPatchMonintor::CheckNotifyEvent
QarthPatchMonintor::CheckNotifyEvent before read
I/HwApiCacheMangerEx: apicache path=/storage/emulated/0 state=mounted key=com.example.testjsondisplay#10270#256
I/HwApiCacheMangerEx: apicache path=/storage/emulated/0 state=mounted key=com.example.testjsondisplay#10270#0
I/AwareBitmapCacher: init processName:com.example.testjsondisplay pid=12222 uid=10270
E/AwareLog: AtomicFileUtils: readFileLines file not exist: android.util.AtomicFile#fff406e
V/ActivityThread: callActivityOnCreate
V/HwWidgetFactory: : successes to get AllImpl object and return....
I/OverScrollerOptimization: start init SmartSlideOverScroller and get the overscroller config
get the overscroller config
W/testjsondispla: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/testjsondispla: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
D/ActivityThread: add activity client record, r= ActivityRecord{a741a53 token=android.os.BinderProxy#1ab7ded {com.example.testjsondisplay/com.example.testjsondisplay.MainActivity}} token= android.os.BinderProxy#1ab7ded
D/HiTouch_PressGestureDetector: onAttached, package=com.example.testjsondisplay, windowType=1, mHiTouchRestricted=false
I/iGraphics: [0020080c] pn: com.example.testjsondisplay, p: 12222
[0030080c] no spt app: com.example.testjsondisplay
D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
W/Gralloc3: mapper 3.x is not supported
E/: APS:IFLoad:importExternalFunctions, search function createNewHwApsUtils failed, dlsym err:undefined symbol: createNewHwApsUtils
D/: APS:importExternalFunctions OK
I/HwViewRootImpl: removeInvalidNode jank list is null
public class ProgressCircleActivity extends AppCompatActivity {
private ProgressDialog progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.progress_circle_activity);
progressBar = new ProgressDialog(ProgressCircleActivity.this);
progressBar.setMessage("Please wait ...");
progressBar.setCancelable(true);
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(3*1000);
Intent i=new Intent(ProgressCircleActivity.this,PhoneNumberLogin.class);
startActivity(i);
//Remove activity
finish();
} catch (InterruptedException e) {
e.printStackTrace();
}
progressBar.dismiss();
}
}).start();
}
}
Here is my logcat
10-05 16:12:22.577 27797-27797/? E/SELinux: [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
10-05 16:12:32.397 27797-27797/com.example.dis015.meetdax2danish E/WindowManager: android.view.WindowLeaked: Activity com.example.dis015.meetdax2danish.ProgressCircleActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{25b6bc4a V.E..... R......D 0,0-501,174} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:520)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:287)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.app.Dialog.show(Dialog.java:325)
at com.example.dis015.meetdax2danish.ProgressCircleActivity.onCreate(ProgressCircleActivity.java:25)
at android.app.Activity.performCreate(Activity.java:6575)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3143)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3300)
at android.app.ActivityThread.access$1000(ActivityThread.java:211)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1705)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6946)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
This is my splashScreenActivity when i open the app is getting crash.But in some mobiles the app is not crashing.I dont know what is the issue please help me to sort out
You did not dismiss the progressbar so it is showing that leaked window message.
Before finishing the activity please dismiss the progressbar dialog.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.progress_circle_activity);
progressBar = new ProgressDialog(ProgressCircleActivity.this);
progressBar.setMessage("Please wait ...");
progressBar.setCancelable(true);
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(3*1000);
Intent i=new Intent(ProgressCircleActivity.this,PhoneNumberLogin.class);
startActivity(i);//dismiss the progressdialog
progressBar.dismiss();
//Remove activity
finish();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
I have a problem with AsyncTask in my app. AsyncTask is located in SplashScreenAcivity.java. It downloads data using json for MainActivity.java while showing splash screen. When data is loaded, app shows MainActivity screen. However, when i turn off internet connection app crashes. Instead of it i would like to move to MainActivity.java and show toast that internet connection must be turned on. SplashScreen.java loads data for listView in MainActivity.
SplashActivityScreen.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
new DownloadData().execute();
}
private class DownloadData extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
SyncHttpClient clientOne = new SyncHttpClient();
clientOne.get("https://api.themoviedb.org/3/tv/top_rated?api_key=d253f520df9cd868af7db8daaa0db8fb&language=en-US", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
try {
tvseries0 = response.getJSONArray("results").getJSONObject(0).getString("name");
tvseries1 = response.getJSONArray("results").getJSONObject(1).getString("name");
tvseries2 = response.getJSONArray("results").getJSONObject(2).getString("name");
tvseries3 = response.getJSONArray("results").getJSONObject(3).getString("name");
tvseries4 = response.getJSONArray("results").getJSONObject(4).getString("name");
tvseries5 = response.getJSONArray("results").getJSONObject(5).getString("name");
tvseries6 = response.getJSONArray("results").getJSONObject(6).getString("name");
tvseries7 = response.getJSONArray("results").getJSONObject(7).getString("name");
tvseries8 = response.getJSONArray("results").getJSONObject(8).getString("name");
tvseries9 = response.getJSONArray("results").getJSONObject(9).getString("name");
tvseries10 = response.getJSONArray("results").getJSONObject(10).getString("name");
tvseries11 = response.getJSONArray("results").getJSONObject(11).getString("name");
tvseries12 = response.getJSONArray("results").getJSONObject(12).getString("name");
tvseries13 = response.getJSONArray("results").getJSONObject(13).getString("name");
tvseries14 = response.getJSONArray("results").getJSONObject(14).getString("name");
tvseries15 = response.getJSONArray("results").getJSONObject(15).getString("name");
tvseries16 = response.getJSONArray("results").getJSONObject(16).getString("name");
tvseries17 = response.getJSONArray("results").getJSONObject(17).getString("name");
tvseries18 = response.getJSONArray("results").getJSONObject(18).getString("name");
tvseries19 = response.getJSONArray("results").getJSONObject(19).getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers,Throwable e , JSONObject response) {
Toast.makeText(SplashScreenActivity.this, "Turn on the internet and swipe to refresh.", Toast.LENGTH_SHORT).show();
}
});
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("tvseries0", tvseries0);
i.putExtra("tvseries1", tvseries1);
i.putExtra("tvseries2", tvseries2);
i.putExtra("tvseries3", tvseries3);
i.putExtra("tvseries4", tvseries4);
i.putExtra("tvseries5", tvseries5);
i.putExtra("tvseries6", tvseries6);
i.putExtra("tvseries7", tvseries7);
i.putExtra("tvseries8", tvseries8);
i.putExtra("tvseries9", tvseries9);
i.putExtra("tvseries10", tvseries10);
i.putExtra("tvseries11", tvseries11);
i.putExtra("tvseries12", tvseries12);
i.putExtra("tvseries13", tvseries13);
i.putExtra("tvseries14", tvseries14);
i.putExtra("tvseries15", tvseries15);
i.putExtra("tvseries16", tvseries16);
i.putExtra("tvseries17", tvseries17);
i.putExtra("tvseries18", tvseries18);
i.putExtra("tvseries19", tvseries19);
startActivity(i);
finish();
}
}
}
Crash 1
04-30 13:15:35.165 12349-12365/przemo.me.recommend.recommendme E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: przemo.me.recommend.recommendme, PID: 12349
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:318)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Caused by: java.lang.RuntimeException: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at com.loopj.android.http.AsyncHttpResponseHandler.onUserException(AsyncHttpResponseHandler.java:304)
at com.loopj.android.http.AsyncHttpResponseHandler.handleMessage(AsyncHttpResponseHandler.java:395)
at com.loopj.android.http.AsyncHttpResponseHandler.sendMessage(AsyncHttpResponseHandler.java:401)
at com.loopj.android.http.AsyncHttpResponseHandler.sendFailureMessage(AsyncHttpResponseHandler.java:319)
at com.loopj.android.http.AsyncHttpRequest.run(AsyncHttpRequest.java:109)
at com.loopj.android.http.SyncHttpClient.sendRequest(SyncHttpClient.java:95)
at com.loopj.android.http.AsyncHttpClient.get(AsyncHttpClient.java:1078)
at com.loopj.android.http.AsyncHttpClient.get(AsyncHttpClient.java:1037)
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData.doInBackground(SplashScreenActivity.java:64)
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData.doInBackground(SplashScreenActivity.java:56)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:346)
at android.widget.Toast.<init>(Toast.java:101)
at android.widget.Toast.makeText(Toast.java:260)
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData$1.onFailure(SplashScreenActivity.java:103)
at com.loopj.android.http.JsonHttpResponseHandler.onFailure(JsonHttpResponseHandler.java:233)
at com.loopj.android.http.AsyncHttpResponseHandler.handleMessage(AsyncHttpResponseHandler.java:359)
at com.loopj.android.http.AsyncHttpResponseHandler.sendMessage(AsyncHttpResponseHandler.java:401)
at com.loopj.android.http.AsyncHttpResponseHandler.sendFailureMessage(AsyncHttpResponseHandler.java:319)
at com.loopj.android.http.AsyncHttpRequest.run(AsyncHttpRequest.java:109)
at com.loopj.android.http.SyncHttpClient.sendRequest(SyncHttpClient.java:95)
at com.loopj.android.http.AsyncHttpClient.get(AsyncHttpClient.java:1078)
at com.loopj.android.http.AsyncHttpClient.get(AsyncHttpClient.java:1037)
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData.doInBackground(SplashScreenActivity.java:64)
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData.doInBackground(SplashScreenActivity.java:56)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Crash 2
04-30 13:15:35.162 12349-12365/przemo.me.recommend.recommendme E/AsyncHttpRH: User-space exception detected!
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:346)
at android.widget.Toast.<init>(Toast.java:101)
at android.widget.Toast.makeText(Toast.java:260)
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData$1.onFailure(SplashScreenActivity.java:103)
at com.loopj.android.http.JsonHttpResponseHandler.onFailure(JsonHttpResponseHandler.java:233)
at com.loopj.android.http.AsyncHttpResponseHandler.handleMessage(AsyncHttpResponseHandler.java:359)
at com.loopj.android.http.AsyncHttpResponseHandler.sendMessage(AsyncHttpResponseHandler.java:401)
at com.loopj.android.http.AsyncHttpResponseHandler.sendFailureMessage(AsyncHttpResponseHandler.java:319)
at com.loopj.android.http.AsyncHttpRequest.run(AsyncHttpRequest.java:109)
at com.loopj.android.http.SyncHttpClient.sendRequest(SyncHttpClient.java:95)
at com.loopj.android.http.AsyncHttpClient.get(AsyncHttpClient.java:1078)
at com.loopj.android.http.AsyncHttpClient.get(AsyncHttpClient.java:1037)
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData.doInBackground(SplashScreenActivity.java:64)
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData.doInBackground(SplashScreenActivity.java:56)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
You can not do UI operations from non UI thread. Like in your code you are showing Toast in Async task thread.
You should replace
Toast.makeText(SplashScreenActivity.this, "Turn on the internet and swipe to refresh.", Toast.LENGTH_SHORT).show();
with this
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(SplashScreenActivity.this, "Turn on the internet and swipe to refresh.", Toast.LENGTH_SHORT).show();
}
});
use -
SplashScreenActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(SplashScreenActivity.this, "Turn on the internet and swipe to refresh.", Toast.LENGTH_SHORT).show();
}
});
Here is a server connection AsyncTask task that I created years ago in Android Java. The background task works successfully. I used it to update in the background the data repository in the App I developed at that time.
public class DataExchangeStore extends Application {
public void startServerConnection(Context contextGlobal, Activity activityGlobal) {
this.contextGlobal = contextGlobal;
this.activityGlobal = activityGlobal;
connectTask = new ConnectTask();
connectTask.execute("");
}
private ConnectTask connectTask;
public class ConnectTask extends AsyncTask<String, String, TCPClient> {
#Override
protected TCPClient doInBackground(String... message) {
android.os.Process.setThreadPriority( android.os.Process.THREAD_PRIORITY_BACKGROUND);
// we create a TCPClient object
mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
#Override
// here the messageReceived method is implemented
public void messageReceived(ChatMessage message) {
// this method calls the onProgressUpdate
publishProgress(message.getMessage());
}
}, contextGlobal, activityGlobal);
mTcpClient.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
System.err.println(values[0]);
// do your stuff here
}
}
Import is to permanently lock the screen orientation of the activity, specifying the screenOrientation attribute in the Android-Manifest file with portrait or landscape values:
<activity android:screenOrientation="portrait" />
Although previous answers are not wrong, using runOnUiThread() to jump out of the background thread in the AsyncTask is not a good practice. You have the onPostExecute() method for that.
What you should be doing is passing a result object to onPostExecute(). This object would encapsulate the result state (ie: error or success) and the actual data received. Then in onPostExecute() you check the result state and display a Toast if the state is error.
And do yourself a favor and replace your 20 TvSerie objects by a List<TvSerie> and do a loop in you AsyncTask to populate the list.
Please refer to the AsyncTask documentation for details on how to properly use it.
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();
}
}
}
hi I am using google license checker on my app it works on API 19 and below but crashes on lollipop. I saw the code that has to be add to my license check code but I don't know where to put this code or what should I edit. here is my code
log:
java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=com.android.vending.licensing.ILicensingService }
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=com.android.vending.licensing.ILicensingService }
at android.app.ContextImpl.validateServiceIntent(ContextImpl.java:1674)
at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1773)
at android.app.ContextImpl.bindService(ContextImpl.java:1751)
at android.content.ContextWrapper.bindService(ContextWrapper.java:538)
at com.google.android.vending.licensing.LicenseChecker.checkAccess(LicenseChecker.java:150)
at appinventor.ai_drsalmanshah165.Clinical_Examination.Splash.doCheck(Splash.java:103)
at appinventor.ai_drsalmanshah165.Clinical_Examination.Splash.onCreate(Splash.java:51)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
... 10 more
Java code:
public class Splash extends Activity {
MyLicenseCheckerCallback mLicenseCheckerCallback;
LicenseChecker mChecker;
byte[] SALT = new byte[] {
my salt no. };
//Handler mHandler;
String BASE64_PUBLIC_KEY="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoxvDF3HGQtrRch14wCPN6nAxasak8X4shJM6bCumNS+6xRXTnRZOSyAvHNa1145KlE/i1sy/";
Context mContext;
IBinder serviceBinder;
String deviceId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash);
mLicenseCheckerCallback = new MyLicenseCheckerCallback();
deviceId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
// Construct the LicenseChecker with a policy.
mChecker = new LicenseChecker(
this, (Policy) new ServerManagedPolicy(Splash.this, new AESObfuscator(SALT, getPackageName(), deviceId)),
BASE64_PUBLIC_KEY);
doCheck();
}
private class MyLicenseCheckerCallback implements LicenseCheckerCallback {
#Override
public void allow(int reason) {
// TODO Auto-generated method stub
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
// Toast.makeText(Splash.this, "License Verified", Toast.LENGTH_SHORT).show();
Intent intent=new Intent(Splash.this,Home.class);
startActivity(intent);
finish();
// Should allow user access.
// so do nothing
}
#Override
public void dontAllow(int reason) {
// TODO Auto-generated method stub
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
// Toast.makeText(Splash.this, "License Verification Failed", Toast.LENGTH_SHORT).show();
createDialog();
}
#Override
public void applicationError(int errorCode) {
// TODO Auto-generated method stub
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mChecker.onDestroy();
}
private void doCheck() {
// mCheckLicenseButton.setEnabled(false);
setProgressBarIndeterminateVisibility(true);
/// mStatusText.setText(R.string.checking_license);
mChecker.checkAccess(mLicenseCheckerCallback);
}
public void createDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("PIRACY WARNING");
builder.setMessage("This application is not licensed. Please purchase it from Android Market. If you received this message in error, please contact Support.");
builder.setPositiveButton("Buy Now", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(
"http://market.android.com/details?id=" + getPackageName()));
startActivity(marketIntent);
}
});
builder.setNegativeButton("Quit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
and here is the other code which I got that this can solve my problem. but don't know where to put it.
Intent serviceIntent = new Intent(
new String(Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U=")));
serviceIntent.setPackage("com.android.vending");
boolean bindResult = mContext
.bindService(
serviceIntent,
this, // ServiceConnection.
Context.BIND_AUTO_CREATE);
Waiting for an official solution, the current solution consists in patching Google's LicenseChecker class
com.google.android.vending.licensing.LicenseChecker.checkAccess(LicenseChecker.java:150)
like this:
new String(
- Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U="))),
+ Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U=")))
+ .setPackage("com.android.vending"), // this fix the 'IllegalArgumentException: Service Intent must be explicit'
this, // ServiceConnection.
Adding package name with statement setPackage("com.android.vending") makes the Intent explicit, i.e., 'safe' (as requested by Android Lollipop )
Note:
Please pay attention as after modifying LicenseChecker class you must change the min sdk version from 3 to 4 (thanks russellhoff)
Source:
https://code.google.com/p/android/issues/detail?id=78505#c19