// I learned android studio about BottomNavigationView, but I have a problem like this ... please help me :(
// Caused by: java.lang.NullPointerException: Attempt to invoke
virtual method 'void
android.support.design.widget.BottomNavigationView.setOnNavigationItemSelectedListener(android.support.design.widget.BottomNavigationView$OnNavigationItemSelectedListener)'
on a null object reference// eror logcat
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selectedFragment = null;
switch (menuItem.getItemId()) {
case R.id.nav_home:
selectedFragment = new HomeFragment();
break;
case R.id.nav_search:
selectedFragment = new SearchFragment();
break;
case R.id.nav_filter:
selectedFragment = new PesananFragment();
break;
case R.id.nav_notifikasi:
selectedFragment = new NotificationFragment();
break;
case R.id.nav_akun:
selectedFragment = new AccountFragment();
break;
}
assert selectedFragment != null;
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();
return true;
}
};
}
It looks like a problem with the initial bottomNav stationing.
Maybe try to put explicit casting like:
BottomNavigationView bottomNav=(BottomNavigationView)findViewById(R.id.bottom_navigation);
If that does not work check the BottomNavigationView implementation requirements.
You can use android studio to create a activity that already has a Bottom navigation.
Related
So this is my main activity class
public class NewMainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
DrawerLayout drawerLayout;
NavigationView navigationView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_main_activity);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.purple_500));
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, new HomeFragment()).commit();
bottomNav.setOnNavigationItemSelectedListener(navListener);
//NewNav
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.navView);
navigationView.bringToFront();
ActionBarDrawerToggle toggle=new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.navigation_drawer_open,R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.mm_home);
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()){
case R.id.nav_home:
selectedFragment = new HomeFragment();
break;
case R.id.nav_faq:
selectedFragment = new FAQFragment();
break;
case R.id.nav_price:
selectedFragment = new PriceMarketFragment();
break;
case R.id.nav_news:
selectedFragment = new NewsFragment();
break;
}
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, selectedFragment).commit();
return true;
}
};
I have a frame layout in my mainactivity xml which i have given ID fragment_container.
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintTop_toBottomOf="#id/appBarLayout"
app:layout_constraintBottom_toTopOf="#id/navBottom"/>
In bottom navigation, I have 4 fragments, in which 3 fragments (Home, Price and News), I have tablayouts (more fragments within fragments).
When the mainactivity starts (the application starts) i want all of the parent fragments and child fragments to be loaded. and then i only need to navigate through them.
How can i do this please help.
When I click again to any item, same fragment view reloading every time. But I wanna do bottom navigation bar item one time clickable. how can i do this?
This is MainActivity.java codes
navigationMenu=findViewById(R.id.navigation);
navigationMenu.setOnNavigationItemSelectedListener(navListener);
//navigationMenu.getMenu().getItem(2).setIcon(R.drawable.arrow_down);
//I added this if statement to keep the selected fragment when rotating the device
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new UserHomeFragment()).commit();
}
This is click listener codes
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.navigation_home:
selectedFragment = new UserHomeFragment();
break;
case R.id.navigation_works:
selectedFragment = new UserWorksFragment();
break;
case R.id.navigation_completed_works:
selectedFragment = new UserCompletedFragment();
break;
case R.id.navigation_profile:
selectedFragment = new UserAccountFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return true;
}
};
I have an android app created with android studio that has a main activity and fragments with webview. Each fragment contains webview code with a link to a website. The problem that I have is that when I press back it closes the app. I want to use back to go to the previous page and the previous activity.
Main Activity code:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.nav_facebook:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FacebookFragment()).commit();
break;
case R.id.nav_twitter:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new TwitterFragment()).commit();
break;
case R.id.nav_instagram:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new InstagramFragment()).commit();
break;
case R.id.nav_linkedin:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new LinkedinFragment()).commit();
break;
case R.id.nav_snapchat:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new SnapchatFragment()).commit();
break;
case R.id.nav_pinterest:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new PinterestFragment()).commit();
break;
case R.id.nav_youtube:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new YoutubeFragment()).commit();
break;
case R.id.nav_about:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new AboutFragment()).commit();
break;
case R.id.nav_privacy:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new PrivacyFragment()).commit();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
Here is the code of one of the fragment's code (the rest of the fragments has similar code):
public class FacebookFragment extends Fragment {
public FacebookFragment() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_facebook, container, false);
WebView webView = (WebView)v.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://www.facebook.com/");
return v;
}
}
After replacing the fragment just make sure to add it to back stack using:
replace(R.id.fragment_container,
new YoutubeFragment()).addToBackStack("tag").commit()
and override the onBackPressed function to pop up stack while it's not empty.
All these fragments have same function is go back fragment. Why don't add the base fragment for them and the code will be easier.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I created a navigation drawer with fragments but I get the error mentioned in the title. When I run the app and click on a menu item, instead of initializing the fragment, it just crashes. Any help would be greatly appreciated.
ActivityMain:
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mToggle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
NavigationView nvDrawer = (NavigationView) findViewById(R.id.nv);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setupDrawerContent(nvDrawer);
}
#Override
public boolean onOptionsItemSelected (MenuItem item) {
if (mToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void selectItemDrawer (MenuItem menuItem){
android.support.v4.app.Fragment myFragment = null;
Class fragmentClass;
switch (menuItem.getItemId()){
case R.id.home:
fragmentClass= home.class;
break;
case R.id.planning:
fragmentClass= planning.class;
break;
case R.id.meal:
fragmentClass= foodOmatic.class;
break;
case R.id.recipes:
fragmentClass= recipes.class;
break;
case R.id.extra:
fragmentClass= extra.class;
break;
case R.id.options:
fragmentClass= options.class;
break;
case R.id.logout:
fragmentClass= logoff.class;
break;
default:
fragmentClass = home.class;
}
try {
myFragment = (android.support.v4.app.Fragment) fragmentClass.newInstance();
}
catch (Exception e) {
e.printStackTrace();
}
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flcontent,myFragment).commit();
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawerLayout.closeDrawers();
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
selectItemDrawer(item);
return true;
}
});
}
And here is the logcat:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
at android.support.v4.app.BackStackRecord.doAddOp(BackStackRecord.java:392)
at android.support.v4.app.BackStackRecord.replace(BackStackRecord.java:439)
at android.support.v4.app.BackStackRecord.replace(BackStackRecord.java:430)
at com.example.android.meat_timealpha10.Activities.MainActivity.selectItemDrawer(MainActivity.java:88)
at com.example.android.meat_timealpha10.Activities.MainActivity$1.onNavigationItemSelected(MainActivity.java:98)
at android.support.design.widget.NavigationView$1.onMenuItemSelected(NavigationView.java:156)
at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:171)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:973)
at android.support.design.internal.NavigationMenuPresenter$1.onClick(NavigationMenuPresenter.java:342)
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:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
I understand it probably has something to do with android.support.v4.app.Fragment myFragment = null; But I don't know how else to do this. Thanks in advance for your help!
This is because you call newInstance() on your fragmentClass, and the fragmentClass object is null at the time of your call. You should create the actual Class object you want by something similar to
case R.id.home:
fragmentClass = new HomeFragment(); //for home
break;
And so on for each different possible class so when you call newInstance(), your
fragmentClass is not null.
Your problem is in the default:return default:fragmentClass = home.class; according to the Java documentation
The default section handles all values that are not explicitly handled
by one of the case sections.
Please take a look at my answer here
I have a problem with ButterKnife library. My views stopped binding after syncing gradle - before it was working without any problem.
I attached some code.
build.gradle (app)
compile 'com.jakewharton:butterknife:8.6.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.6.0'
MainActivity
public class MainActivity extends AppCompatActivity {
#BindView(R.id.navigation)
BottomNavigationView navigation;
private Fragment fragment;
private FragmentManager fragmentManager;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
fragment = new HomeFragment();
break;
case R.id.navigation_dashboard:
fragment = new GraphFragment();
break;
case R.id.navigation_notifications:
fragment = new ProfileFragment();
break;
}
final FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.content, fragment).commit();
return true;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.setDebug(true);
ButterKnife.bind(this);
fragmentManager = getSupportFragmentManager();
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}}
ButterKnife logs
D/ButterKnife: Looking up binding for
com.example.azkb.instproject.refactor.MainActivity D/ButterKnife: Not
found. Trying superclass android.support.v7.app.AppCompatActivity
D/ButterKnife: MISS: Reached framework class. Abandoning search.
The problem occured when I added Kotlin to my project.
Solution:
kapt 'com.jakewharton:butterknife-compiler:8.7.0'
Thanks for downvoting :)