I created ViewPager with fragments. But when I switch to another fragment in this Activity, the app crashes. Debugger shows a very long list of errors. When I tap on page title the app crashes immediately but when I slide it the app crashes after more than one slide. Here is Debug Console log, Java and XML codes from my app. Please write in comments if you need to see more code.
Debug Console
E/InputEventReceiver: Exception dispatching input event.
E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
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.add(BackStackRecord.java:387)
at android.support.v4.app.FragmentPagerAdapter.instantiateItem(FragmentPagerAdapter.java:104)
at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:1004)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1218)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1086)
at android.support.v4.view.ViewPager$3.run(ViewPager.java:267)
at android.support.v4.view.ViewPager.completeScroll(ViewPager.java:1999)
at android.support.v4.view.ViewPager.onInterceptTouchEvent(ViewPager.java:2129)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1965)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2438)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2060)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2438)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2060)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2438)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2060)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2438)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2060)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2438)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2060)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2438)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2060)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2386)
at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1730)
at android.app.Activity.dispatchTouchEvent(Activity.java:2757)
at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:68)
at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:68)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2347)
at android.view.View.dispatchPointerEvent(View.java:8681)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4123)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3989)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3544)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3597)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3563)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3680)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3571)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3737)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3544)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3597)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3563)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3571)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3544)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5817)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5791)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5762)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:5907)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:143)
at android.os.Looper.loop(Looper.java:122)
at android.app.ActivityThread.main(ActivityThread.java:5345)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.r
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.chatting, PID: 13816
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.add(BackStackRecord.java:387)
at android.support.v4.app.FragmentPagerAdapter.instantiateItem(FragmentPagerAdapter.java:104)
at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:1004)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1218)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1086)
at android.support.v4.view.ViewPager$3.run(ViewPager.java:267)
at android.support.v4.view.ViewPager.completeScroll(ViewPager.java:1999)
at android.support.v4.view.ViewPager.onInterceptTouchEvent(ViewPager.java:2129)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1965)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2438)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2060)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2438)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2060)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2438)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2060)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2438)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2060)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2438)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2060)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2438)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2060)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2386)
at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1730)
at android.app.Activity.dispatchTouchEvent(Activity.java:2757)
at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:68)
at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:68)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2347)
at android.view.View.dispatchPointerEvent(View.java:8681)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4123)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3989)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3544)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3597)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3563)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3680)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3571)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3737)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3544)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3597)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3563)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3571)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3544)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5817)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5791)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5762)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:5907)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:143)
at android.os.Looper.loop(Looper.java:122)
at android.app.ActivityThread.main(ActivityThread.java:5345)
at
MainActivity.java
public class MainActivity extends AppCompatActivity {
private android.support.v7.widget.Toolbar mToolbar;
private FirebaseAuth mAuth;
private ViewPager myViewPager;
private TabLayout myTabLayout;
private TabsPagerAdapter myTabsPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
//Tabs for MainActivity
myViewPager = (ViewPager) findViewById(R.id.main_tabs_pager);
myTabsPagerAdapter = new TabsPagerAdapter(getSupportFragmentManager());
myViewPager.setAdapter(myTabsPagerAdapter);
myTabLayout = (TabLayout) findViewById(R.id.main_tabs);
myTabLayout.setupWithViewPager(myViewPager);
mToolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Chatting");
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null){
LogOutUser();
}
}
private void LogOutUser() {
Intent startPageIntent = new Intent(MainActivity.this, StartPageActivity.class);
startPageIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(startPageIntent);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.main_logout_button){
mAuth.signOut();
LogOutUser();
}
return true;
}
}
MainActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include
layout="#layout/app_bar_layout"
android:id="#+id/main_page_toolbar">
</include>
<android.support.design.widget.TabLayout
android:id="#+id/main_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/main_tabs_pager"
android:layout_width="match_parent"
android:layout_height="464dp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"></android.support.v4.view.ViewPager>
</RelativeLayout>
TabsPagerAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
RequestsFragment requestsFragment = new RequestsFragment();
return requestsFragment;
case 1:
ChatsFragment chatsFragment = new ChatsFragment();
return chatsFragment;
case 3:
FriendsFragment friendsFragment = new FriendsFragment();
return friendsFragment;
default:
return null;
}
}
#Override
public int getCount() {
return 3;
}
public CharSequence getPageTitle(int position){
switch (position){
case 0:
return "Requests";
case 1:
return "Chats";
case 2:
return "Friends";
default:
return null;
}
}
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
RequestsFragment requestsFragment = new RequestsFragment();
return requestsFragment;
case 1:
ChatsFragment chatsFragment = new ChatsFragment();
return chatsFragment;
case 3:
FriendsFragment friendsFragment = new FriendsFragment();
return friendsFragment;
default:
return null;
}
where is case 2, my friend? And do not return null in the default case. Just return any one of declared fragments.
#Override
public int getCount() {
return 3;
}
will make it run three times. for 0,1 and 2 positions but for case 2, default fragment is returned which is null. Resulting in null pointer exception.
case 3:
FriendsFragment friendsFragment = new FriendsFragment();
return friendsFragment;
change this to
case 2:
FriendsFragment friendsFragment = new FriendsFragment();
return friendsFragment;
Related
I am new to android .. trying to build application that is having webview inside fragment and in the bottom it is having BottomNavigationView on click of particular item fragment change according to click .
every thing is working fine when having 3 items in BottomNavigationView when i add 4 app start crashing .
error is as fallows -
E/AndroidRuntime: FATAL EXCEPTION: main
Process: in.xparticle.digitalkabadi, PID: 23369
java.lang.RuntimeException: Unable to start activity ComponentInfo{in.xparticle.digitalkabadi/in.xparticle.digitalkabadi.MainActivity}: android.view.InflateException: Binary XML file line #19 in in.xparticle.digitalkabadi:layout/activity_main: Binary XML file line #19 in in.xparticle.digitalkabadi:layout/activity_main: Error inflating class com.google.android.material.bottomnavigation.BottomNavigationView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:491)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:940)
Caused by: android.view.InflateException: Binary XML file line #19 in in.xparticle.digitalkabadi:layout/activity_main: Binary XML file line #19 in in.xparticle.digitalkabadi:layout/activity_main: Error inflating class com.google.android.material.bottomnavigation.BottomNavigationView
Caused by: android.view.InflateException: Binary XML file line #19 in in.xparticle.digitalkabadi:layout/activity_main: Error inflating class com.google.android.material.bottomnavigation.BottomNavigationView
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
at android.view.LayoutInflater.createView(LayoutInflater.java:854)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1006)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:961)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1123)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1084)
at android.view.LayoutInflater.inflate(LayoutInflater.java:682)
at android.view.LayoutInflater.inflate(LayoutInflater.java:534)
at android.view.LayoutInflater.inflate(LayoutInflater.java:481)
at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:696)
at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:170)
at in.xparticle.digitalkabadi.MainActivity.onCreate(MainActivity.java:17)
at android.app.Activity.performCreate(Activity.java:7824)
at android.app.Activity.performCreate(Activity.java:7813)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1306)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:491)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:940)
E/AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setImportantForAccessibility(int)' on a null object reference
at androidx.core.view.ViewCompat.setImportantForAccessibility(ViewCompat.java:1119)
at com.google.android.material.bottomnavigation.BottomNavigationItemView.<init>(BottomNavigationItemView.java:104)
at com.google.android.material.bottomnavigation.BottomNavigationItemView.<init>(BottomNavigationItemView.java:87)
at com.google.android.material.bottomnavigation.BottomNavigationItemView.<init>(BottomNavigationItemView.java:83)
at com.google.android.material.bottomnavigation.BottomNavigationMenuView.getNewItem(BottomNavigationMenuView.java:606)
at com.google.android.material.bottomnavigation.BottomNavigationMenuView.buildMenuView(BottomNavigationMenuView.java:538)
at com.google.android.material.bottomnavigation.BottomNavigationPresenter.updateMenuView(BottomNavigationPresenter.java:67)
at com.google.android.material.bottomnavigation.BottomNavigationView.inflateMenu(BottomNavigationView.java:344)
at com.google.android.material.bottomnavigation.BottomNavigationView.<init>(BottomNavigationView.java:226)
at com.google.android.material.bottomnavigation.BottomNavigationView.<init>(BottomNavigationView.java:133)
... 28 more
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
}
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_scrape_price:
selectedFragment = new ScrapePriceFragment();
break;
case R.id.nav_aboutUs:
selectedFragment = new AboutUsFragment();
break;
case R.id.nav_scrape_Process:
selectedFragment = new AboutUsFragment();
break;
}
assert selectedFragment != null;
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return true;
}
};
}
try this -->
public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//loading the default fragment
loadFragment(new FirstFragment());
//getting bottom navigation view and attaching the listener
BottomNavigationView navigation = findViewById(R.id.bottom_navigation);
navigation.setOnNavigationItemSelectedListener(this);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.id1:
fragment = new FirstFragment();
break;
case R.id.id2:
fragment = new SecondFragment();
break;
case R.id.id3:
fragment = new thirsFragment();
break;
case R.id.id4:
fragment = new fourthFragment();
break;
}
return loadFragment(fragment);
}
private boolean loadFragment(Fragment fragment) {
//switching fragment
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
return true;
}
return false;
}
}
I tried to create a bottom navigation bar, but when I try to run the app it keeps showing "navbar has stopped".
I am using the code from this website: https://www.androidhive.info/2017/12/android-working-with-bottom-navigation/
public class MainActivity extends AppCompatActivity {
private ActionBar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = getSupportActionBar();
toolbar.setTitle("Home");
loadFragment(new HomeFragment());
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment;
switch (item.getItemId()) {
case R.id.navigation_home:
toolbar.setTitle("Home");
fragment = new HomeFragment();
loadFragment(fragment);
return true;
case R.id.navigation_search:
toolbar.setTitle("Search");
fragment = new SearchFragment();
loadFragment(fragment);
return true;
case R.id.navigation_category:
toolbar.setTitle("Category");
fragment = new CategoryFragment();
loadFragment(fragment);
return true;
case R.id.navigation_share:
toolbar.setTitle("Share");
fragment = new ShareFragment();
loadFragment(fragment);
return true;
case R.id.navigation_more_horiz:
toolbar.setTitle("More");
fragment = new MoreFragment();
loadFragment(fragment);
return true;
}
return false;
}
};
private void loadFragment(Fragment fragment) {
// load fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
What I need to do
this is the logcat, but i am quite new dont know what to do:
2019-07-16 20:57:32.007 7235-7235/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 7235
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.RuntimeException: com.example.myapplication.MainActivity#51ea29f must implement OnFragmentInteractionListener
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
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)
Caused by: java.lang.RuntimeException: com.example.myapplication.MainActivity#51ea29f must implement OnFragmentInteractionListener
at com.example.myapplication.HomeFragment.onAttach(HomeFragment.java:83)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1404)
at android.support.v4.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1195)
at android.support.v4.app.FragmentTransition.calculateFragments(FragmentTransition.java:1078)
at android.support.v4.app.FragmentTransition.startTransitions(FragmentTransition.java:117)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2408)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3273)
at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3229)
at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:201)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:620)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:178)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1334)
at android.app.Activity.performStart(Activity.java:7029)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2741)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
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)
In your MainActivity you must implement interface
public class MainActivity extends AppCompatActivity implement OnFragmentInteractionListener{
}
I'm just trying this library out to see if it fits my needs and so far I have not been able to get it to work. Here is the code
package com.example.user.bottomnavigationbar;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
PieChart pc;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
return true;
// case R.id.navigation_overview:
// Intent intentOverview = new Intent(MainActivity.this, activity_test.class);
// intentOverview.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// MainActivity.this.finish();
// startActivity(intentOverview);
// return true;
case R.id.navigation_expenses:
return true;
case R.id.navigation_reminder:
return true;
case R.id.navigation_income:
return true;
case R.id.navigation_login:
Intent intentLogin = new Intent(MainActivity.this, LoginActivity.class);
intentLogin.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
MainActivity.this.finish();
startActivity(intentLogin);
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
pc = findViewById(R.id.chart);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
ArrayList <PieEntry> pieData = new ArrayList<>();
pieData.add(new PieEntry(10));
pieData.add(new PieEntry(20));
pieData.add(new PieEntry(30));
PieDataSet dataSet = new PieDataSet(pieData, "Survey Results");
PieData data = new PieData(dataSet);
pc.setData(data);
}
public void onBackPressed()
{
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Closing Activity")
.setMessage("Are you sure you want to close this activity?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
And here is the error I get
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.bottomnavigationbar, PID: 4172
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.bottomnavigationbar/com.example.user.bottomnavigationbar.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.github.mikephil.charting.charts.PieChart.setData(com.github.mikephil.charting.data.ChartData)' 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 com.github.mikephil.charting.charts.PieChart.setData(com.github.mikephil.charting.data.ChartData)' on a null object reference
at com.example.user.bottomnavigationbar.MainActivity.onCreate(MainActivity.java:78)
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)
I've searched for a bit and all I've found was that for others, they did not initialize the object hence it throws this error. Now someone did mention that it is possible to create the chart in code and then add it to the activity as the documentation's Getting Started page suggests but I have been unable to get it working. So what gives?
P.S Left in the code for navigation as I'm not sure if it might be the cause of the issue
You are first finding the view and then providing the content view to your activity replace with this code
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pc = findViewById(R.id.chart);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
ArrayList <PieEntry> pieData = new ArrayList<>();
pieData.add(new PieEntry(10));
pieData.add(new PieEntry(20));
pieData.add(new PieEntry(30));
PieDataSet dataSet = new PieDataSet(pieData, "Survey Results");
PieData data = new PieData(dataSet);
pc.setData(data);
}
I followed this tutorial (http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/) for creating member system with login and logout feature. The problem is when logout it doesn't work. I'm creating logout in Fragment Navigation Drawer Menu.
This My Activity.
public class HomeActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = HomeActivity.class.getSimpleName();
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
private SQLiteHandler db;
private SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.title_home);
break;
case 1:
captureImage();
break;
case 2:
fragment = new ReportsFragment();
title = getString(R.string.title_reports);
break;
case 3:
title = getString(R.string.title_settings);
break;
case 4:
logoutUser();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
// Launching the login activity
Intent intent = new Intent(HomeActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
}
And this is error log.
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.company.report.activity.HomeActivity.logoutUser(HomeActivity.java:251)
at com.company.report.activity.HomeActivity.displayView(HomeActivity.java:124)
at com.company.report.activity.HomeActivity.onDrawerItemSelected(HomeActivity.java:99)
at com.company.report.activity.FragmentDrawer$1.onClick(FragmentDrawer.java:79)
at com.company.report.activity.FragmentDrawer$RecyclerTouchListener.onInterceptTouchEvent(FragmentDrawer.java:160)
at android.support.v7.widget.RecyclerView.dispatchOnItemTouchIntercept(RecyclerView.java:1986)
at android.support.v7.widget.RecyclerView.onInterceptTouchEvent(RecyclerView.java:2027)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1629)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:1957)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1726)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:1957)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1726)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:1957)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1726)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:1957)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1726)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:1957)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1726)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:1957)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1726)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:1957)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1726)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1912)
at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1371)
at android.app.Activity.dispatchTouchEvent(Activity.java:2364)
at android.support.v7.internal.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:59)
at android.support.v7.internal.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:59)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1860)
at android.view.View.dispatchPointerEvent(View.java:5721)
at android.view.ViewRootImpl.deliverPointerEvent(ViewRootImpl.java:2890)
at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2466)
at android.view.ViewRootImpl.processInputEvents(ViewRootImpl.java:845)
at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2475)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Looks like sessionand db are never initialized. Initialize it and the error will be gone.
package viewbrosers.mehdi.home.mytestappviewbrowser;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button getAnswer = (Button) findViewById(R.id.getAnswerButton);
getAnswer.setOnClickListener(getAnswerListener);
}
private View.OnClickListener getAnswerListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Random randomnum = new Random();
int numToast = randomnum.nextInt(19);
numToast++;
CharSequence text = "";
switch (numToast) {
case 1:
text = getString(R.string.answer1);
break;
case 2:
text = getString(R.string.answer2);
break;
case 3:
text = getString(R.string.answer3);
break;
case 4:
text = getString(R.string.answer4);
break;
case 5:
text = getString(R.string.answer5);
break;
case 6:
text = getString(R.string.answer6);
break;
case 7:
text = getString(R.string.answer7);
break;
}
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#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);
}
}
My error is:
Unfortunately Application has stopped and 06-05
11:31:44.131 13711-13711/? I/art﹕ Not late-enabling -Xcheck:jni
(already on) 06-05 11:31:44.208 13711-13711/? D/AndroidRuntime﹕
Shutting down VM 06-05 11:31:44.208 13711-13711/? E/AndroidRuntime﹕
FATAL EXCEPTION: main
Process: viewbrosers.mehdi.home.mytestappviewbrowser, PID: 13711
java.lang.RuntimeException: Unable to start activity ComponentInfo{viewbrosers.mehdi.home.mytestappviewbrowser/viewbrosers.mehdi.home.mytestappviewbrowser.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'boolean java.lang.String.equals(java.lang.Object)' on a null object
reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
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:5257)
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 'boolean java.lang.String.equals(java.lang.Object)' on
a null object reference
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:715)
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 com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:378)
at android.app.Activity.setContentView(Activity.java:2145)
at viewbrosers.mehdi.home.mytestappviewbrowser.MainActivity.onCreate(MainActivity.java:23)
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:2390)
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:5257)
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) 06-05
11:31:44.218 13711-13718/? I/art﹕ Debugger is no longer active 06-05
11:32:28.690 13711-13718/viewbrosers.mehdi.home.mytestappviewbrowser
W/art﹕ Suspending all threads took: 12.748ms
Move the creation and initialization of your text variable outside of the onClick() method. Try the following code.
public class MainActivity extends Activity {
CharSequence text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = "";
Button getAnswer = (Button) findViewById(R.id.getAnswerButton);
getAnswer.setOnClickListener(getAnswerListener);
}
private View.OnClickListener getAnswerListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Random randomnum = new Random();
int numToast = randomnum.nextInt(19);
numToast++;
switch (numToast) {
case 1:
text = getString(R.string.answer1);
break;
case 2:
text = getString(R.string.answer2);
break;
case 3:
text = getString(R.string.answer3);
break;
case 4:
text = getString(R.string.answer4);
break;
case 5:
text = getString(R.string.answer5);
break;
case 6:
text = getString(R.string.answer6);
break;
case 7:
text = getString(R.string.answer7);
break;
}
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#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);
}
}
You are somewhere using equals function on string which is null.
Look at exception: 'boolean java.lang.String.equals(java.lang.Object)' on a null object
reference
Try it, may be like this.
public class MainActivity extends Activity implements OnClickListener
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button getAnswer = (Button) findViewById(R.id.getAnswerButton);
getAnswer.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.getAnswerButton:
//Your code
break;
}
}
}