MediaController - Error when Show() called - java

I have this code for show the MediaController, but it give me a fatal error when I'm calling to Show() method.
The MediaPlayer itself working on Service and get Intent from the MediaPlayerControl interface.
My code:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaController = new MediaController(this, false);
mediaController.setMediaPlayer(mediaPlayerControl);
mediaController.setAnchorView(findViewById(R.id.mediaController));
mediaController.setEnabled(true);
mediaController.show(0);
}
//implements MediaPlayerControl interface
private MediaPlayerControl mediaPlayerControl = new MediaPlayerControl()
{
//Override the methods to send Intent to the MediaPlayer Service
....
....
};
my logcat:
07-27 11:03:07.365: E/AndroidRuntime(328): FATAL EXCEPTION: main
07-27 11:03:07.365: E/AndroidRuntime(328): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.radius100fm/com.example.radius100fm.MainActivity}: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
07-27 11:03:07.365: E/AndroidRuntime(328): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
07-27 11:03:07.365: E/AndroidRuntime(328): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
07-27 11:03:07.365: E/AndroidRuntime(328): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
07-27 11:03:07.365: E/AndroidRuntime(328): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
07-27 11:03:07.365: E/AndroidRuntime(328): at android.os.Handler.dispatchMessage(Handler.java:99)
07-27 11:03:07.365: E/AndroidRuntime(328): at android.os.Looper.loop(Looper.java:123)
07-27 11:03:07.365: E/AndroidRuntime(328): at android.app.ActivityThread.main(ActivityThread.java:3683)
07-27 11:03:07.365: E/AndroidRuntime(328): at java.lang.reflect.Method.invokeNative(Native Method)
07-27 11:03:07.365: E/AndroidRuntime(328): at java.lang.reflect.Method.invoke(Method.java:507)
07-27 11:03:07.365: E/AndroidRuntime(328): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
07-27 11:03:07.365: E/AndroidRuntime(328): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
07-27 11:03:07.365: E/AndroidRuntime(328): at dalvik.system.NativeStart.main(Native Method)
07-27 11:03:07.365: E/AndroidRuntime(328): Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
07-27 11:03:07.365: E/AndroidRuntime(328): at android.view.ViewRoot.setView(ViewRoot.java:527)
07-27 11:03:07.365: E/AndroidRuntime(328): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
07-27 11:03:07.365: E/AndroidRuntime(328): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
07-27 11:03:07.365: E/AndroidRuntime(328): at android.view.Window$LocalWindowManager.addView(Window.java:424)
07-27 11:03:07.365: E/AndroidRuntime(328): at android.widget.MediaController.show(MediaController.java:304)
07-27 11:03:07.365: E/AndroidRuntime(328): at com.example.radius100fm.MainActivity.onCreate(MainActivity.java:100)
07-27 11:03:07.365: E/AndroidRuntime(328): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-27 11:03:07.365: E/AndroidRuntime(328): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
07-27 11:03:07.365: E/AndroidRuntime(328): ... 11 more
What is the problem with my code?

Use this method.
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(mediaController != null)
mediaController.show(0);
}

I got the same problem and after several hours got the solution. I did the following:
Summary:
The Activity class implements the interfaces: MediaPlayer.OnPreparedListener and MediaController.MediaPlayerControl
OnCreate. setContentView.
onStart. Create MediaPlayer and MediaController, start the listener with setOnPreparedListener and call prepare() method of MediaPlayer.
Implement method onPrepared. Link the mediaController with the mediaPlayer, start mediaPlayer and here is where the method show() is called using a handler, only when we know that mediaPlayer is ready.
My code:
public class MainActivity extends Activity implements MediaPlayer.OnPreparedListener, MediaController.MediaPlayerControl {
private static final String TAG = "AudioPlayer";
private MediaPlayer mediaPlayer;
private MediaController mediaController;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
Log.d(TAG, "Play - onStart");
super.onStart();
mediaPlayer = new MediaPlayer();
mediaController = new MediaController(this);
mediaPlayer.setOnPreparedListener(this);
try {
AssetFileDescriptor afd = getApplicationContext().getResources().openRawResourceFd(R.raw.audio_example);
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
mediaPlayer.prepare();
afd.close();
} catch (IOException e) {
Log.e(TAG, "Error opening audio: " + e.getCause());
}
}
// override this method because of the OnPreparedListener interface
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
Log.d(TAG, "Play - onPrepared");
mediaController.setMediaPlayer(this);
mediaController.setAnchorView(findViewById(R.id.mediaController1));
mediaPlayer.start();
handler.post(new Runnable() {
#Override
public void run() {
mediaController.setEnabled(true);
mediaController.show(0);
}
});
}
// override these methods because of the MediaController.MediaPlayerControl interface
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getBufferPercentage() {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
#Override
public int getDuration() {
return mediaPlayer.getDuration();
}
#Override
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
#Override
public void pause() {
mediaPlayer.pause();
}
#Override
public void seekTo(int pos) {
mediaPlayer.seekTo(pos);
}
#Override
public void start() {
mediaPlayer.start();
}
// release resources before kill the Activity
#Override
protected void onStop() {
Log.d(TAG, "Play - onStop");
super.onStop();
if (mediaPlayer != null) {
mediaController.hide();
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
} }

Ok, so finely I found the answer.
The problem is in the line:
mediaController.show(0);
Because it called in onCreate() and the app still not activated.
Simple tried, add bottom that callingmediaController.show(0); when it clicked, and the app work perfect.
So now I have to call this line after the app get activate.
I'm tried onStart() and onResume() and it not working. The same error logCat.
How can I fix that??

I needed to show the MediaController to a already running MediaPlayer, so I couldn't set the OnPreparedListener like e_v_e said.
With the answer to this question: Can't fix MediaController.show() exception I discovered that the show method is been called before all the activity lifecycle methods were called. The solution proposed there(setting a delay to show) works, but to avoid the delay, you can place the show inside the onAttachedToWindow method, that is called after all the activity lifecycle methods.

Just put the mediaPlayer.prepare() and mediaPlayer.start() in a thread like handler or AsyncTask and done.
If you are using kotlin and anko lib, you can put it in doAsync {}.

Related

ASyncTask with progressdialog and button

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

Create Dialog Box For Checking Internet Connection in Android

I'm implementing to show dialog box when Internet is offline, when i run my app i got "FATAL Exception main" and ClassCastException when when i click on button and application is crash . Can someone tell me what i am doing wrong ? Thanks to you in Advanced.
here is code how i check is internet enabled or not:
public class AndroidDetectInternetConnectionActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnStatus = (Button) findViewById(R.id.btn_check);
btnStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isOnline())
{
showNoConnectionDialog(this);
}
}
});
}
public static void showNoConnectionDialog(OnClickListener onClickListener)
{
final Context ctx = (Context) onClickListener;
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setCancelable(true);
builder.setMessage(R.string.no_connection);
builder.setTitle(R.string.no_connection_title);
builder.setPositiveButton(R.string.settings_button_text, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
ctx.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
});
builder.setNegativeButton(R.string.cancel_button_text, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
return;
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog) {
return;
}
});
builder.show();
}
public boolean isOnline()
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting())
{
return true;
}
return false;
}
}
// This is my Log Cat stack trace
11-15 11:57:19.115: D/AndroidRuntime(453): Shutting down VM
11-15 11:57:19.115: W/dalvikvm(453): threadid=1: thread exiting with uncaught exception (group=0x40015560)
11-15 11:57:19.122: E/AndroidRuntime(453): FATAL EXCEPTION: main
11-15 11:57:19.122: E/AndroidRuntime(453): java.lang.ClassCastException: com.example.detectinternetconnection.AndroidDetectInternetConnectionActivity$1
11-15 11:57:19.122: E/AndroidRuntime(453): at com.example.detectinternetconnection.AndroidDetectInternetConnectionActivity.showNoConnectionDialog(AndroidDetectInternetConnectionActivity.java:99)
11-15 11:57:19.122: E/AndroidRuntime(453): at com.example.detectinternetconnection.AndroidDetectInternetConnectionActivity$1.onClick(AndroidDetectInternetConnectionActivity.java:64)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.view.View.performClick(View.java:2485)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.view.View$PerformClick.run(View.java:9080)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.os.Handler.handleCallback(Handler.java:587)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.os.Handler.dispatchMessage(Handler.java:92)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.os.Looper.loop(Looper.java:123)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.app.ActivityThread.main(ActivityThread.java:3683)
11-15 11:57:19.122: E/AndroidRuntime(453): at java.lang.reflect.Method.invokeNative(Native Method)
11-15 11:57:19.122: E/AndroidRuntime(453): at java.lang.reflect.Method.invoke(Method.java:507)
11-15 11:57:19.122: E/AndroidRuntime(453): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-15 11:57:19.122: E/AndroidRuntime(453): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-15 11:57:19.122: E/AndroidRuntime(453): at dalvik.system.NativeStart.main(Native Method)
11-15 11:57:24.892: I/Process(453): Sending signal. PID: 453 SIG: 9
change this line
final Context ctx = (Context) onClickListener;
to below one
final Context ctx = AndroidDetectInternetConnectionActivity.this;
basically you are trying to conver onClickListener to Contex which is incorrect and can not be casted.
Either you directly use ActivityName.this wherever you need context instance, or define static Context ctx as a class variable and intialize it in onCreate()by just adding this line ctx =this also remember to intialize it before using it.
Enjoy
There are two ways to solve this problem.
1) showNoConnectionDialog(this); and later on:
public static void showNoConnectionDialog(Context ctx) ...
2) showNoConnectionDialog(); and later on: public void showNoConnectionDialog() { Context ctx = AndroidDetectInternetConnectionActivity.this
You basic problem is generated by the line:
final Context ctx = (Context) onClickListener;
This is simply not a context so trying to force it to be one doesn't work.
I believe that you wanted to do was pass a context (or activity) to this function (as opposed to the local unnamed OnClickListener class that you are now passing)
The easiest solution would be to simple not pass anything to the constructor and use AndroidDetectInternetConnectionActivity.this to access your valid context.

adding a counter in an android activity

I am very new to android. I have a counter on some SomeActivity, but when I get to the page corresponding to SomeActivity, my app crashes :
final TextView counter = (TextView) findViewById(R.id.laws_counter);
ImageView handDown = (ImageView) findViewById(R.id.handViewDown);
counter.setText("" + 0);
I want that on click of the handown, the counter is idented by -1. Here's
handDown.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(NewsActivity.this,
"The favorite list would appear on clicking this icon",
Toast.LENGTH_LONG).show();
setDown();
}
private void setDown() {
String count = counter.getText().toString();
int now_count = Integer.parseInt(count) +1;
counter.setText(String.valueOf(now_count));
}
});
Is this code correct ?
Update : here's the logcat
10-22 00:18:05.579: ERROR/AndroidRuntime(378): FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.donnfelker.android.bootstrap/com.donnfelker.android.bootstrap.ui.NewsActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.donnfelker.android.bootstrap.ui.NewsActivity.onCreate(NewsActivity.java:41)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
... 11 more
There are many ways that you can implement that functionality but think this would be an easy solution.
Make a helper method:
public class PreferencesData {
public static void saveInt(Context context, String key, int value) {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
sharedPrefs.edit().putInt(key, value).commit();
}
public static int getInt(Context context, String key, int defaultValue) {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
return sharedPrefs.getInt(key, defaultValue);
}
}
Then simply call the putInt method to save the counter in any Activity and getInt to get it again in any other Activity. As long as you use the same key both places.

BadTokenException even after referring to Activity and not the application context

android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy#406a6678 is not valid; is your activity running?
at android.view.ViewRoot.setView(ViewRoot.java:528)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.view.Window$LocalWindowManager.addView(Window.java:424)
at android.app.Dialog.show(Dialog.java:241)
at android.app.Activity.showDialog(Activity.java:2569)
at android.app.Activity.showDialog(Activity.java:2527)
at MyCode$8$4.run(MyCode.java:557)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:636)
at dalvik.system.NativeStart.main(Native Method)
I am getting above exception when following code is executed. This file dialog will shown once the processing is done and progressbar reaches 100%. FileSaveDialog extends Dialog and implements OnCompletionListener
runOnUiThread(new Runnable() {
#Override
public void run() {
showDialog(error.Code());//Line 557
}
});
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog;
AlertDialog.Builder builder;
final ScrollView scrollView = new ScrollView(this);
final TextView textView = new TextView(this);
switch (id) {
// Other cases are here
case 4:
File playFile = new File(mediaPath, TEMP_WAV_FILE_NAME);
dialog = new FileSaveDialog(this, getResources(),
playFile.getAbsolutePath(), saveDiscardHandler);
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// do whatever you want the back key to do
cleanUp();
}
});
break;
// Other cases are here
default:
dialog = null;
}
return dialog;
}
You must check activity isFinishing() If the activity is finishing, returns true; else returns false.

windowleaked in android view

Hi I have developed android phonegap app and when dialog is shown and screen orientation changes,showing the error in logcat.How to solve this
Here is my logcat error:
E/WindowManager(5759): Activity com.example.Service.NotificationAlert has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#412c93c0 that was originally added here
E/WindowManager(5759): android.view.WindowLeaked: Activity com.example.Service.NotificationAlert has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#412c93c0 that was originally added here
E/WindowManager(5759): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:344)
E/WindowManager(5759): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:267)
E/WindowManager(5759): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:215)
E/WindowManager(5759): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:140)
E/WindowManager(5759): at android.view.Window$LocalWindowManager.addView(Window.java:537)
E/WindowManager(5759): at android.app.Dialog.show(Dialog.java:278)
E/WindowManager(5759): at com.example.Service.NotificationAlert$1.handleMessage(NotificationAlert.java:103)
E/WindowManager(5759): at android.os.Handler.dispatchMessage(Handler.java:99)
E/WindowManager(5759): at android.os.Looper.loop(Looper.java:137)
E/WindowManager(5759): at android.app.ActivityThread.main(ActivityThread.java:4424)
E/WindowManager(5759): at java.lang.reflect.Method.invokeNative(Native Method)
E/WindowManager(5759): at java.lang.reflect.Method.invoke(Method.java:511)
E/WindowManager(5759): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
E/WindowManager(5759): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
E/WindowManager(5759): at dalvik.system.NativeStart.main(Native Method)
Please tell me the solution.Thanks In Advance.
Here is my code:
AlertDialog alertDialog = new AlertDialog.Builder(NotificationAlert.this).create();
alertDialog.setTitle("Mobilyzer");
msgCountBundle = getIntent().getExtras();
messageCount = msgCountBundle.getInt("Count");
userId = msgCountBundle.getInt("userid");
if (messageCount > 1) {
alertDialog
.setMessage("You have " + messageCount + " New Messages");
} else {
alertDialog.setMessage("You have " + messageCount + " New Message");
}
alertDialog.show();
new Timer().schedule(new task(), 30000);
private class task extends TimerTask
{
public void run()
{
toastHandler.sendEmptyMessage(0);
}
}
private final Handler toastHandler = new Handler() {
public void handleMessage(Message msg) {
if(alertDialog.isShowing())
{
try
{
alertDialog.dismiss();
finish();
Log.i("alertdialog","hide alert dialog");
}
catch(IllegalArgumentException e)
{
Log.e("illegal ","illegal exception in dialog"+e);
}
catch(Exception e)
{
Log.e("illegal ","exception in dialog"+e);
}
}
Log.i("alertdialog","show alert dialog");
}
};
In NotificationAlert Activity you are showing a Dialog that was not dismissed by explicitly calling dismiss() on it when Activity was paused. Keep a reference to your Dialog object and in onPause() call dismiss() on it.
#Override
protected void onPause() {
if (myDialog != null) {
myDialog.dismiss();
}
super.onPause();
}
Check the flow of application .In application you are adding dialog more than one time i think.So, try to solve by adding only one dialog in to activity view.
It is because of some other exception the app is crashing and because the dialog is showing the window leak exception is thrown.
Anyways the window leak exception occurs when the dialog is not null and the activity is finished. So the dialog has to be made null either in onPause() as mentioned above or where the activity is moving to a new screen like before starting an intent. Here you can nullify the dailog in the catch so that the window leak exception can be handled, but there is some other exception in your code. Provide the complete logcat.

Categories