I am trying to set up the Android Nav Drawer with an action bar. I am having difficulty setting the icon for the Nav Drawer and generating all of the list items as well. Below is my code, I am currently generating a NullPointer Exception:
Crash:
--------- beginning of crash
04-20 18:02:03.690 13170-13170/com.sourcey.materialloginexample E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.sourcey.materialloginexample, PID: 13170
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sourcey.materialloginexample/com.troychuinard.fanpolls.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
at com.troychuinard.fanpolls.MainActivity.onCreate(MainActivity.java:71)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
MainActivity:
public class MainActivity extends AppCompatActivity implements HomePollsFragment.OnFragmentInteractionListener {
private Toolbar toolbar;
private Firebase mPollsRef;
private ViewPager mPager;
private ScreenSlidePagerAdapter mPagerAdapter;
private DateFormat mDateFormat;
private Date mDate;
private String mCurrentDateString;
private ValueEventListener v;
private String[] mPlanetTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.action_tool_bar);
setSupportActionBar(toolbar);
Firebase.setAndroidContext(this);
mPollsRef = FirebaseUtil.FIREBASE.child("Polls");
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
toolbar, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */) {
};
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
ArrayList<String> drawerTitleArray = new ArrayList<>();
drawerTitleArray.add(0, "TEST");
drawerTitleArray.add(1, "TEST 1");
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, drawerTitleArray));
// TODO: Add Fragment Code to check if savedInstanceState == null; add at Activity Level?
// Check that the activity is using the layout version with
// the fragment_container FrameLayout
//set up viewpager for current day
mPager = (ViewPager) findViewById(R.id.home_polls_viewpager_fragment_container);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
//get current date to apply to Viewpager
mDateFormat = new SimpleDateFormat("MM-dd-yyyy");
mDate = new Date();
mCurrentDateString = mDateFormat.format(mDate);
// TODO: Checkn if AuthStateListenerNecessary
//Determine whether necessary to use an AuthStateListener here
// mUserRef.addAuthStateListener(new Firebase.AuthStateListener() {
// #Override
// public void onAuthStateChanged(AuthData authData) {
// if (authData == null) {
// Intent backToSignIn = new Intent(getApplication(), SignupActivity.class);
// startActivity(backToSignIn);
// finish();
// }
// }
// })
}
#Override
protected void onStart() {
super.onStart();
v = new ValueEventListener() {
//testing methodology of adding children
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int pollsAvailable = (int) dataSnapshot.child(mCurrentDateString).getChildrenCount();
mPagerAdapter.setPollsAvailable(pollsAvailable);
Log.i("TAG", "There are " + String.valueOf(pollsAvailable) + " children in today's poll count.");
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
};
mPollsRef.addValueEventListener(v);
}
#Override
protected void onStop() {
super.onStop();
mPollsRef.removeEventListener(v);
}
#Override
public void onFragmentInteraction(Uri uri) {
}
class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
private int pollsAvailable = 0;
//fragment adapter constructor
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return HomePollsFragment.newInstance(position);
}
#Override
public int getCount() {
return pollsAvailable;
}
public void setPollsAvailable(int pollsAvailable) {
this.pollsAvailable = pollsAvailable;
this.notifyDataSetChanged();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
if (mPager.getCurrentItem() == 0) {
// If the user is currently looking at the first step, allow the system to handle the
// Back button. This calls finish() on this activity and pops the back stack.
super.onBackPressed();
} else {
// Otherwise, select the previous step.
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
}
XML:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/action_tool_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/actionRed">
</android.support.v7.widget.Toolbar>
<android.support.v4.view.ViewPager
android:id="#+id/home_polls_viewpager_fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</LinearLayout>
<!-- The navigation drawer -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>
I do it like this:
android.support.v7.app.ActionBar actionBar = getSupportActionBar();
if(actionBar != null){
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
This should solve the java.lang.NullPointerException.
"and generating all of the list items as well"
I cant see whats the problem here. Could you explain it a little bit?
The icon - Three horizontal lines in closed mode, a back arrow in opened mode with a nice smoot animation:
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
drawerLayout, /* DrawerLayout object */
toolbar, /* nav drawer icon to replace 'Up' caret */
R.string.nav, /* "open drawer" description */
R.string.nav /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
if(extra == null){
toolbar.setTitle(title);
}else{
toolbar.setTitle(title + " - " + extra);
}
isOpen = false;
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
actionBar.setTitle(R.string.nav);
isNavReady = true;
isOpen = true;
}
};
drawerLayout.addDrawerListener(drawerToggle);
#Override
public boolean onOptionsItemSelected(MenuItem item){
return drawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
Related
I have created a project int activity_main and want to add a Navigation drawer to it.
I have gone into the java folder. Right click > new > Actvity > Navigation Drawer activity.
Note: I DON't have an action bar, to create the menu button(3 stacked lines)
Now I don't know how to actually open the navigation drawer over activity_main, without the app crashing.
Thanks.
I've tried doing an on click listener with a button which has
the drawer layout defined as dl (DrawerLayout dl = (DrawerLayout)findviewbyIOd(R.id.Drawer_layout))
and have done
dl.openDrawer(Gravity.LEFT);
have tried putting the code from the NavDrawer activity into the activity_main, but app won't start.
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
Switch OnOff;
EditText editText;
int NumberPicked;
int NumberPicked2;
private DrawerLayout dl;
private ActionBarDrawerToggle abdt;
Values[] troughvals = new Values[8];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BobbleSelector BS = new BobbleSelector();
final DrawerLayout dl = (DrawerLayout)findViewById(R.id.dl);
Button btnChange = (Button) findViewById(R.id.btnChange);
Switch OnOff = (Switch) findViewById(R.id.OnOff);
NumberPicker numberPicker2 = findViewById(R.id.numberPicker2);
NumberPicker numberPicker = findViewById(R.id.numberPicker);
numberPicker.setMinValue(00);
numberPicker2.setMinValue(00);
numberPicker2.setMaxValue(23);
numberPicker.setMaxValue(23);
btnChange.setOnClickListener( new View.OnClickListener(){
public void onClick(View v){
dl.openDrawer(Gravity.LEFT);
}
});
OnOff.setTextOff("On");
OnOff.setTextOn("Off");
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return abdt.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
public void handleSwitchClick(View view) {
Switch s = (Switch) view;
boolean isChecked = s.isChecked();
}
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked){
switch (compoundButton.getId()){
case R.id.OnOff:
break;
}
}
}
Note: have disabled fab, because it could not be found in my project.
I have created a custom Menu for the Navigation Drawer
public class BobbleSelector extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bobble_selector);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Button fab = findViewById(R.id.btnChange);
// fab.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
// }
// });
DrawerLayout drawer = findViewById(R.id.dl);
NavigationView navigationView = findViewById(R.id.nav_view);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.dl);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.bobble_selector, 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.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
DrawerLayout drawer = findViewById(R.id.dl);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Drawer Layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/dl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_bobble_selector"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_bobble_selector"
app:menu="#menu/nav_menu" />
</android.support.v4.widget.DrawerLayout>
From Logcat
2019-06-02 13:13:08.195 12745-12745/com.example.mytest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mytest, PID: 12745
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.openDrawer(int)' on a null object reference
at com.example.mytest.MainActivity$1.onClick(MainActivity.java:49)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:440)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Expected to open drawer with the changebutton.openDrawer(Gravity.Left) But crashes the app.
Found I needed to move the code relating to the nav bar to the bottom of OnCreate and set the "SetContentView()" to be the layout for the Navigation bar.
Then it worked perfectly.
Before
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.btnChange);
drawer = findViewById(R.id.dl);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,drawer, R.string.navigation_drawer_open,R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
//Not nav
Switch OnOff = (Switch) findViewById(R.id.OnOff);
NumberPicker numberPicker2 = findViewById(R.id.numberPicker2);
NumberPicker numberPicker = findViewById(R.id.numberPicker);
numberPicker.setMinValue(00);
numberPicker2.setMinValue(00);
numberPicker2.setMaxValue(23);
numberPicker.setMaxValue(23);
OnOff.setTextOff("On");
OnOff.setTextOn("Off");
//not nav
}
After
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.btnChange);
//Not nav
Switch OnOff = (Switch) findViewById(R.id.OnOff);
NumberPicker numberPicker2 = findViewById(R.id.numberPicker2);
NumberPicker numberPicker = findViewById(R.id.numberPicker);
numberPicker.setMinValue(00);
numberPicker2.setMinValue(00);
numberPicker2.setMaxValue(23);
numberPicker.setMaxValue(23);
OnOff.setTextOff("On");
OnOff.setTextOn("Off");
//not nav
setContentView(R.layout.activity_bobble_selector);
drawer = findViewById(R.id.dl);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,drawer, R.string.navigation_drawer_open,R.string.navigation_drawer_close);
assert drawer != null;
drawer.addDrawerListener(toggle);
toggle.syncState();
}
I created an android application using ButterKnife. I wanted to add an activity with Navigation bar . So I used , Navigation Drawer Activityin android studio.
Then I tried to launch it using another activity .Like this ,
Intent intent = new Intent(this, AddInfoActivity.class);
startActivity(intent);
Then I got following error message.
FATAL EXCEPTION: main
Process: xxx.com.au.abcd, PID: 13408
java.lang.RuntimeException: Unable to start activity ComponentInfo{xxx.com.au.abcd/xxx.com.au.abcd.activities.AddInfoActivity}: android.view.InflateException: Binary XML file line #18: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2436)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2498)
at android.app.ActivityThread.access$900(ActivityThread.java:179)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1324)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5641)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1288)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1104)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #18: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:719)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)
at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
at android.view.LayoutInflater.inflate(LayoutInflater.java:354)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at xxx.com.au.abcd.activities.AddInfoActivity.onCreate(AddInfoActivity.java:33)
at android.app.Activity.performCreate(Activity.java:5484)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2400)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2498)
at android.app.ActivityThread.access$900(ActivityThread.java:179)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1324)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5641)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1288)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1104)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at xxx.com.au.abcd.activities.NavigationDrawerFragment.onCreateView(NavigationDrawerFragment.java:103)
at android.app.Fragment.performCreateView(Fragment.java:1700)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:866)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1040)
at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1142)
at android.app.Activity.onCreateView(Activity.java:5020)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:36)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:75)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:695)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)
at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
at android.view.LayoutInflater.inflate(LayoutInflater.java:354)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at xxx.com.au.abcd.activities.AddInfoActivity.onCreate(AddInfoActivity.java:33)
at android.app.Activity.performCreate(Activity.java:5484)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2400)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2498)
at android.app.ActivityThread.access$900(ActivityThread.java:179)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1324)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5641)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
And this is my activity with navigation bar,
AddInfoActivity.java
import android.app.Activity;
import butterknife.ButterKnife;
import tekhinno.com.au.mygulukose.R;
public class AddInfoActivity extends BaseActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_info_activity);
ButterKnife.inject(this);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_add_info, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((AddInfoActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
NavigationDrawerFragment.java
import butterknife.ButterKnife;
import tekhinno.com.au.mygulukose.R;
/**
* Fragment used for managing interactions for and presentation of a navigation drawer.
* See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
* design guidelines</a> for a complete explanation of the behaviors implemented here.
*/
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
**#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.drawer_add_info, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3),
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}**
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.action_example) {
Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return getActivity().getActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
And these are my layout files,
fragment_add_info.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="tekhinno.com.au.mygulukose.activities.AddInfoActivity$PlaceholderFragment">
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
drawer_add_info.xml
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#cccc"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
tools:context="tekhinno.com.au.mygulukose.activities.NavigationDrawerFragment" />
add_info_activity.xml
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="tekhinno.com.au.mygulukose.activities.AddInfoActivity">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The drawer is given a fixed width in dp and extends the full height of
the container. -->
<fragment
android:id="#+id/navigation_drawer"
android:name="tekhinno.com.au.mygulukose.activities.NavigationDrawerFragment"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
tools:layout="#layout/drawer_add_info" />
</android.support.v4.widget.DrawerLayout>
NOTE :- These layout files and NavigationDrawerFragment.java were generated by Android Studio.
Have any idea about this problem ?
You are using getFragmentManager() to get the fragment manager. You need to get SupportFragmentManager if you are extending AppCompatActivity by your BaseActivity.
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
Note: While using support packages you need to use SupportFragmentManager.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
When I run the program I get NullPointerException on the line albumlist.add(0, recentAlbum). I have checked other classes which is good and I even initialized the list But i cant figure out where I went wrong.
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// Navigation drawer title
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private List<Category> albumsList;
private ArrayList<NavDrawerItem> navDrawerItems = new ArrayList<NavDrawerItem>();
private NavDrawerListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
// Getting the albums from shared preferences
albumsList = AppController.getInstance().getPrefManager().getCategory();
// Insert "Recently Added" in navigation drawer first position
Category recentAlbum = new Category(null,
getString(R.string.nav_drawer_recently_added));
albumsList.clear();
albumsList.add(0, recentAlbum);
// Loop through albums in add them to navigation drawer adapter
for (Category a : albumsList) {
navDrawerItems.add(new NavDrawerItem(a.getId(), a.getTitle()));
}
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// Setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// Enabling action bar app icon and behaving it as toggle button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setIcon(
new ColorDrawable(getResources().getColor(
android.R.color.transparent)));
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.side_nav_bar, R.string.app_name, R.string.app_name) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
/**
* Navigation drawer menu item click listener
*/
private class SlideMenuClickListener implements AdapterView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_scrolling, menu);
return true;
}
/**
* On menu item selected
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
// Selected settings menu item
// launch Settings activity
Intent intent = new Intent(MainActivity.this,
SettingsActivity.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
*/
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
// Recently added item selected
// don't pass album id to home fragment
fragment = GridFragment.newInstance(null);
break;
default:
// selected wallpaper category
// send album id to home fragment to list all the wallpapers
String albumId = albumsList.get(position).getId();
fragment = GridFragment.newInstance(albumId);
break;
}
if (fragment != null) {
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(albumsList.get(position).getTitle());
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e(TAG, "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
} }
Here is the Stack trace
Process: com.thedreamlight.thewallyapp, PID: 4645
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.thedreamlight.thewallyapp/com.thedreamlight.thewallyapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2479)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2541)
at android.app.ActivityThread.access$1000(ActivityThread.java:168)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1436)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5628)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:956)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:751)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference
at com.thedreamlight.thewallyapp.MainActivity.onCreate(MainActivity.java:61)
at android.app.Activity.performCreate(Activity.java:6001)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2432)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2541)
at android.app.ActivityThread.access$1000(ActivityThread.java:168)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1436)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5628)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:956)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:751)
Initialize albumList array list like this:
private List<Category> albumsList = new ArrayList<>();
Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference
In a nutshell, you are trying to use a null variable,which will through NullPointerException.
private List<Category> albumsList; that you declare was not initiated yet, so you need to initialize it as follows:
private List<Category> albumsList = new ArrayList<>();
I am working on an Android project in which I would like to add Drawer functionality, for which I already have classes and all ready.
THe problem is the Drawer code works by extends or extending the class which wants to add a drawer, and similarly my GoogleMaps code works in the same way. But because of Multiple-inheritance, I cannot extend 2 classes.
What should I do?
Google-maps code :
public class MapsActivity extends FragmentActivity {
GoogleMap googleMap;
SharedPreferences sharedPreferences;
int locationCount = 0;
private RestaurantServiceImpl restaurantService = new RestaurantServiceImpl();
List<RestRestaurant> restRestaurantList = new ArrayList<>();
GPSTracker gps;
double longitude, latitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapsact);
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
// Opening the sharedPreferences object
sharedPreferences = getSharedPreferences("location", 0);
// Getting number of locations already stored
locationCount = sharedPreferences.getInt("locationCount", 0);
// Getting stored zoom level if exists else return 0
String zoom = sharedPreferences.getString("zoom", "12");
gps = new GPSTracker(MapsActivity.this);
if (gps.canGetLocation()) {
longitude = gps.getLongitude();
latitude = gps.getLatitude();
restRestaurantList = this.restaurantService.getRestaurantsByLocation(longitude,latitude);
double lat=0, longi=0;
for(RestRestaurant restRestaurant : restRestaurantList){
drawMarker(new LatLng(restRestaurant.getLatitude(),restRestaurant.getLongitude()), restRestaurant.getRestaurantName(), restRestaurant.getRestaurantId());
lat = restRestaurant.getLatitude();
longi = restRestaurant.getLongitude();
}
googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(lat,longi)));
// Setting the zoom level in the map on last position is clicked
googleMap.animateCamera(CameraUpdateFactory.zoomTo(Float.parseFloat(zoom)));
} else {
gps.showSettingsAlert();
}
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
int restoId = Integer.valueOf(marker.getSnippet());
Intent intent = new Intent(MapsActivity.this, MenuCardList.class);
intent.putExtra("restaurantid", restoId);
startActivity(intent);
finish();
return true;
}
});
}
This class I need to extend to add a drawer :
public class DrawerLoader extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
private ArrayList<DrawerModel> navDrawerItems;
private DrawerListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawerlayout);
}
public void set(String[] navMenuTitles, TypedArray navMenuIcons) {
mTitle = mDrawerTitle = getTitle();
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<DrawerModel>();
If any more information is required, kindly let me know.
Ignoring all your work regarding a navigation drawer, this would be my preferred solution, since There is no need for a extra Fragment, List filling, new classes....
1, Create a nav_menu.xml (in menues folder):
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group
android:checkableBehavior="single">
<item
android:id="#+id/drawer_home"
android:checked="true"
android:icon="#drawable/ic_home_black_24dp"
android:title="Home"/>
<item
android:id="#+id/drawer_favourite"
android:icon="#drawable/ic_favorite_black_24dp"
android:title="Favourites"/>
<item
android:id="#+id/drawer_settings"
android:icon="#drawable/ic_settings_black_24dp"
android:title="Settings"/>
</group>
2, Wrap your activites layout with a DrawerLayout:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Your activity layout here-->
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/drawer_header"
app:menu="#menu/nav_menu"/>
</android.support.v4.widget.DrawerLayout>
3, Update your activities java code:
//If you have a toolbar (recommended!)
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
//and finally the Navigation View Code:
final NavigationView navigation = (NavigationView) findViewById(R.id.navigation);
navigation.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
navigation.setCheckedItem(menuItem.getItemId());
drawerLayout.closeDrawers();
switch (menuItem.getItemId()) {
case R.id.drawer_home:
//open fragment home
return true;
case R.id.drawer_favourite:
//open fragment favourite
return true;
case R.id.nav_drawer_channels:
showFragment(2);
return true;
case R.id.drawer_settings:
//open settings
return true;
}
return false;
}
});
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(
this,
drawerLayout,
toolbar,
R.string.drawer_open, //simply a String "open"
R.string.drawer_close) { //simply a String "close"
public void onDrawerClosed(View view) {
super.onDrawerOpened(drawerLayout);
drawerToggle.syncState();
}
public void onDrawerOpened(View drawerView) {
super.onDrawerClosed(drawerLayout);
drawerToggle.syncState();
}
};
drawerLayout.setDrawerListener(drawerToggle);
drawerToggle.syncState();
//And, last but not least, open the drawer with a Click on 'home'
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
And you are done! No messing with extra fragment, unnecessary and messy code.
I have been having an issue passing an ArrayList from my activity to my fragment. I have tried several different methods of doing so, however, it appears that the code is not passing SetContentView as seen below, the onCreate method is instanciating the fragment, however executes nothing after SetContentView:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer);
Log.i(TAG, "scooby snacks");
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
ArrayList<String> menuItems = new ArrayList<String>();
menuItems.add("Test");
Bundle input = new Bundle();
input.putStringArrayList("edttext", menuItems);
/* set Fragmentclass Arguments */
mNavigationDrawerFragment.setArguments(input);
Log.i(TAG, mNavigationDrawerFragment.getArguments().toString());
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
The fragment code is as follows, it is only instantiating and trying to pull arguments:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ArrayList<String> strtext = getArguments().getStringArrayList("edttext");
Log.i(TAG, strtext.toString());
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
strtext));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
Here is the content view being referenced this is the code being called on SetContentView:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".drawer">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead. -->
<!-- The drawer is given a fixed width in dp and extends the full height of
the container. -->
<fragment
android:id="#+id/navigation_drawer"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:name="org.tcnjteamandroid.cryptochat.NavigationDrawerFragment"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
Finally, here is the stack trace:
04-02 17:59:57.897 23321-23321/org.tcnjteamandroid.cryptochat E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: org.tcnjteamandroid.cryptochat, PID: 23321
java.lang.RuntimeException: Unable to start activity ComponentInfo{org.tcnjteamandroid.cryptochat/org.tcnjteamandroid.cryptochat.drawer}: android.view.InflateException: Binary XML file line #24: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2299)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2361)
at android.app.ActivityThread.access$800(ActivityThread.java:145)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1279)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5240)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: android.view.InflateException: Binary XML file line #24: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at android.support.v7.app.ActionBarActivityDelegateBase.setContentView(ActionBarActivityDelegateBase.java:228)
at android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:102)
at org.tcnjteamandroid.cryptochat.drawer.onCreate(drawer.java:56)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2252)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2361)
at android.app.ActivityThread.access$800(ActivityThread.java:145)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1279)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5240)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.ArrayList android.os.Bundle.getStringArrayList(java.lang.String)' on a null object reference
at org.tcnjteamandroid.cryptochat.NavigationDrawerFragment.onCreateView(NavigationDrawerFragment.java:100)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:920)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1206)
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2159)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:297)
at android.support.v7.app.ActionBarActivity.onCreateView(ActionBarActivity.java:547)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at android.support.v7.app.ActionBarActivityDelegateBase.setContentView(ActionBarActivityDelegateBase.java:228)
at android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:102)
at org.tcnjteamandroid.cryptochat.drawer.onCreate(drawer.java:56)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2252)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2361)
at android.app.ActivityThread.access$800(ActivityThread.java:145)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1279)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5240)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Thanks in advance!
I tried for a couple of hours to get this working with a bundle to get data to the NavigationDrawerFragment, and was not successful. I was getting the same errors that you are getting.
However, I realized that since you have a reference to mNavigationDrawerFragment, there is no need to use a bundle to pass data.
I was able to just add a parameter to setUp() and pass an ArrayList that way.
MainActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
ArrayList<String> menuItems = new ArrayList<String>();
menuItems.add("Test");
menuItems.add("Test2");
menuItems.add("TestThree");
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout), menuItems);
}
NavigationDrawerFragment.java:
public void setUp(int fragmentId, DrawerLayout drawerLayout, ArrayList<String> array) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
Log.i("NavTesting", array.toString());
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
//......
It successfully logged the array passed in:
04-02 18:11:30.680 17274-17274/com.fragmentarraylist.daniel.myapplication I/NavTesting﹕ [Test, Test2, TestThree]
Then, if you want to update data in the NavigationDrawer at times other than initialization, you can add a function to update the data.
In NavigationDrawerFragment.java:
public class NavigationDrawerFragment extends Fragment {
private ArrayList<String> mArray;
//......
public void updateArray(ArrayList<String> array){
Log.i("NavTesting", array.toString());
mArray = array;
}
//......
private void selectItem(int position) {
if (mArray != null){
Log.i("NavTestingSelectItem", mArray.toString());
}
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
In MainActivity.java:
public void onSectionAttached(int number) {
ArrayList<String> menuItems = new ArrayList<String>();
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
menuItems.add(mTitle.toString());
mNavigationDrawerFragment.updateArray(menuItems);
break;
case 2:
mTitle = getString(R.string.title_section2);
menuItems.add(mTitle.toString());
mNavigationDrawerFragment.updateArray(menuItems);
break;
case 3:
mTitle = getString(R.string.title_section3);
menuItems.add(mTitle.toString());
mNavigationDrawerFragment.updateArray(menuItems);
break;
}
}
After running and clicking on the different Drawer selections:
04-03 07:31:13.529 9397-9397/com.fragmentarraylist.daniel.myapplication I/NavTesting﹕ [Test, Test2, TestThree]
04-03 07:31:13.539 9397-9397/com.fragmentarraylist.daniel.myapplication I/NavTesting﹕ [Section 1]
04-03 07:31:18.874 9397-9397/com.fragmentarraylist.daniel.myapplication I/NavTestingSelectItem﹕ [Section 1]
04-03 07:31:18.884 9397-9397/com.fragmentarraylist.daniel.myapplication I/NavTesting﹕ [Section 2]
04-03 07:31:27.963 9397-9397/com.fragmentarraylist.daniel.myapplication I/NavTestingSelectItem﹕ [Section 2]
04-03 07:31:27.973 9397-9397/com.fragmentarraylist.daniel.myapplication I/NavTesting﹕ [Section 3]
04-03 07:31:33.829 9397-9397/com.fragmentarraylist.daniel.myapplication I/NavTestingSelectItem﹕ [Section 3]
04-03 07:31:33.839 9397-9397/com.fragmentarraylist.daniel.myapplication I/NavTesting﹕ [Section 1]
Update: I just tested this and it looks like it works, just move the call to setAdapter() to the setUp() function in order to populate the Navigation Drawer menu with the ArrayList.
public void setUp(int fragmentId, DrawerLayout drawerLayout, ArrayList<String> array) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
Log.i("NavTesting", array.toString());
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
array));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
If you want to update the title from the ArrayList as well, you could also do this in the Activity (I just tested this and it works):
public void onSectionAttached(int number) {
if (menuItems == null){
menuItems = new ArrayList<String>();
menuItems.add("Test");
menuItems.add("Test2");
menuItems.add("TestThree");
}
switch (number) {
case 1:
mTitle = menuItems.get(0);
break;
case 2:
mTitle = menuItems.get(1);
break;
case 3:
mTitle = menuItems.get(2);
break;
}
}
However, I would recommend using values from strings.xml, and passing them into the NavigationDrawer. Here are my full class files and strings:
MainActivity.java:
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
ArrayList<String> menuItems;
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
menuItems = new ArrayList<String>();
menuItems.add(getString(R.string.title_section1));
menuItems.add(getString(R.string.title_section2));
menuItems.add(getString(R.string.title_section3));
//mNavigationDrawerFragment.updateArray(menuItems);
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout), menuItems);
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
public void onSectionAttached(int number) {
/*
if (menuItems == null){
menuItems = new ArrayList<String>();
menuItems.add("Test");
menuItems.add("Test2");
menuItems.add("TestThree");
}
switch (number) {
case 1:
mTitle = menuItems.get(0);
break;
case 2:
mTitle = menuItems.get(1);
break;
case 3:
mTitle = menuItems.get(2);
break;
}
*/
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
NavigationDrawerFragment.java:
public class NavigationDrawerFragment extends Fragment {
private ArrayList<String> mArray;
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
public void updateArray(ArrayList<String> array){
Log.i("NavTesting", array.toString());
mArray = array;
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout, ArrayList<String> array) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
Log.i("NavTesting", array.toString());
mArray = array;
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
mArray));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
if (mArray != null){
Log.i("NavTestingSelectItem", mArray.toString());
}
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.action_example) {
Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My Application</string>
<string name="title_section1">Test Section 1</string>
<string name="title_section2">Test Section 2</string>
<string name="title_section3">Test Section 3</string>
<string name="navigation_drawer_open">Open navigation drawer</string>
<string name="navigation_drawer_close">Close navigation drawer</string>
<string name="action_example">Example action</string>
<string name="action_settings">Settings</string>
</resources>