Action bar home button crashes while back button works - java

I'm completely stumped on this one. I have an activity C, when I try and press the back button, it works. But when I use the home/up button in the action bar it just crashes with (see the following error). Here are the parts of my code which deal with the back/up buttons.
Activity C:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_offline_viewer);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
if(!isOnline) {
menu.removeItem(R.id.saveRoute);
}
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.offline_viewer, menu);
return true;
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
//Get names for saving
String[] startParts = onlineFrom.split(",");
String startName = startParts[0] + "," + startParts[1];
String[] endParts = onlineTo.split(",");
String endName = endParts[0] + "," + endParts[1];
System.out.println(item.getItemId());
switch(item.getItemId()){
//Save xml file or route once pressed
case R.id.saveRoute:
//TODO:Uncomment once server is ready
new DownloadFileFromURL(this, startName, endName).execute(urlForDownload);
return true;
case android.R.id.home:
System.out.println(item.getItemId());
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
Error:
08-22 16:15:43.629: W/dalvikvm(4908): threadid=1: thread exiting with uncaught exception (group=0x41c7e888)
08-22 16:15:43.634: E/AndroidRuntime(4908): FATAL EXCEPTION: main
08-22 16:15:43.634: E/AndroidRuntime(4908): java.lang.NullPointerException
08-22 16:15:43.634: E/AndroidRuntime(4908): at com.example.otpxmlgetter.OfflineViewer.onOptionsItemSelected(OfflineViewer.java:185)
08-22 16:15:43.634: E/AndroidRuntime(4908): at android.app.Activity.onMenuItemSelected(Activity.java:2590)
08-22 16:15:43.634: E/AndroidRuntime(4908): at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:361)
08-22 16:15:43.634: E/AndroidRuntime(4908): at com.android.internal.widget.ActionBarView$3.onClick(ActionBarView.java:167)
08-22 16:15:43.634: E/AndroidRuntime(4908): at android.view.View.performClick(View.java:4204)
08-22 16:15:43.634: E/AndroidRuntime(4908): at android.view.View$PerformClick.run(View.java:17354)
08-22 16:15:43.634: E/AndroidRuntime(4908): at android.os.Handler.handleCallback(Handler.java:725)
08-22 16:15:43.634: E/AndroidRuntime(4908): at android.os.Handler.dispatchMessage(Handler.java:92)
08-22 16:15:43.634: E/AndroidRuntime(4908): at android.os.Looper.loop(Looper.java:137)
08-22 16:15:43.634: E/AndroidRuntime(4908): at android.app.ActivityThread.main(ActivityThread.java:5232)
08-22 16:15:43.634: E/AndroidRuntime(4908): at java.lang.reflect.Method.invokeNative(Native Method)
08-22 16:15:43.634: E/AndroidRuntime(4908): at java.lang.reflect.Method.invoke(Method.java:511)
08-22 16:15:43.634: E/AndroidRuntime(4908): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
08-22 16:15:43.634: E/AndroidRuntime(4908): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:561)
08-22 16:15:43.634: E/AndroidRuntime(4908): at dalvik.system.NativeStart.main(Native Method)
Does this have something to do with the fact that there are two possible ways to get to Activity C? Either A->B->C or A->D->C?
The fact that the back button still works completely confounds me.

It is commonly not recommended to call Activity life cyle methods. The onWhatEver methods are used by the framework. If you want to finish the activity rather use ...
this.finish()
or ...
getActivity.finish()
if you are in a fragment context.
p.s.s: onBackPressed does actually work (against initial asumption of this answer). See comments below for the root cause of this issue.
p.s.: this post proposes this.dispatchKeyEvent(new Keyevent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK)); as an alternative

Related

can't get menuitem on android 4.1, it crashes

I have code, that gets Menu Item and changes icon color. on Android 8.1 it's working fine, but when I tested it on android 4.1.1, app crashes.
Drawable drawable = menuos.getItem(1).getIcon();
if(drawable != null) {
drawable.mutate();
drawable.setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP);
}
Menuos:
Menu menuos = menu
It is located in onCreateOptionsMenu
Logcat:
07-28 11:20:15.794 3443-3443/com.developerfromjokela.edison E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.developerfromjokela.edison.MainActivity$5.onPageStarted(MainActivity.java:223)
at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:318)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
onCreateOptionsMenu:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
menuos = menu;
return super.onCreateOptionsMenu(menu);
}
If this is the line that throws NPE:
Drawable drawable = menuos.getItem(1).getIcon();
then there are 2 options:
menuos is null or menuos.getItem(1) is null
so do this before the above line:
Log.i("menuos_isnull", menuos == null);
if (menuos != null) {
Log.i("Item1_isnull", menuos.getItem(1) == null);
}
and see what'rs printed.
This is debugging and you must use it more often.

Cant start a dialog activity from a button in another activity

I am trying to start a new activity as a Dialog Activity putting a Intent on a button from another activity. Whenever I try and press the button, the activity unfotunately closes.
Main Activity.java
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button ab = (Button) findViewById(R.id.button1);
ab.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this, NewDialog.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void side(View view){
android.support.v4.app.FragmentManager fm1 = getSupportFragmentManager();
NewDialog newdialog = new NewDialog();
newdialog.show(fm1, "SideDialog");
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
}
NewDialog.java
public class NewDialog extends DialogFragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
final View view = inflater.inflate(R.layout.activity_new_dialog, container);
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
return view;
}
}
Added Logcat:
05-29 22:37:36.472: D/dalvikvm(26806): Late-enabling CheckJNI
05-29 22:37:36.762: D/ActivityThread(26806): setTargetHeapUtilization:0.25
05-29 22:37:36.762: D/ActivityThread(26806): setTargetHeapIdealFree:8388608
05-29 22:37:36.762: D/ActivityThread(26806): setTargetHeapConcurrentStart:2097152
05-29 22:37:39.172: D/libEGL(26806): loaded /system/lib/egl/libEGL_adreno200.so
05-29 22:37:39.222: D/libEGL(26806): loaded /system/lib/egl/libGLESv1_CM_adreno200.so
05-29 22:37:39.322: D/libEGL(26806): loaded /system/lib/egl/libGLESv2_adreno200.so
05-29 22:37:39.362: I/Adreno200-EGL(26806): <qeglDrvAPI_eglInitialize:299>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_JB_REL_2.0.3.1_RB1.04.01.01.45.000_msm8625_JB_REL_2.0.3.1_Merge_release_AU (Merge)
05-29 22:37:39.362: I/Adreno200-EGL(26806): Build Date: 03/28/13 Thu
05-29 22:37:39.362: I/Adreno200-EGL(26806): Local Branch:
05-29 22:37:39.362: I/Adreno200-EGL(26806): Remote Branch: m/jb_rel_2.0.3.1
05-29 22:37:39.362: I/Adreno200-EGL(26806): Local Patches: NONE
05-29 22:37:39.362: I/Adreno200-EGL(26806): Reconstruct Branch: NOTHING
05-29 22:37:39.452: D/OpenGLRenderer(26806): Enabling debug mode 0
05-29 22:37:43.822: D/AndroidRuntime(26806): Shutting down VM
05-29 22:37:43.822: W/dalvikvm(26806): threadid=1: thread exiting with uncaught exception (group=0x40fd4438)
05-29 22:37:44.022: E/AndroidRuntime(26806): FATAL EXCEPTION: main
05-29 22:37:44.022: E/AndroidRuntime(26806): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.createdialog/com.example.createdialog.NewDialog}: java.lang.ClassCastException: com.example.createdialog.NewDialog cannot be cast to android.app.Activity
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2038)
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2139)
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.app.ActivityThread.access$700(ActivityThread.java:143)
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1241)
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.os.Handler.dispatchMessage(Handler.java:99)
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.os.Looper.loop(Looper.java:137)
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.app.ActivityThread.main(ActivityThread.java:4963)
05-29 22:37:44.022: E/AndroidRuntime(26806): at java.lang.reflect.Method.invokeNative(Native Method)
05-29 22:37:44.022: E/AndroidRuntime(26806): at java.lang.reflect.Method.invoke(Method.java:511)
05-29 22:37:44.022: E/AndroidRuntime(26806): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
05-29 22:37:44.022: E/AndroidRuntime(26806): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
05-29 22:37:44.022: E/AndroidRuntime(26806): at dalvik.system.NativeStart.main(Native Method)
05-29 22:37:44.022: E/AndroidRuntime(26806): Caused by: java.lang.ClassCastException: com.example.createdialog.NewDialog cannot be cast to android.app.Activity
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.app.Instrumentation.newActivity(Instrumentation.java:1068)
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2029)
05-29 22:37:44.022: E/AndroidRuntime(26806): ... 11 more
I might be wrong here, but as far as I know, you can't start an Intent passing a DialogFragment, you should pass an Activity. Here's what's wrong:
Intent intent = new Intent(MainActivity.this, NewDialog.class);
startActivity(intent);
Since NewDialog is declared as a DialogFragment and not as an Activity subclass.
If what you are trying to do is show the dialog, then you should do:
NewDialog dialog = NewDialog();
// use getSupportFragmentManager() if using support fragments instead of native fragments, or
// use getChildFragmentManager() if this code is inside a fragment rather than an activity
dialog.show(getFragmentManager(), "pass-any-string-here");
Without a logcat stacktrace to look at, I am assuming that your issue has to do with variable scope (here is an example explanation on the topic).
What you need to do is declare your button as a class level variable because right now it is a method variable and as such ceases to exist once your onCreate method has finished executing.
public class MainActivity extends FragmentActivity {
private Button myButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myButton = (Button) findViewById(R.id.button1);
myButton.setOnClickListener(...);
...
}
}

code with thread crashes at startup (android beginner)

I am trying to make an application that passes through the audio samples obtained at the microphone to the speaker. This is the source code:
public class MainActivity extends Activity {
AudioManager am = null;
AudioRecord record =null;
AudioTrack track =null;
final int SAMPLE_FREQUENCY = 44100;
final int SIZE_OF_RECORD_ARRAY = 1024;
boolean isPlaying = false;
class MyThread extends Thread{
#Override
public void run(){
recordAndPlay();
}
}
MyThread newThread;
private void init() {
int min = AudioRecord.getMinBufferSize(SAMPLE_FREQUENCY, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
record = new AudioRecord(MediaRecorder.AudioSource.VOICE_COMMUNICATION, SAMPLE_FREQUENCY, AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT, min);
int maxJitter = AudioTrack.getMinBufferSize(SAMPLE_FREQUENCY, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
track = new AudioTrack(AudioManager.MODE_IN_COMMUNICATION, SAMPLE_FREQUENCY, AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT, maxJitter, AudioTrack.MODE_STREAM);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
init();
newThread.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void recordAndPlay() {
short[] lin = new short[SIZE_OF_RECORD_ARRAY];
int num = 0;
am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
am.setMode(AudioManager.MODE_IN_COMMUNICATION);
record.startRecording();
track.play();
while (true) {
num = record.read(lin, 0, SIZE_OF_RECORD_ARRAY);
track.write(lin, 0, num);
}
}
public void passStop(View view){
Button playBtn = (Button) findViewById(R.id.playBtn);
// /*
if(!isPlaying){
record.startRecording();
track.play();
isPlaying = true;
playBtn.setText("Pause");
}
if(isPlaying){
record.stop();
track.pause();
isPlaying=false;
playBtn.setText("Pass through");
}
// */
}
#SuppressWarnings("deprecation")
#Override
public void onDestroy(){
newThread.stop();
}
}
Unfortunately, this program stops as soon as I try to run it through eclipse. This is wht I get in the logcat but I am not sure what it all means:
08-19 18:58:43.365: D/AndroidRuntime(27915): Shutting down VM
08-19 18:58:43.365: W/dalvikvm(27915): threadid=1: thread exiting with uncaught exception (group=0x4161f700)
08-19 18:58:43.365: E/AndroidRuntime(27915): FATAL EXCEPTION: main
08-19 18:58:43.365: E/AndroidRuntime(27915): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mypassthrough/com.example.mypassthrough.MainActivity}: java.lang.NullPointerException
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.os.Handler.dispatchMessage(Handler.java:99)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.os.Looper.loop(Looper.java:137)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.ActivityThread.main(ActivityThread.java:5103)
08-19 18:58:43.365: E/AndroidRuntime(27915): at java.lang.reflect.Method.invokeNative(Native Method)
08-19 18:58:43.365: E/AndroidRuntime(27915): at java.lang.reflect.Method.invoke(Method.java:525)
08-19 18:58:43.365: E/AndroidRuntime(27915): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
08-19 18:58:43.365: E/AndroidRuntime(27915): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-19 18:58:43.365: E/AndroidRuntime(27915): at dalvik.system.NativeStart.main(Native Method)
08-19 18:58:43.365: E/AndroidRuntime(27915): Caused by: java.lang.NullPointerException
08-19 18:58:43.365: E/AndroidRuntime(27915): at com.example.mypassthrough.MainActivity.onCreate(MainActivity.java:46)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.Activity.performCreate(Activity.java:5133)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
08-19 18:58:43.365: E/AndroidRuntime(27915): ... 11 more
What could be the reason for this code crashing, and how can it be debugged? I am pretty sure it has something to do with Thread, because my other versions of this code where I have not included Thread at all do not crash on startup.
Variable newThread is not initialized in oncreate() method that's why it is giving nullpointer exception
add this in your init() method it will work
newThread=new Thread();
You are getting a null pointer exception because newThread has not been initialized yet and it is null when you try to start it. The thread doesn't have anything to do also. You should look at implementing a runnable, handler, and timer into your activity instead of a thread.
Use sub class with extending AsyncTask Class
class TestActivity extends AsyncTask <String, Void, String > {
protected String doInBackground(String... urls) {
// execution
}
protected void onPostExecute(String result) {
// post execution
}
protected void onPreExecute() {
super.onPreExecute();
// initial activities
}
}

activity crashes when going back home

I have an edit task activity with a single edittext view. When i click the back button on the action bar, the database is updated and the log even registers it, but the activity crashes while going back. The main activity does display the text that was added in the task activity.
Here is the code for the home button:
public class NewTask extends Activity {
protected TaskerDbHelper db;
MyAdapter adapt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_task);
db = new TaskerDbHelper(this);
setupActionBar();
}
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.new_task, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
EditText t = (EditText) findViewById(R.id.editText1);
String s = t.getText().toString();
if (s.equalsIgnoreCase("")) {
Toast.makeText(this, "enter the task description first!!",
Toast.LENGTH_LONG);
} else {
Task task = new Task(s, 0);
db.addTask(task);
Log.d("tasker", "data added");
//t.setText("");
//adapt.add(task);
adapt.notifyDataSetChanged();
}
setResult(RESULT_OK);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Whats wrong?
Here is the log:
08-16 17:56:05.117: E/AndroidRuntime(6162): FATAL EXCEPTION: main
08-16 17:56:05.117: E/AndroidRuntime(6162): java.lang.NullPointerException
08-16 17:56:05.117: E/AndroidRuntime(6162): at com.example.tasker.NewTask.onOptionsItemSelected(NewTask.java:62)
08-16 17:56:05.117: E/AndroidRuntime(6162): at android.app.Activity.onMenuItemSelected(Activity.java:2552)
08-16 17:56:05.117: E/AndroidRuntime(6162): at com.android.internal.widget.ActionBarView$3.onClick(ActionBarView.java:167)
08-16 17:56:05.117: E/AndroidRuntime(6162): at android.view.View.performClick(View.java:4204)
08-16 17:56:05.117: E/AndroidRuntime(6162): at android.view.View$PerformClick.run(View.java:17355)
08-16 17:56:05.117: E/AndroidRuntime(6162): at android.os.Handler.handleCallback(Handler.java:725)
08-16 17:56:05.117: E/AndroidRuntime(6162): at android.os.Handler.dispatchMessage(Handler.java:92)
08-16 17:56:05.117: E/AndroidRuntime(6162): at android.os.Looper.loop(Looper.java:137)
08-16 17:56:05.117: E/AndroidRuntime(6162): at android.app.ActivityThread.main(ActivityThread.java:5234)
08-16 17:56:05.117: E/AndroidRuntime(6162): at java.lang.reflect.Method.invokeNative(Native Method)
08-16 17:56:05.117: E/AndroidRuntime(6162): at java.lang.reflect.Method.invoke(Method.java:525)
08-16 17:56:05.117: E/AndroidRuntime(6162): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:799)
08-16 17:56:05.117: E/AndroidRuntime(6162): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
08-16 17:56:05.117: E/AndroidRuntime(6162): at dalvik.system.NativeStart.main(Native Method)
Try checking if the adapter is null first
if(adapt != null) {
adapt.notifyDataSetChanged();
} else {
// Initialize and do other stuff with it
}
And in the declaration, declare adapt like this
public MyAdapter adapt;
I can see that your using a custom adapter class. I think the problem may also be there in the notifyDataSetChanged() method. Can you post it?
if(adapt != null) {
adapt.notifyDataSetChanged();
} else {
adapt = new Adapter();
listview.setAdapter(adapt);
}
check the answer from Noah. he is overriding the notify() to access the BaseAdapter
https://stackoverflow.com/a/5327197/2074990

Show menu in android on startup

Is there any way to automatically show the menu when an activity starts as it's a list activity which will be blank when it starts for the first time.
Check Following link, It explain how to open and close option menu progamatically
http://kahdev.wordpress.com/2010/03/15/progamatically-open-and-close-an-activitys-option-menu/
I played around with this one and it didn't matter if I put it in onCreate, onStart, onResume, onPostResume it always threw (physical Galaxy S4 # 4.4.2 and Genymotion Galaxy S2 # 2.3.7):
10-23 12:50:22.389 27702-27702/net.twisterrob.debug D/AndroidRuntime﹕ Shutting down VM
10-23 12:50:22.389 27702-27702/net.twisterrob.debug W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x418e3da0)
10-23 12:50:22.389 27702-27702/net.twisterrob.debug E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: net.twisterrob.debug, PID: 27702
java.lang.RuntimeException: Unable to start activity ComponentInfo{net.twisterrob.debug/net.twisterrob.android.MyActivity}: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
...
Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:751)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:278)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at com.android.internal.policy.impl.PhoneWindow.openPanel(PhoneWindow.java:746)
at com.android.internal.policy.impl.PhoneWindow.openPanel(PhoneWindow.java:621)
at android.app.Activity.openOptionsMenu(Activity.java:2960)
at net.twisterrob.android.MyActivity.onCreate(MyActivity.java:35)
at android.app.Activity.performCreate(Activity.java:5426)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
...
The final solution that worked is:
#Override public void onAttachedToWindow() {
super.onAttachedToWindow();
openOptionsMenu();
}
After the activity has resumed and !isFinishing() it is safe to use openOptionsMenu in any event handler or AsyncTask.onPostExecute.
All you have to do is call either on of these in a listener and you can open or close the menu no problem.
openOptionsMenu();
closeOptionsMenu();
So call it in onCreate.
public class List extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
openOptionsMenu();
}
// Menu Button Stuff
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
MenuInflater Menu = getMenuInflater();
Menu.inflate(R.menu.menu_layout, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.menuBack:
finish();
return true;
}
return false;
}
}

Categories