OpenOptionMenu from ImageButton gives null pointer exception - android

I am trying to invoke optionMenu from ImageButton in onClick listener but getting following exception.
07-19 01:08:09.693: E/AndroidRuntime(15133): java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.Menu.getItem(int)' on a null object reference
public class myApp extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
}
/** Called when the activity is first created. */
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);
menu_icon = (ImageView) findViewById(R.id.icon);
infoBtn = (ImageButton) findViewById(R.id.pfkey_button);
menu_icon.setImageResource(R.drawable.info_icon);
menu_icon.setOnClickListener(this);
infoBtn.setOnClickListener(this);
//Create Terminal View
terminalView = (TerminalView)findViewById(R.id.terminalView);//new TerminalView(this);
registerForContextMenu(terminalView);
}
public void onClick(View v) {
KeyEvent event = null;
if (v == infoBtn) {
openOptionsMenu();
}
if (v == menu_icon) {
openOptionsMenu();
}
}
}
I also tried with `infoBtn = (ImageButton)myApp.this.findViewById(R.id.pfkey_button); but not working

I don't know why you overrided onPostCreate,I think you shold do those things in onCreate.
Apart from this, openOptionsMenu not work in my app.
So I use a ToolBar to replace the ActionBar.Here is the code:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mToolbar.showOverflowMenu();
}
});
}
// override this method to inflat the menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "onOptionsItemSelected: "+item.getTitle().toString());
return super.onOptionsItemSelected(item);
}
}

Make sure to inflate your menu first inside onCreateOptionsMenu()
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the navigation_menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.your_menu, menu);
return true;
}
It is possible that your menu itself is not inflated, thus causing the exception. Please provide the full code if this is not the case

here it was crashing although implementation is correct.
#Override
public boolean onMenuOpened(int featureId, Menu menu) {
/*if (!hostcom.isConnected())
menu.getItem(0).setTitle("Login");
else
menu.getItem(0).setTitle("Logout");*/
return true;
}

Related

actionbar upnavigation from fragmentB to fragmentA

I'm trying to build with only fragments.
The App opens with a Activity blank that only has a ActionBar upon clicking the hamburger icon it opens a drawer that give you a menu option.
Upon clicking on one of the Menu Items it opens the First Fragment which has a Recycler/Card View. Upon clicking one of the Cards it opens a new fragment with more details of the selected cards.
Now the problem is the detail fragment shows home icon cause I enable setDisplayHomeAsUpEnabled(true) but when I click on the back arrow it does not do anything. The hardware back button does take me back to the previous (Recycler/Card View) fragment.
I also have setHasOptionsMenu(true) in the detail fragment.
I put log tags everywhere to see when the home button reacts but nothing.
Hope someone can give me a hand.
Activity:
public class AppStart extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
ActionBarDrawerToggle actionBarDrawerToggle;
final String TAG = "AppSart: onBackPressed";
final String TAG1 = "AppSart: resetActionBar";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_start);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
public void onBackPressed() {
int stack = getSupportFragmentManager().getBackStackEntryCount();
Log.d(TAG,Integer.toString(stack));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return false;
}
public void resetActionBar(boolean childAction)
{
Log.d(TAG1,Boolean.toString(childAction));
if (childAction) {
actionBarDrawerToggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} else {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
}
}
}
Recycler Fragment:
public class ProductFragment extends Fragment {
final String TAG1 = "ProdFrag: onCreate";
final String TAG2 = "ProdFrag: onCreateView";
final String TAG3 = "ProdFrag: onResume";
final String TAG6 = "ProdFrag: ActionSetting";
final String TAG7 = "ProdFrag: home";
public ProductFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
int stack = getActivity().getSupportFragmentManager().getBackStackEntryCount();
Log.d(TAG1,Integer.toString(stack));
boolean canback = stack>0;
((AppStart)getActivity()).resetActionBar(canback);
}
#Override
public void onResume() {
super.onResume();
int stack = getActivity().getSupportFragmentManager().getBackStackEntryCount();
Log.d(TAG3,Integer.toString(stack));
boolean canback = stack>0;
((AppStart)getActivity()).resetActionBar(canback);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.fragment_product,container,false);
int stack = getActivity().getSupportFragmentManager().getBackStackEntryCount();
Log.d(TAG2,Integer.toString(stack));
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.toolbar_menu, menu);
super.onCreateOptionsMenu(menu,inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int stack = getActivity().getSupportFragmentManager().getBackStackEntryCount();
switch (item.getItemId()) {
case R.id.action_settings:
Log.d(TAG6,Integer.toString(stack));
return true;
default:
break;
}
return false;
}
}
Detail Fragment:
public class ProductTabsFragment extends Fragment {
final String TAG1 = "TabFrag: onCreate";
final String TAG2 = "TabFrag: onResume";
final String TAG3 = "TabFrag: ActionSettings";
final String TAG4 = "TabFrag: home";
final String TAG5 = "TabFrag: onBckStkChng";
final String TAG6 = "TabFrag: onNavigateUp";
public ProductTabsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
int stack = getActivity().getSupportFragmentManager().getBackStackEntryCount();
Log.d(TAG1,Integer.toString(stack));
boolean canback = stack>0;
((AppStart)getActivity()).resetActionBar(canback);
}
#Override
public void onResume() {
super.onResume();
int stack = getActivity().getSupportFragmentManager().getBackStackEntryCount();
Log.d(TAG2,Integer.toString(stack));
boolean canback = stack>0;
((AppStart)getActivity()).resetActionBar(canback);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_product_tabs, container, false);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.toolbar_menu, menu);
super.onCreateOptionsMenu(menu,inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int stack = getActivity().getSupportFragmentManager().getBackStackEntryCount();
switch (item.getItemId()) {
case R.id.action_settings:
Log.d(TAG3,Integer.toString(stack));
return true;
case android.R.id.home:
Log.d(TAG4,Integer.toString(stack));
//getActivity().onBackPressed();
return true;
default:
break;
}
return false;
}
}
Also this is the code in the recycler adapter for when a card is click to load the detail Fragment:
cvProduct.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
ProductTabsFragment productTabsFragment = new ProductTabsFragment();
AppCompatActivity activity = (AppCompatActivity) view.getContext();
FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container,productTabsFragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
For those who might have this problem. Turns out that when ActionBarDrawerToggle is used setToolbarNavigationClickListener needs to be used for the backarrow.
The R.id.home in optionitemselected seems to be disabled. Hope this helps!
so what I did was remove from the onOptionsItemSelected(MenuItem item):
case android.R.id.home:
Log.d(TAG4,Integer.toString(stack));
return true;
and modified resetActionBar(boolean childAction) in the main Activity which is called in the oncreate of fragmentA and fragmentB.
public void resetActionBar(boolean childAction)
{
Log.d(TAG1,Boolean.toString(childAction));
if (childAction) {
actionBarDrawerToggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
actionBarDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Log.d(TAG4,"Clicked");
onBackPressed();
}
});
} else {
getSupportActionBar().setHomeButtonEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
}
}

android some times menu does not show up

I am using options menu in message fragment where I can add friends from menu. I can navigate to this fragment from activity or fragment. When I launch this message fragment, menu is working fine. When I do navigate through other screen and come to message fragment menu disappears. After using/navigating in the application for 4-5 minutes, menu starts behaving randomly.
Strange behavior is, when I do launch message fragment from activity, menu always works well. This behaves randomly when I launch it from fragment.
Here is my code
public class MessagesFragment extends BaseFragment{
private static final String TAG = MessagesFragment.class.getSimpleName();
Context mContext;
View mView;
private ListView listBuddy;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mContext = activity;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
((InnerActivity)getActivity()).setActionbarTitle(getResources().getString(R.string.my_buddies));
View v = inflater.inflate(R.layout.fragment_messages, container, false);
listBuddy = (ListView) v.findViewById(R.id.listViewFindBuddy);
this.mView = v;
return v;
}
#Override
public void onDetach() {
// TODO Auto-generated method stub
super.onDetach();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
#Override
public void onStop() {
// TODO Auto-generated method stub
super.onStop();
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
// TODO Auto-generated method stub
super.setUserVisibleHint(isVisibleToUser);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.messages, menu);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_add:
break;
}
return super.onOptionsItemSelected(item);
}
Activity
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
add the following code in your activity :
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

saving the edittext value to another activity on click of save actionbutton in android

how to save the text given to edit text, after clicking the save action button in action bar that should save to another activity.
my first activity Add.java
public class Add extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
getActionBar().setDisplayShowHomeEnabled(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflate=getMenuInflater();
getMenuInflater().inflate(R.menu.activity_add_action, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save:save();
return true;
case R.id.cancel:cancelnavi();
return true;
}
return super.onOptionsItemSelected(item);
}
private void save() {
EditText titlename;
titlename=(EditText)findViewById(R.id.edittitle);
String title=titlename.getText().toString();
if (title.equalsIgnoreCase("")){
Toast.makeText(Add.this, "Script title should not be empty", Toast.LENGTH_LONG).show();
} else {
Intent i;
i=new Intent(getApplicationContext(), Scripts.class);
i.putExtra("n", titlename.getText().toString());
startActivityForResult(i, 0);
titlename.setText("");
}
}
}
It should be saved to scripts.java
public class Scripts extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scripts);
getActionBar().setDisplayShowHomeEnabled(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflate=getMenuInflater();
getMenuInflater().inflate(R.menu.activity_main_actions, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_edit:editscript();
break;
}
return true;
}
private void editscript() {
Intent editinIntent;
editinIntent=new Intent(Scripts.this, Edit.class);
startActivity(editinIntent);
}
}
Maybe this can help you.
public class Scripts extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scripts);
getActionBar().setDisplayShowHomeEnabled(false);
//Extract the data
String yourTitle = getIntent().getStringExtra("n");
}
}

why is onCreate() of the previous activity called when the next activity is finished?

I have an activity, say MainActivity that has just onCreate method (no onResume, onStop, etc)
when a contBut is clicked, another activity, say SecondActivity is started and with pressing exitBut, we navigate back to MainActivity. in this case, onCreate of MainActivity is recalled which I can't figure why. I expect it to resume the activity, or at least not to call onCreate.
here is the code for MainActivity:
public class MainActivity extends Activity {
private Button contBut;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contBut = (Button) findViewById(R.id.cont);
contBut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("d", "in count onclick");
Intent intent = new Intent(MainActivity.this, ContActivity.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
here is the code for SecondActivity:
public class SecondActivity extends Activity{
private Button exitBut;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cont);
exitBut = (Button) findViewById(R.id.exit);
exitBut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
problem solved.
in the developer options section of my device, "Don't keep activities" was checked.

How can I click an Android Action Bar item under program control?

PeterH posted the following code:
//initiate the button
button.performClick();
button.setPressed(true);
button.invalidate();
// delay completion till animation completes
button.postDelayed(new Runnable() { //delay button
public void run() {
button.setPressed(false);
button.invalidate();
//any other associated action
}
}, 800); // .8secs delay time
Can the same type of operation be performed for Action Bar items?
Well, you can save MenuItem as a field and then call onOptionsItemSelected(savedMenuItem). But as ActionBar items are MenuItems and not Buttons (of course, if your action bar isn't customized with view like http://www.vogella.com/articles/AndroidActionBar/article.html#actionbar_dynamic). But if your ActionBar is customized with view and that view has a Button, that Button's behaviour can be customized as considered in your code snippet.
Example:
public class MainActivity extends Activity {
MenuItem item;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getActionBar();
actionBar.setSubtitle("mytest");
actionBar.setTitle("TESTESTEST");
TextView tView = (TextView) findViewById(R.id.textView1);
tView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
onOptionsItemSelected(item);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_settings) {
this.item = item;
Toast.makeText(this, "settings", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
}

Categories

Resources