getActionBar() returns NULL in actionBar - java

I am currently creating the actionBar in android studio and I have created action buttons and my aim is to have a dropdown menu everytime I click a button.
In my menu_main.xml, I added the items search and help:
<item
android:id="#+id/menu_search"
android:icon="#drawable/ic_action_search"
android:title="#string/menu_search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="collapseActionView|ifRoom"/>
<item android:id="#+id/action_help"
android:icon="#drawable/ic_action_help"
android:title="#string/action_help"
app:showAsAction="ifRoom"/>
In my MainActivity.java, I have added the Strings for my dropdown:
String[] actions = new String[] {
"Bookmark", "Subscribe", "Share", "Like"
};
In my onOptionsItemSelected() method, i have added the case where everytime you click on this button, it will call a function. Here is my code:
#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.
switch (item.getItemId()) {
case R.id.action_help:
helpMessage();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void helpMessage() {
//Toast.makeText(this, "Location button pressed", Toast.LENGTH_SHORT).show();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_dropdown_item, actions);
System.out.println("HERE: " + getActionBar());
getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
ActionBar.OnNavigationListener navigationListener = new ActionBar.OnNavigationListener() {
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
Toast.makeText(getBaseContext(), "You selected : " + actions[itemPosition], Toast.LENGTH_SHORT).show();
return false;
}
};
getActionBar().setListNavigationCallbacks(adapter, navigationListener);
}
When I run the program, my app will crash and I get
NullPointerException: Attempt to invoke virtual method 'void
android.app.ActionBar.setNavigationMode(int)' on a null object
reference
It points to getActionBar() which is NULL.
Any thoughts?

I always have this error....
I found a solution which I put this to my Style it will be work and getActionBar() won't be null anymore...
<item name="android:windowNoTitle">false</item>
<item name="android:windowActionBar">true</item>
Hope this help you

Use getSupportActionBar() instead of getActionBar(). Also theme of your activity should be extended of Theme.AppCompat.

I think you should
1.Check themes
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
</style>
2.Check your Activity class , it's extend AppcombatActivity or ActionBarActivity
So, I hope it useful for you

Related

How to remove the green bar on a android app in android studio

Like the title, I am wondering how to get rid of the green bar at the top so that it matches the background of the activity. I have no idea where to look I've had a look in the manifest and haven't found anything.
What do I do so that it matches the background of the activity?
Note. Different activities have different backgrounds, so is there a way that I just match the activity it is on?
The green bar is called Status bar, and to hide it in activity call below method in onCreate()
void hideStatusBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
getWindow().getDecorView().setSystemUiVisibility(uiOptions);
} else {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
}
And to hide it in a fragment, call it in onCreateView()
void hideStatusBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
requireActivity().getWindow().getDecorView().setSystemUiVisibility(uiOptions);
} else {
requireActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
}
You can change status bar color using this extension function, call this function from Activity just passing the color
fun AppCompatActivity.changeStatusBarColor(#ColorRes color: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.statusBarColor = ContextCompat.getColor(this, color)
}
}
go to following path:
app->res->values->styles
and here in style tag three item tags are available, in that colour of first and last item keep same.
then app status bar and action bar colour display same.
Example:
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here.
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
-->
<item name="colorPrimary">#FFA500</item>
<item name="colorPrimaryDark">#FFA500</item>
</style>

How to use Radio button in menu to change text and background colour of a textview

basically I am trying to create a night mode of white text on black background on radio button click. I would like the radio button to be gray when not clicked and green when clicked/active. I have been able to make the item toast on click but lost from here. I have attached a screenshot below. No idea what to do next. Thanks for your help.
Night mode gray image
Code in Activity
enter code here #Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_text, menu);
return true;
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.item2) {
Toast.makeText(this, "Night mode", Toast.LENGTH_LONG).show();
return true;
}
if (id == R.id.item3) {
Toast.makeText(this, "Fonts", Toast.LENGTH_LONG).show();
return true;
}
if (id == R.id.font1) {
Toast.makeText(this, "Font 1", Toast.LENGTH_LONG).show();
return true;
}
if (id == R.id.font2) {
Toast.makeText(this, "Font 2", Toast.LENGTH_LONG).show();
return true;
}
if (id == R.id.font3) {
Toast.makeText(this, "Font 3", Toast.LENGTH_LONG).show();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Menu xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:title="#string/settings"
app:showAsAction="always">
<menu>
<item android:id="#+id/item2"
android:title="#string/night_mode"
android:icon="#drawable/ic_night"
app:showAsAction="withText" />
<item android:id="#+id/item3"
android:title="#string/font"
app:showAsAction="never" >
<menu>
<item android:id="#+id/font1"
android:title="Times Roman"/>
<item android:id="#+id/font2"
android:title="Vollkorn"/>
<item android:id="#+id/font3"
android:title="Default"/>
</menu>
</item>
</menu>
</item>
</menu>
You can use the official AppCompatDelegate.setDefaultNightMode(MODE) where MODE stands for one of these scenarios:
AppCompatDelegate.MODE_NIGHT_YES
AppCompatDelegate.MODE_NIGHT_NO
AppCompatDelegate.MODE_NIGHT_AUTO
For your project, you will need to switch between MODE_NIGHT_NO and MODE_NIGHT_YES because MODE_NIGHT_AUTO will change the App Theme depending on the time.
When you hit the radio button you have to switch the mode and recreate the activity, calling activity.recreate()
For more information, there is a useful article here: DayNight Theme Android Tutorial with Example

Implement onClick on submenu to start new activity

I'm building an app which has menu item in toolbar, i have created submenu for one menu i.e whose id is 'cloud'. I would like to implement onclick on each submenu when click will open different activity.
Here is the menu.xml file
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_refresh"
app:showAsAction="ifRoom"
android:title="Refresh"
android:icon="#drawable/ic_loop_black_24dp"></item>
<item
android:id="#+id/notes"
app:showAsAction="ifRoom"
android:title="Refresh"
android:icon="#drawable/ic_event_note_black_24dp"></item>
<item
android:id="#+id/cloud"
app:showAsAction="ifRoom"
android:title="Refresh"
android:icon="#drawable/ic_cloud_upload_blackt_24dp">
<menu>
<group
android:checkableBehavior="single">
<item android:id="#+id/imageee"
android:title="Image Upload"
android:orderInCategory="100"
app:showAsAction="ifRoom" />
<item android:id="#+id/pdfff"
android:title="Pdf Upload"
android:orderInCategory="100"
app:showAsAction="never"/>
</group>
</menu>
</item>
</menu>
Here is the Mainactivity file
#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);
mymenu = menu;
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_refresh:
Intent intent = new Intent(MainActivity.this, UpdateService.class);
startService(intent);
}
return true;
case R.id.notes:{
Intent activity_weather = new Intent(this,Physics.class);
startActivity(activity_weather);
}
return true;
case R.id.cloud:{
}
return true;
}
return super.onOptionsItemSelected(item);
}
I looked for answer and tried on my own but I have no idea how to achieve this.
Any help is appreciated.
Thank you in advance.
I have a solution for you:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh:
// TODO:
toast("refresh");
return true;
case R.id.notes:
// TODO:
toast("notes");
return true;
case R.id.imageee:
// TODO: Start your image upload
toast("imageee");
return true;
case R.id.pdfff:
// TODO: Start your PDF upload
toast("pdfff");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void toast(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
I write toast method to show a toast when users click on an item on menu or sub menu. Please remove //TODO: line and add your code for each case there.
I don't think you want to have
android:checkableBehavior="single"
set on your submenu. This behaviour is only useful if you just want to capture the choice (or choices) in the menu item, but not if you actually want to react (ie: do something) when the user selects a submenu item.
Based on your question, it sounds like you want to launch another Activity when the user selects one of these submenu items. To do that just add those menu items to the switch statement in onOptionsItemSelected():
case R.id.imageee:
Intent imageIntent = new Intent(this, Upload.class);
startActivity(imageIntent);
return true;
case R.id.pdfff:
Intent pdfIntent = new Intent(this, Pdf.class);
startActivity(pdfIntent);
return true;
Another interesting solution could be:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent = new Intent();
switch (item.getItemId()) {
case R.id.action_refresh:
intent.setClass(this, UpdateService.class);
break;
case R.id.notes:
intent.setClass(this, Physics.class);
break;
case R.id.cloud:
intent = null;
break
case R.id.imageee:
// TODO set intent class
break;
case R.id.pdfff:
// TODO set intent class
break;
}
// If the selected item is the one that opens the submenu does not try to start the
// activity avoiding throwing null pointer exception and consequently opens the submenu
if (!(intent == null))
startActivity(intent);
return super.onOptionsItemSelected(item);
}
That way you avoid having to have multiple times, in all cases the same call to the method.
startActivity()
Saving lines of code. It is even more advantageous if you decide to add more items to the menu.

Changing options menu icon in bottomNavigationView depending on an open Fragment

Option Menu:
<item
android:id="#+id/home"
android:icon="#drawable/ic_home"
android:title="Home"/>
<item
android:id="#+id/companies"
android:icon="#drawable/ic_companies"
android:title="Companies"/>
<item
android:id="#+id/contact"
android:icon="#drawable/ic_contacts"
android:title="Contact"/>
I want to change this item's icon programmatically depending on the open Fragment and, obviously, have different actions when the user hits this button. I tried several things to do that, but nothing worked.
The last thing I tried was this code in my Fragment onCreateView method:
Menu menu = bottomNavigationView.getMenu();
menu.findItem(R.id.ic_home).setIcon(R.drawable.ic_home_fill);
but its not work for me.
what i tried in selectFragment(MenuItem item)
switch (item.getItemId()) {
case R.id.home:
item.setIcon(R.id.ic_home_fill);
break;
}
I want to change the icon of the bottom navigation of selected position. if user clicked one item then the icon change to another one and when i select another one then 1st icon can set as a default.
refer this link:Android: Bottom Navigation View - change icon of selected item
but it's not work for me
plz give me a other solution.
Thank you
Try this, It worked for me
BottomNavigationView mBottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_nav);
mBottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
invalidateOptionsMenu();
switch (item.getItemId()) {
case R.id.click_to_use:
addHomeFragment(MainActivity.this);
mTitle.setText("Home");
item.setIcon(R.drawable.device);
break;
case R.id.history:
addNotifyFragment(MainActivity.this);
mTitle.setText("History");
item.setIcon(R.drawable.ios_icon);
break;
case R.id.settings:
addSettingFragment(MainActivity.this);
mTitle.setText("Settings");
break;
}
return true;
}
});
after any modification in the menu, you would have to make an "Invalidateoptionsmenu ()" in the action. I invite you to want to test this feature . see here

Action bar option action

Before Clicking:
After Clicking:
I am having an issue with my code where clicking on an actionbar action will bring up the title of the action. If you then click on the title that is how you get to the onclick listener. Very strange... I know it is hard to tell without code but I am away and will post it soon. Just wanted to ask around to see if anyone has experienced similar.
ActionBar:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_settings"
android:title="#string/hello1"
app:showAsAction="never"/>
</menu>
onClickListener:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_settings:
onCreateDialog();
return true;
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public void onCreateDialog() {
String[] string= new String[]{"Add to Calendar", "Share"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Options")
.setItems(string, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:...................}
This is the expected behavior for the way you have the menu setup currently.
<item
android:id="#+id/action_settings"
android:title="#string/hello1"
app:showAsAction="never"/> <!-- Don't show this action until the overflow menu is shown -->
With the showAsAction set to never, the action is not shown until the overflow menu is shown. The available options for showAsAction are:
["ifRoom" | "never" | "withText" | "always" | "collapseActionView"]
In your case, because you only have one menu item, you can use always.
Refer to the menu resource documentation for more info.
You should be able to preview this in Android Studio (see screenshot below)
I fixed it by extending the activity to appcompatactivity instead of activity. Weird bug. Then it didn't do it.

Categories