I am trying to set up my Navigation Drawer listener for my MainScreen activity. When I set everything up, my app crashes when I try use ActionBarDrawerToggle. Are there other ways of implementing this?
Unable to start activity ComponentInfo{koeksworld.com.firstandroidproject/koeksworld.com.firstandroidproject.UserMainPanel}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.setDrawerListener(android.support.v4.widget.DrawerLayout$DrawerListener)' on a null object reference
Here is some of the code in my activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_main_panel);
listener = new NavigationDrawerItemListener(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.groceryAppHomeToolbar);
homeDrawer = (DrawerLayout) findViewById(R.id.mainDrawerLayout);
homeListView = (ListView) findViewById(R.id.homeListView);
homeListView.setBackgroundColor(getResources().getColor(R.color.colorBlue));
navigationArray = getResources().getStringArray(R.array.navigationArray);
navigationAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,
navigationArray);
homeListView.setAdapter(navigationAdapter);
homeListView.setOnItemClickListener(listener);
//The suspected culprit
drawerListener = new ActionBarDrawerToggle(this, homeDrawer, toolbar, R
.string
.open_drawer, R
.string.close_Drawer);
homeDrawer.setDrawerListener(drawerListener);
drawerListener.syncState();
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
Make sure you are using the same id for the navigation drawer in findViewById(R.id.mainDrawerLayout) and in the layout file.
Seems mDrawerLayout is null when calling .setDrawerListener()
Related
I want to show an ActionBar in my Activity while only showing a closing symbol. Therefore I used the method getSupportActionBar():
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close);
setTitle("Add Event");
But it throws a NullPointerExeption because apparently there's no ActionBar to call:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tutorial/com.example.tutorial.AddEventActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setHomeAsUpIndicator(int)' on a null object reference
In my MainActivity I implemented a Drawer Navigation where I already used a toolbar that works:
public class MainActivity extends AppCompatActivity {
protected DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nvDrawer;
// Make sure to be using androidx.appcompat.app.ActionBarDrawerToggle version.
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set a Toolbar to replace the ActionBar.
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// This will display an Up icon (<-), we will replace it with hamburger later
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Find our drawer view
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = setupDrawerToggle();
// Setup toggle to display hamburger icon with nice animation
drawerToggle.setDrawerIndicatorEnabled(true);
drawerToggle.syncState();
// Tie DrawerLayout events to the ActionBarToggle
mDrawer.addDrawerListener(drawerToggle);
// Find our drawer view
nvDrawer = (NavigationView) findViewById(R.id.nvView);
// Setup drawer view
setupDrawerContent(nvDrawer);
}
How do I fix that?
Thanks in advance!
Replace this line :
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
with this line :
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
This should solve your problem.
You may try to add following attribute to your MainActivity item under your ActivityManifest.xml
android:theme="#style/Theme.AppCompat.Light.DarkActionBar"
Then try to access it with the getSupportActionBar(). With this way you can choose the activities that you don't or do want to include actionbars by using relevant themes. For example:
<activity
android:name=".SecondActivity"
android:theme="#style/Theme.AppCompat.Light.DarkActionBar"
android:parentActivityName=".MainActivity" />
I have an app that connects my activities with a navigation drawer.The problem is that some activities load more difficult than others(when i press the icon on drawer,instead of opens the activity immediately,it stays for 1-2 seconds and then loads the activity). It might be a dummy question but is it possible if you could give me some advice on how to fix it?Here is one of the activities that load more difficult
public class ImportAPI extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
public TextView fullnameside, emailside;
public static String stravaToken;
public ImageButton btnStrava;
public ImageView tickStrava;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.importapi);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar.setTitle("");
toolbar.setSubtitle("");
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
View headerView = navigationView.getHeaderView(0);
fullnameside = (TextView) headerView.findViewById(R.id.fullnameside);
emailside = (TextView) headerView.findViewById(R.id.emailside);
fullnameside.setText(""+GetInfo.fullname);
emailside.setText(""+GetInfo.email);
navigationView.setNavigationItemSelectedListener(this);
navigationView.getMenu().getItem(3).setChecked(true);
//STRAVA
tickStrava=(ImageView) findViewById(R.id.tickStrava);
btnStrava=(ImageButton) findViewById(R.id.stravaBtn);
connectStrava();
}
public void connectStrava(){
btnStrava.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent getStravaApi= new Intent(ImportAPI.this,StravaSetupApi.class);
startActivity(getStravaApi);
}
});
//GET ACCESS TOKEN FROM STRAVAS AUTHORIZE ACCOUNT
String accessToken = StravaAuthenticateActivity.getStravaAccessToken(this);
stravaToken=accessToken; //make static var so i can use it anywhere i want
//Get athletes activities from GetStravaAthleteActivities.java
new GetStravaAthleteActivities.AthleteActivities();
//check if token is null so i can display the tick and also disable the button press
if(stravaToken!=null)
{
btnStrava.setEnabled(false);
tickStrava.setVisibility(View.VISIBLE);
}
else {
tickStrava.setVisibility(View.INVISIBLE);
}
}
Try checking whether it's the Activity's fault and not the drawer menu's. You could time your onnectStrava() method, which could be causing the delay. Add log messages at the beginning and the end of the method.
public void connectStrava(){
Log.d(“TAG”, “STRAVA Entry point);
…
Log.d(“TAG”, “STRAVA Exit point);
}
then check the timestamps on your IDE Logcat and see how long it takes for the method to run. if it's indeed 1-2 seconds, then you know what causes the delay. If that's the case you could try to start the method on a separate thread or as an AsyncTask, so as to not have the method block your UI
I'm trying to have 2 theme options for my app, Dark and Light. When the dark theme is selected I use sharedpreference to save and apply the theme on startup. But when I try to change the background color of the toolbar & appBarLayout like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
long currentTheme = sharedPref.getInt(getString(string.current_theme), 0);
if (currentTheme == 0) {
this.setTheme(R.style.AppTheme_NoActionBar);
}
if (currentTheme == 1) {
this.setTheme(R.style.AppTheme_NoActionBar_Dark);
Toolbar toolbar = (Toolbar) findViewById(id.toolbar);
setSupportActionBar(toolbar);
toolbar.setBackgroundColor(getResources().getColor(ActionbarDark));
}
Logcat returns the error: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.Toolbar.setBackgroundColor(int)' on a null object reference
And I cant understand why
Update: Fixed it by using the answer from #Nilesh Rathod and changing the theme of the activity before setting the content view, then after setting content view changing the theme of the Toolbar and AppBarLayout.
You have missed R in findViewById of toolbar
it should like below
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
change your code like this
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
long currentTheme = sharedPref.getInt(getString(string.current_theme), 0);
if (currentTheme == 0) {
this.setTheme(R.style.AppTheme_NoActionBar);
}
if (currentTheme == 1) {
this.setTheme(R.style.AppTheme_NoActionBar_Dark);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(0xff00DDED));
}
setContentView(R.layout.activity_main);
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
android.app.FragmentManager fragmentmanager = getFragmentManager();
fragmentmanager.beginTransaction()
.replace(R.id.content_frame
, new FirstFragment())
.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, string.navigation_drawer_open, string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.getMenu().getItem(0).setChecked(true);
}
My app has two activities, the main one is working well but when opening the login one it crashes with the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
Here's the fragment of my code referred to the toolbar (It's basically the login activity + the toolbar I want to add):
public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor> {
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.inflateMenu(R.menu.mainmenu);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Toolbar and menu are working well on my main activity. Toolbar is also in the XML layout for the login activity.
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference...
This NPE intimate you to first of all set the toolbar
You are not setting the toolbar..First of all set it...
Do like this...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
toolbar = (Toolbar) findViewById(R.id.toolbar);
// toolbar.inflateMenu(R.menu.mainmenu);
setSupportActionBar(toolbar)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
you don't need to use toolbar.inflateMenu() because the Toolbar is acting as your ActionBar. The only time you need to call toolbar.inflateMenu() is when you are using the Toolbar as a standalone widget. You can handle menu item click events by using the following lines of code...
toolbar.setOnMenuItemClickListener(
new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
// Handle menu item click event here
return true;
}
});
Hope this will help you
call setSupportActionBar(toolbar); before getSupportActionBar().setDisplayHomeAsUpEnabled(true);
I'm having a problem with the Navigation Drawer Icon.
We replaced the default "back caret" to use a different icon and it works fine.
However, if the navigation drawer is already open and the user rotates their device, then the icon reverts back to the default caret and won't go back to the custom one until the navigation drawer is closed and the onCreate() method for the activity is called again (usually by rotating the device).
Here is the code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
// set the toolbar as the action bar
Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
toolbar.setNavigationIcon(R.drawable.ic_drawer);
setSupportActionBar(toolbar);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new StartFragment())
.commit();
}
//Init the GameLog
GameLog.init(this);
}
/**
* Initializes the DrawerLayout for the particular activity
*/
public static void init(Activity activity) {
mActivity = activity;
mDrawerLayout = (DrawerLayout)activity.findViewById(R.id.drawer_layout);
mRecyclerView = (RecyclerView)activity.findViewById(R.id.left_drawer);
//set adapter
mRecyclerView.setAdapter(mAdapter);
//set layout manager
mRecyclerView.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false));
//add a divider between elements
mRecyclerView.addItemDecoration(
new HorizontalDividerItemDecoration.Builder(activity)
.color(Color.WHITE)
.build());
Toolbar toolbar = (Toolbar)((ActionBarActivity)activity).getSupportActionBar().getCustomView();
mDrawerToggle = new ActionBarDrawerToggle(activity, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (activity.getActionBar() != null) {
activity.getActionBar().setDisplayHomeAsUpEnabled(true);
activity.getActionBar().setHomeButtonEnabled(true);
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
GameLog.getToggle().syncState();
}
Hopefully this makes sense.
Thanks for any help.
Look into calling ActionBarDrawerToggle#syncState.
https://developer.android.com/reference/android/support/v4/app/ActionBarDrawerToggle.html#syncState()