I have the following error when showing a PopupWindow.
The errors are triggered by the line:
checkInPopup.showAtLocation((ViewGroup) mapView.getParent(), Gravity.CENTER_HORIZONTAL, 0, 0);
mapView is a MapView and nothing is null.
The stacktrace:
01-08 18:00:09.402: E/AndroidRuntime(27768): Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
01-08 18:00:09.402: E/AndroidRuntime(27768): at android.view.ViewRootImpl.setView(ViewRootImpl.java:513)
01-08 18:00:09.402: E/AndroidRuntime(27768): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:301)
01-08 18:00:09.402: E/AndroidRuntime(27768): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:215)
01-08 18:00:09.402: E/AndroidRuntime(27768): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:140)
01-08 18:00:09.402: E/AndroidRuntime(27768): at android.view.Window$LocalWindowManager.addView(Window.java:537)
01-08 18:00:09.402: E/AndroidRuntime(27768): at android.widget.PopupWindow.invokePopup(PopupWindow.java:988)
01-08 18:00:09.402: E/AndroidRuntime(27768): at android.widget.PopupWindow.showAtLocation(PopupWindow.java:845)
01-08 18:00:09.402: E/AndroidRuntime(27768): at android.widget.PopupWindow.showAtLocation(PopupWindow.java:809)
01-08 18:00:09.402: E/AndroidRuntime(27768): at com.geoloc.ActivityCheckIn.onCreate(ActivityCheckIn.java:50)
01-08 18:00:09.402: E/AndroidRuntime(27768): at android.app.Activity.performCreate(Activity.java:4465)
01-08 18:00:09.402: E/AndroidRuntime(27768): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
This is the code from my activity (that extends MapActivity)
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.checkin);
mapView = (MapView) findViewById(R.id.mapview);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
checkInPopup = new PopupWindow(inflater.inflate(CHECK_IN_POPUP_LAYOUT, null, false));
checkInPopup.setOutsideTouchable(true);
checkInPopup.setHeight(100);
checkInPopup.setWidth(200);
checkInPopup.showAtLocation((ViewGroup) mapView.getParent(), Gravity.CENTER_HORIZONTAL, 0, 0);
}
Thank you for sharing your thoughts
Same problem happened with me when I try to show a popup menu in an activity.
I also got the same exception but I encountered problems and resolved it by providing the right context.
// at this line
Dialog dialog = new Dialog(getApplicationContext());
Use
YourActivityName.this instead of getApplicationContext()
and yes it worked for me may it will help someone else.
you are showing your popup too early. You may post a delayed runnable for showatlocation in Onresume , Give it a try
Edit:
This post seems to have the same problem answered Problems creating a Popup Window in Android Activity
Use:
YourActivityName.this
Instead of:
getApplicationContext();
There are two scenarios when this exception could occur. One is mentioned by nandeesh. Other scenario is mentioned here: http://blackriver.to/2012/08/android-annoying-exception-unable-to-add-window-is-your-activity-running/
Make sure you handle both of them
The correct way is to call popupwindow.show() at onWindowFocusChanged():
#Override
protected void onCreate(Bundle savedInstanceState) {
View view = LayoutInflater.from(mContext).inflate(R.layout.popup_window_layout, new LinearLayout(mContext), true);
popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
popupWindow.setContentView(view);
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
if (hasFocus) {
popupWindow.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
}
}
A popup's parent can't itself be a popup. Both of their parents must be the same. So, if you create a popup inside a popup, you must save the parent's popup and make it a parent.
here's an example
Try to show the pop like below
findViewById(R.id.main_layout).post(new Runnable() {
public void run() {
mPopupWindow.showAtLocation(findViewById(R.id.main_layout), Gravity.CENTER, 0, 0);
Button close = (Button) customView.findViewById(R.id.btn_ok);
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPopupWindow.dismiss();
doOtherStuff();
}
});
}
});
use this method before show
public static ViewGroup getActivityFirstLayout(Context ctx)
{
return (ViewGroup)((ViewGroup) ActivityMaster.getActivity(ctx).findViewById(android.R.id.content)).getChildAt(0);
}
private boolean activityIsOk(Activity activity)
{
boolean s1 = !(activity == null || activity.isFinishing());
if(s1)
{
View v = LayoutMaster.getActivityFirstLayout(activity);
return v.isShown() && ViewCompat.isLaidOut(v);
}
return false;
}
Try to use it
LayoutInflater inflater = (LayoutInflater).getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View view = inflate.from(YourActivity.this).inflate(R.layout.yourLayout, null);
Following many hours of search and testing i found following solution(by implementing different SO solutions) here it what didn't failed in any case i was getting crash.
Runnable runnable = new Runnable() {
#Override
public void run() {
//displayPopup,progress dialog or what ever action. example
ProgressDialogBox.setProgressBar(Constants.LOADING,youractivityName.this);
}};
Where logcat is indicating the crash is happening.. start a runnable .in my case at receiving broadcast.
runOnUiThread(new Runnable() {
#Override
public void run() {
if(!isFinishing()) {
new Handler().postAtTime(runnable,2000);
}
}
});
try to show popup like this
new Handler().postDelayed(new Runnable(){
public void run() {
popupWindow.showAtLocation(context.getWindow().getDecorView(), Gravity.CENTER,0,0);
}
}, 200L);
Related
I'm a new in RxJava in Android development. I had changed in project AsyncTask to RxJava and got a ConcurrentModificationException. Yes, I used collection (sparseArray) but it doesn't matter 'cause exeption was thrown in findViewById.setVisibility. Only when I try to invoke setVisibility. I confused, what I do wrong? I have a TextView in fragment. At first I set up OnClickListener, in listener I init Single.fromCallable, then I set up OnDragListener
TextView tv;
tv.setOnClickListener(v -> {
if (isClickEnable) {
tv.setBackgroundResource(R.drawable.cheap_dark);
cheapInObservable(tv);
}
});
tv.setOnDragListener(new MyDragListener());
private void cheapInObservable(TextView tView) {
Single.fromCallable( () -> tView).subscribeOn(Schedulers.io())
.delay(250, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
.doOnSuccess(this::onSuccessCheapIn)
.subscribe();
}
And in this code I get exeption:
private class MyDragListener implements View.OnDragListener {
#Override
public boolean onDrag(View v, DragEvent event) {
View dragView = (View)event.getLocalState();
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_ENDED:
if(!event.getResult()) {
if(dragView == v) {
dragView.setVisibility(View.VISIBLE);
activity.findViewById(sparseCheaps.get(dragView.getId())).
setVisibility(View.VISIBLE);
}
}
break;
private void onSuccessCheapIn(TextView tv) {
tv.setVisibility(View.INVISIBLE);
TextView tvd = activity.findViewById(sparseCheaps.get(tv.getId()));
tvd.setVisibility(View.VISIBLE);
AnimatorSet set = new AnimatorSet();
tvd.animate().rotation(0);
int up = activity.findViewById(R.id.guidelineGlowUp).getTop();
int left = getXcoord(tvd);
set.setDuration(400).playTogether(ObjectAnimator.ofFloat(tvd, TextView.TRANSLATION_X,
tvd.getX(), left),
ObjectAnimator.ofFloat(tvd, TextView.TRANSLATION_Y, tvd.getY(), up - 3));
set.setInterpolator(new AccelerateInterpolator((float) 0.4));
set.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
isAnimationCheaps = false;
super.onAnimationEnd(animation);
}
});
set.start();
}
I've found out that only the exeption is thrown when I use setVisibility. If I use AsyncTask instead of Rx it works without exception
StackTrace is:
java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:795)
at java.util.HashMap$KeyIterator.next(HashMap.java:822)
at android.view.ViewGroup.dispatchDragEvent(ViewGroup.java:1154)
at android.view.ViewGroup.dispatchDragEvent(ViewGroup.java:1156)
at android.view.ViewGroup.dispatchDragEvent(ViewGroup.java:1156)
at android.view.ViewGroup.dispatchDragEvent(ViewGroup.java:1156)
at android.view.ViewGroup.dispatchDragEvent(ViewGroup.java:1156)
at android.view.ViewGroup.dispatchDragEvent(ViewGroup.java:1156)
at android.view.ViewGroup.dispatchDragEvent(ViewGroup.java:1156)
at android.view.ViewGroup.dispatchDragEvent(ViewGroup.java:1156)
at android.view.ViewRootImpl.handleDragEvent(ViewRootImpl.java:4322)
at android.view.ViewRootImpl.access$1100(ViewRootImpl.java:103)
at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:3407)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5370)
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:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
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.
im trying to make a splash screen, the codes showing no errors, build succesfully, but when it started,it shows this message at the apps
and when i check the log on android monitor, it show these messages
08-07 05:41:23.709 16344-16344/com.android.andika.soundsmart E/WindowManager: android.view.WindowLeaked: Activity com.android.andika.soundsmart.SplashS has leaked window DecorView#e044f4c[] that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:418)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:331)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
at android.app.Dialog.show(Dialog.java:329)
at android.app.AlertDialog$Builder.show(AlertDialog.java:1112)
at android.app.Activity.performStart(Activity.java:6723)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2662)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2766)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1507)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6236)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:891)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:781)
this is the code from my splashscreen class
public class SplashS extends AppCompatActivity {
ProgressBar progressBar;
int status = 0;
int proses = 0;
Handler handle = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_s);
getSupportActionBar().setTitle("SPLASHSREEN");
ActionBar ab = getSupportActionBar();
ab.hide();
progressBar = (ProgressBar) findViewById(R.id.tunggu);
new Thread(new Runnable() {
#Override
public void run() {
while(status<100){
status = loading();
handle.post(new Runnable() {
#Override
public void run() {
progressBar.setProgress(status);
}
});
}
handle.post(new Runnable() {
#Override
public void run() {
Intent pindah = new Intent(SplashS.this,MenuS.class);
startActivity(pindah);
finish();
}
});
}
private int loading() {
try{
Thread.sleep(45);
}
catch(InterruptedException ie){
ie.printStackTrace();
}
return ++proses;
}
}).start();
}
}
i debug the app via an android phone with android N 7.1 OS.
i'll appreciate any answer, advice, or response. thanks :)
i think that error related to showing dialog where the activity is dismissed , but your code does not showing any dialogs so check if you are using 3rd party libraries which can do that
I'm creating a screen lock app, and faced notification able to drag down in the lock screen.
I've research it and found this solution to block the notification bar by using addView code below, but I cannot remove the view after user unlocked my app. Please advice how to remove the view.
I've try to use manager.removeView(view); in public void onDestroy() { but it crashed after run this code.
This is the error message
FATAL EXCEPTION: main
Process: com.mehuljoisar.lockscreen, PID: 10256
java.lang.IllegalArgumentException: View=android.view.View{42348cc0 V.ED.... ........ 0,0-0,0} not attached to window manager
at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:373)
at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:302)
at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:79)
at com.mehuljoisar.lockscreen.LockScreenActivity.disablePullNotificationTouch(LockScreenActivity.java:261)
at com.mehuljoisar.lockscreen.LockScreenActivity.access$100(LockScreenActivity.java:24)
at com.mehuljoisar.lockscreen.LockScreenActivity$2.onClick(LockScreenActivity.java:113)
at android.view.View.performClick(View.java:4469)
at android.view.View$PerformClick.run(View.java:18788)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5347)
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:835)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:651)
at dalvik.system.NativeStart.main(Native Method)
Where should I put the removeView code?
private void disablePullNotificationTouch(String gg) {
WindowManager manager = ((WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE));
WindowManager.LayoutParams localLayoutParams = new WindowManager.LayoutParams();
localLayoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
localLayoutParams.gravity = Gravity.TOP; //make the line top
localLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
// this is to enable the notification to recieve touch events
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
// Draws over status bar
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
localLayoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
localLayoutParams.height = (int) (25 * getResources().getDisplayMetrics().scaledDensity);
localLayoutParams.format = PixelFormat.RGBX_8888;
View view = new View(this);
if(gg == "on") {
manager.addView(view, localLayoutParams);
}else {
manager.removeView(view);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
disablePullNotificationTouch("on");
}
#Override
public void onDestroy() {
super.onDestroy();
disablePullNotificationTouch("off");
}
You use
WindowManager manager = ((WindowManager) this.getSystemService(Context.WINDOW_SERVICE));
Not use
WindowManager manager = ((WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE));
Try it!
i have Target.java(it is the main activity) and Layout.java.
When user clicks a button a url opens.
The button click is handled in Layout.java.
deleteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DebugLog.LOGD("Within onClick event of 'GO' button ");
Target.openURL();
}
});
Target.java has a static function openURL
public static void openURL() {
Uri uri = Uri.parse("http://www.thecinema.in");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
I'd like to know how i can make this code work, since the error im getting now is "Cannot make a static reference to the non-static method startActivity(Intent) from the type Activity" . I can understand startActivity will not work within a static function, but please suggest me how i could acheive the objective ..Im a newbie to android.FYI ..Thanks guys
-Updated code :
Layout.java
deleteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DebugLog.LOGD("Within onClick event of 'GO' button ");
Target iA = new Target();
iA.openURL();
}
});
Target.java
public void openURL() { //removed static keyword
DebugLog.LOGD("Within nDelete event of GO button ");
Uri uri = Uri.parse("http://www.thecinema.in");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
Exception thrown:
03-02 10:10:28.351: D/QCAR(6820): Within onClick event of 'GO' button
03-02 10:10:28.351: W/dalvikvm(6820): threadid=1: thread exiting with uncaught exception (group=0x400207d8)
03-02 10:10:28.361: E/AndroidRuntime(6820): FATAL EXCEPTION: main
03-02 10:10:28.361: E/AndroidRuntime(6820): java.lang.NullPointerException
03-02 10:10:28.361: E/AndroidRuntime(6820): at android.app.Activity.startActivityForResult(Activity.java:2817)
03-02 10:10:28.361: E/AndroidRuntime(6820): at android.app.Activity.startActivity(Activity.java:2923)
03-02 10:10:28.361: E/AndroidRuntime(6820): at com.ingage.pocs.phonegap.Layout$4.onClick(Layout.java:124)
03-02 10:10:28.361: E/AndroidRuntime(6820): at android.view.View.performClick(View.java:2408)
03-02 10:10:28.361: E/AndroidRuntime(6820): at android.view.View$PerformClick.run(View.java:8816)
03-02 10:10:28.361: E/AndroidRuntime(6820): at android.os.Handler.handleCallback(Handler.java:587)
03-02 10:10:28.361: E/AndroidRuntime(6820): at android.os.Handler.dispatchMessage(Handler.java:92)
03-02 10:10:28.361: E/AndroidRuntime(6820): at android.os.Looper.loop(Looper.java:123)
03-02 10:10:28.361: E/AndroidRuntime(6820): at android.app.ActivityThread.main(ActivityThread.java:4633)
Guys what went wrong in here..
i was able to come up with a solution for this question.
Under Target.java i created openURL() as:
public void openURL(Context context)
{
Intent intent = new Intent("com.ingage.pocs.phonegap.URL");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
I created a new Activity OpenURL.java and associated the intent "com.ingage.pocs.phonegap.URL" with it:
package com.ingage.pocs.phonegap;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
public class OpenURL extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
DebugLog.LOGD("Within BookTicketsActivity Activity GO button ");
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.thecinema.in"));
startActivity(browserIntent);
}
}
Layout.java:
private Context applicationContext;
deleteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DebugLog.LOGD("Within onClick event of 'GO' button ");
ImageTargets ia =new ImageTargets();
ia.openURL(applicationContext);
iA.openURL();
}
});
The best thing is, it worked :) If you guys come up with a better or more sensible solution , pls do post here.thank you
startActivity is not static and since you call it from Target not Layout it cannot resolve call context.
You'll need to call startActivity from Layout.java or pass reference or Target to Layout class
do it like this
Layout.java:
deleteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DebugLog.LOGD("Within onClick event of 'GO' button ");
Target.openURL(Layout.this);
}
});
Target.java:
public static void openURL(Context context) {
Uri uri = Uri.parse("http://www.thecinema.in");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
context.startActivity(intent);
}
You have
Targets iA = new Targets();
Did you, perhaps, mean to write
Target iA = new Target();
That would throw a NullPointerException because you're asking Java to find a class named Targets when none exists.