FAB Button Gives Error When Use With Bottom Navigation View - java

I have a bottom navigation view and at the center of bottom navigation view I have a floating action button. I start fragments when click on bottom navigation view items and when click on float action button I start an activity. Fragments are loading correctly but when I click on fab button sometimes it run correctly but sometimes it gives error.
I think, it gives error because I try to load fragment in activity and then I try to open a different activity when a fragment loaded in activity. But I couldn't fix it.
Menu :
https://i.stack.imgur.com/V5auA.jpg
Relative Part of Main Activity :
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private Context context;
private SharedPreference sharedPreference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = MainActivity.this;
sharedPreference = SharedPreference.getInstance(context);
if (getIntent().hasExtra(Constants.SCREEN_TAG)) {
String type = getIntent().getStringExtra(Constants.SCREEN_TAG);
}
FloatingActionButton fabMainActivity = findViewById(R.id.fabMainActivity);
BottomNavigationView bnvMainActivity = findViewById(R.id.bnvMainActivity);
bnvMainActivity.setOnNavigationItemSelectedListener(onNavigationItemSelectedListener);
loadFragment(new DiscoverFragment());
fabMainActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, PostJobActivity.class));
}
});
}
private BottomNavigationView.OnNavigationItemSelectedListener onNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selectedFragment = null;
switch (menuItem.getItemId()){
case R.id.navigation_discover:
selectedFragment = new DiscoverFragment();
break;
case R.id.navigation_nearby:
selectedFragment = new NearbyFragment();
break;
case R.id.empty_menu:
break;
case R.id.navigation_notification:
selectedFragment = new NotificationFragment();
break;
case R.id.navigation_profile:
selectedFragment = new ProfileFragment();
break;
}
loadFragment(selectedFragment);
return true;
}
};
private void loadFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.flMainActivity, fragment);
fragmentTransaction.commit();
}
}
Main Activity XML:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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=".Activity.MainActivity"
android:background="#color/app_background">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="#+id/rlTopBackgroundMainActivity"
android:layout_width="match_parent"
android:layout_height="75dp"
android:background="#drawable/top_background"
android:layout_gravity="top">
<ImageView
android:id="#+id/ivLogoWithTextMainActivity"
android:layout_width="142dp"
android:layout_height="41dp"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="20dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="23dp"
android:layout_marginEnd="247dp"
android:layout_marginRight="247dp"
android:layout_marginBottom="17dp"
android:layout_centerVertical="true"
android:contentDescription="#string/terms_activity_logo_with_text"
android:src="#drawable/logo_with_text" />
<ImageView
android:id="#+id/ivMessagesMainActivity"
android:layout_width="33dp"
android:layout_height="41dp"
android:src="#drawable/message_icon"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_marginRight="20dp"
android:layout_marginEnd="20dp"
android:contentDescription="#string/messages_icon" />
</RelativeLayout>
<FrameLayout
android:id="#+id/flMainActivity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/rlTopBackgroundMainActivity" />
</RelativeLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bnvMainActivity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:layout_gravity="bottom"
app:itemIconTint="#color/bottom_menu_color"
app:menu="#menu/bottom_navigation_menu"
app:labelVisibilityMode="unlabeled" />
<com.google.android.material.bottomappbar.BottomAppBar
android:id="#+id/bapMainActivity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
app:itemIconTint="#color/bottom_menu_color"
app:labelVisibilityMode="unlabeled"
app:fabAlignmentMode="center"
app:fabCradleMargin="7dp"
app:elevation="0dp"
android:layout_gravity="bottom"/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fabMainActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="#color/purple_2"
app:tint="#android:color/white"
android:src="#drawable/post_job_icon"
app:layout_anchor="#id/bapMainActivity"
app:maxImageSize="35dp" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Relative Part of Post Job Activity : (Post Job Activity also in frame layout.)
public class PostJobActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_job);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
context = PostJobActivity.this;
btnBackToMainActivityPostJobActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(PostJobActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
});
}
#Override
public void onBackPressed() {
Intent intent = new Intent(PostJobActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
}
Error Message:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
at androidx.fragment.app.FragmentTransaction.doAddOp(FragmentTransaction.java:161)
at androidx.fragment.app.BackStackRecord.doAddOp(BackStackRecord.java:179)
at androidx.fragment.app.FragmentTransaction.replace(FragmentTransaction.java:225)
at androidx.fragment.app.FragmentTransaction.replace(FragmentTransaction.java:200)
at dk.lejekspert.lejekspertrekrutter.Activity.MainActivity.loadFragment(MainActivity.java:133)
at dk.lejekspert.lejekspertrekrutter.Activity.MainActivity.access$000(MainActivity.java:58)
at dk.lejekspert.lejekspertrekrutter.Activity.MainActivity$3.onNavigationItemSelected(MainActivity.java:126)
at com.google.android.material.bottomnavigation.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:243)
at androidx.appcompat.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:840)
at androidx.appcompat.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)
at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:991)
at com.google.android.material.bottomnavigation.BottomNavigationMenuView$1.onClick(BottomNavigationMenuView.java:124)
at android.view.View.performClick(View.java:5723)
at android.view.View$PerformClick.run(View.java:22689)
at android.os.Handler.handleCallback(Handler.java:836)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6364)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
Any idea to solve this problem?
Thanks.
Edit : I added a sentence to my bottom_navigation_menu.xml file to make not enable menu item below fab button.
<item
android:id="#+id/empty_menu"
app:showAsAction="always"
android:enabled="false"
android:title="#string/nearby" />
Also this code part is not necessary anymore.
case R.id.empty_menu:
break;

The issue happens when you call fragmentTransaction.replace(R.id.flMainActivity, fragment); with fragment = null.
Check the onNavigationItemSelected.
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selectedFragment = null;
switch (menuItem.getItemId()){
//...
case R.id.empty_menu:
break; // <-- this case
}
loadFragment(selectedFragment);
return true;
In this case the selectedFragment is null.
Checking the screen in the question it seems that you are using in the BottomNavigationView a menuItem without icon exactly behind the FAB.

Related

OnClickListener Null Object Reference

I know this issue has been put out there 100 times, but nothing I've seen solves this. I have a button in a layout called fragment_main which is shown to another layout: activity_main. That button opens a fragment called AddEditFragment, which allows users to add info to a form that then spits it into a recyclerview(fragment_main) that is shown in MainActivity.
I have both layouts due to having a navigation drawer in a linearlayout in activity_main and the recyclerview and button in fragment_main constraintlayout. However I have onDelete/Edit/Save methods already up and going in MainActivity, so it only makes sense to me to put the button onClickListener there as well. Except since the button isn't in the main layout, activity_main, I get a fatal null object exception.
Even though fragment_main is shown in activity_main is there a way around this so the OnClick method can be put into MainActivity for a button in a linked layout?
MainActivity.java
public class MainActivity extends AppCompatActivity implements RecyclerViewAdapter.OnVehicleClickListener,
FragmentAddEdit.OnSaveClicked,
NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
// Launcher view
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FragmentMainActivity()).commit();
navigationView.setCheckedItem(R.id.nav_garage);
}
Button button_add = findViewById(R.id.button_add);
button_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AddEditRequest(null);
}
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_garage:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FragmentMainActivity()).commit();
break;
case R.id.nav_history:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FragmentHistory()).commit();
break;
case R.id.nav_upcoming:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FragmentUpcoming()).commit();
break;
case R.id.nav_about:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FragmentAbout()).commit();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onSaveClicked() {
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment AddEditFragment = fragmentManager.findFragmentById(R.id.fragment_container);
if (AddEditFragment != null) {
getSupportFragmentManager().beginTransaction()
.remove(AddEditFragment)
.commit();
}
}
public void onEditClick(#NonNull Vehicle vehicle) {
AddEditRequest(vehicle);
}
#Override
public void onDeleteClick(#NonNull Vehicle vehicle) {
}
private void AddEditRequest(Vehicle vehicle) {
Intent detailIntent = new Intent(this, FragmentAddEdit.class);
if (vehicle != null) {
detailIntent.putExtra(Vehicle.class.getSimpleName(), vehicle);
startActivity(detailIntent);
}
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
activity_main.xml
<?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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".com.carupkeep.MainActivity"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer_menu" />
</android.support.v4.widget.DrawerLayout>
fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".com.carupkeep.FragmentMainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:id="#+id/no_vehicles"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="#string/no_vehicle_message"
android:textSize="22sp"
android:textStyle="normal|bold"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintTop_creator="1"/>
<Button
android:id="#+id/button_add"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:drawableLeft="#drawable/ic_add"
android:drawablePadding="10dp"
android:drawableTint="#color/colorAdd"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="#string/addVehicle"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/vehicle_list" />
<android.support.v7.widget.RecyclerView
android:id="#+id/vehicle_list"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/no_vehicles"
app:layout_constraintVertical_bias="0.0" />
</android.support.constraint.ConstraintLayout>
UPDATE
I got close but still feel so far. I've given up on trying to keep it in MainActivity and put it in FragmentMainAcitivity as suggested. Except now I have 2 can't resolve errors. The first being on view in view.findViewById button initialization AND on fragment_container in the callback method. Any thoughts on how to resolve this?
public class FragmentMainActivity extends Fragment {
Button button_add = view.findViewById(R.id.button_add);
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
button_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fragmentManager = getFragmentManager();
Fragment AddEditFragment = fragmentManager.findFragmentById(R.id.fragment_container);
getFragmentManager().beginTransaction().replace(fragment_container, AddEditFragment).commit();
}
});
}
}
easier way to do it is to put
onClick="AddEditRequestView"
in your fragment_main.xml
so it will be
<Button
android:id="#+id/button_add"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:drawableLeft="#drawable/ic_add"
android:drawablePadding="10dp"
android:drawableTint="#color/colorAdd"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="#string/addVehicle"
android:onClick="AddEditRequestView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/vehicle_list" />
and in your MainActivity.java
add this method
public void AddEditRequestView(View viewc){
AddEditRequest(null);
}
and delete these code from your activity
Button button_add = findViewById(R.id.button_add);
button_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AddEditRequest(null);
}
});

CollapsingToolbarLayout and toolbar action buttons

I would appreciate if someone could give me some pointers to solve my latest issue.
I have an activity with a CollapsingToolbarLayout. In an un-collapsed state Im unable to get the buttons to work. I do not know how to fix this issue. I have searched on stackoverflow before posting this, but I did not find any helpful tips.
Im posting here hoping for an answer
Thanks
This is my code!
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
android:background="?attr/app_background"
android:fitsSystemWindows="true"
tools:context="com.company.walt.activities.photos.PhotosAAAActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/backdrop"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="#drawable/ip_photo_header"
app:layout_collapseMode="parallax"
app:layout_collapseParallaxMultiplier="0.7" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/love_music"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="AAAAAA"
android:textColor="#android:color/white"
android:textSize="#dimen/ssi_txt_40sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BBBBBBBB"
android:textColor="#android:color/white"
android:textSize="#dimen/ssi_txt_20sp" />
</LinearLayout>
</RelativeLayout>
<android.support.v7.widget.Toolbar
android:id="#+id/main_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_marginTop="#dimen/ssi_24dp"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
</android.support.design.widget.CollapsingToolbarLayout>
<android.support.design.widget.TabLayout
android:id="#+id/tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
app:tabIndicatorColor="#color/white"
app:tabSelectedTextColor="#color/white"
app:tabTextColor="#color/white" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.design.widget.CoordinatorLayout>
PhotosAAAActivity.java
public class PhotosAAAActivity extends AppCompatActivity {
//region WIDGETS
private AppBarLayout bAppBarLayout;
private CollapsingToolbarLayout bCollapsingToolbar;
private Toolbar bToolbar;
private TabLayout mTabLayout;
//endregion
//region VARS
private ViewPager mViewPager;
private PhotosPagerAdapter mPhotosPagerAdapter;
SharedPreferencesManager mSharedPreferences;
//endregion
/* ******************************************************************************************* */
//region THE ONCREATE
#Override
protected void onCreate(Bundle savedInstanceState)
{
//region Load Preferences
mSharedPreferences = new SharedPreferencesManager(this);
//endregion
//region Switching theme style
if (mSharedPreferences.getNightModeState() == true) {
setTheme(R.style.NightTheme);
} else {
setTheme(R.style.LightTheme);
}
//endregion
//region Super onCreate
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photos);
//endregion
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window w = getWindow(); // in Activity's onCreate() for instance
w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
//region Calling Methods
setUpCollapsingToolbar();
setUpToolbar();
setViewPager();
//endregion
}
//endregion
private void setUpCollapsingToolbar() {
bCollapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
bCollapsingToolbar.setCollapsedTitleTextColor(getResources().getColor(R.color.white));
bAppBarLayout = (AppBarLayout) findViewById(R.id.appbar);
bAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = false;
int scrollRange = -1;
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
bCollapsingToolbar.setTitle("Post photos");
isShow = true;
} else if (isShow) {
bCollapsingToolbar.setTitle("");
isShow = false;
}
}
});
}
/* ******************************************************************************************* */
//region Used to create the toolbar on top
private void setUpToolbar() {
bToolbar = (Toolbar) findViewById(R.id.main_toolbar);
setSupportActionBar(bToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("");
}
//endregion
/* ******************************************************************************************* */
//region Used to create the tab layout
private void setViewPager() {
mViewPager = (ViewPager) findViewById(R.id.pager);
mPhotosPagerAdapter = new PhotosPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mPhotosPagerAdapter);
mTabLayout = (TabLayout) findViewById(R.id.tab);
mTabLayout.setupWithViewPager(mViewPager);
}
//endregion
/* ******************************************************************************************* */
//region MATERIAL DRAWER
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.photo_category, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case android.R.id.home:
finish();
//Toast.makeText(PhotosAAAActivity.this, "GO BACK", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//endregion
}
UPDATE! - 2018-01-13
I figured out what is cousing the the issue but I still dont know fix this
The problem is that if I remove this code then the tabs won't show up, so it feels as if this ***** with me
The issue
//region Used to create the tab layout
private void setViewPager() {
ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);
mPhotosPagerAdapter = new PhotosPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mPhotosPagerAdapter);
mTabLayout = (TabLayout) findViewById(R.id.tab);
mTabLayout.setupWithViewPager(mViewPager);
}
//endregion
There are two issues with your code, both related to the buttons you're trying to get to work.
First, with the home button (or the up button you need to activate it with actionBar before handling events with it. Add the following:
getSupportActionBar().setHomeButtonEnabled(true);
inside your setupToolbar method. You can now access the button using the code you've written under the case android.R.id.home:.
The second button has the same issue. You haven't added any logic to handle the button click. Let's say your button on the right has id="#+id/more". Now to define an action for it, you need to put a case with its id inside switch like,
case R.id.more:
//The action needed for the button
break;
try this.
in your activity
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
}
in your xml
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
//for menu you should give ids to that menu items in your menu file
//R.menu.photo_category and after that if you have 2 menu items
// you have to write listener for every single items for onClick like.
case R.id.item1:
finish();
break;
case R.id.item2:
finish();
break;
}
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();
if (id == android.R.id.home) {
finish();
}
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
Back Button on click listener.

Android NullPointerException Toolbar.setNavigationOnClickListener null object reference

Here is error
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.support.v7.widget.Toolbar.setNavigationOnClickListener(android.view.View$
OnClickListener)' on a null object reference
it happen on
toolBar.setNavigationOnClickListener(new View.OnClickListener()
imageView.setOnClickListener(new View.OnClickListener()
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener()
have the same problem "null object reference".
my team separate file to fragment and all action listener in MainActivity is broke down but we want to separate to fragment like this, but I can't find why separate file to fragment it will null object reference
Here XML fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layoutDirection="rtl"><!--set tool bar right to left set drawer to right-->
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="0dp"
android:layout_height="56dp"
android:background="#color/colorPrimary"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
tools:layout_editor_absoluteY="0dp"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<ImageView
android:id="#+id/pamba_icon_id"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="0dp"
app:layout_constraintLeft_toLeftOf="#+id/toolbar"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/pambaicon"
app:layout_constraintBottom_toBottomOf="#+id/toolbar"
android:layout_marginBottom="0dp"
app:layout_constraintVertical_bias="0.0" />
<ImageView
android:id="#+id/filter_icon_id"
android:clickable="true"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginBottom="8dp"
android:layout_marginRight="48dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="#+id/toolbar"
app:layout_constraintRight_toRightOf="#+id/toolbar"
app:layout_constraintTop_toTopOf="#+id/toolbar"
app:srcCompat="#drawable/filter"
app:layout_constraintVertical_bias="0.533" />
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewPaper_id"
android:layout_below="#id/toolbar">
</android.support.v4.view.ViewPager>
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/bottomNavigation_id"
android:layout_gravity="bottom"
android:background="?android:attr/windowBackground"
app:menu="#menu/bottom_navigation_menu"
app:theme="#style/BottomNavigationTheme"
app:itemBackground="#color/colorGray"/>
</android.support.design.widget.CoordinatorLayout>
</android.support.constraint.ConstraintLayout>
Here activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layoutDirection="rtl"><!--set tool bar right to left set drawer to right-->
<android.support.constraint.ConstraintLayout
android:id="#+id/contentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.constraint.ConstraintLayout>
Here MainFragment
import...
public class MainFragment extends Fragment {
public MainFragment() {
super();
}
public static MainFragment newInstance() {
MainFragment fragment = new MainFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
initInstances(rootView);
return rootView;
}
private void initInstances(View rootView) {
// Init 'View' instance(s) with rootView.findViewById here
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
/*
* Save Instance State Here
*/
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save Instance State here
}
/*
* Restore Instance State Here
*/
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
// Restore Instance State here
}
}
}
and MainActivity
import...
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
Toolbar toolBar;
DrawerLayout drawerLayout;
NavigationView navigationView;
ImageView imageView;
BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_drawer);
setTitle(R.string.title);
drawerLayout = (DrawerLayout) findViewById(R.id.drawe_layout);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
imageView = (ImageView) findViewById(R.id.filter_icon_id);
navigationView.setNavigationItemSelectedListener(this);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolBar, R.string.open_drawer, R.string.close_drawer);
drawerLayout.setDrawerListener(toggle);
toggle.syncState();
// set own toolbar
toolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolBar);
toolBar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
drawerLayout.closeDrawer(Gravity.RIGHT);
} else {
drawerLayout.openDrawer(Gravity.RIGHT);
}
}
});
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "filter click", Toast.LENGTH_SHORT).show();
}
});
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigation_id);
// select item from bottom navigation
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.firstpage_id:
Toast.makeText(getApplicationContext(), "home", Toast.LENGTH_SHORT).show();
break;
case R.id.offergape_id:
Toast.makeText(getApplicationContext(), "offer", Toast.LENGTH_SHORT).show();
break;
case R.id.needpage_id:
Toast.makeText(getApplicationContext(), "need", Toast.LENGTH_SHORT).show();
break;
case R.id.searchpage_id:
Toast.makeText(getApplicationContext(), "search", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
});
}
//close drawer when click back
#Override
public void onBackPressed() {
if(drawerLayout.isDrawerOpen(GravityCompat.END)){
drawerLayout.closeDrawer(GravityCompat.END);
}else {
super.onBackPressed();
}
}
// select item from drawer
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.account_detail_id:
Toast.makeText(getApplicationContext(), "account", Toast.LENGTH_SHORT).show();
break;
case R.id.trip_detail_id:
Toast.makeText(getApplicationContext(), "detail", Toast.LENGTH_SHORT).show();
break;
case R.id.mail_id:
Toast.makeText(getApplicationContext(), "mail", Toast.LENGTH_SHORT).show();
break;
case R.id.logout_id:
Toast.makeText(getApplicationContext(), "logout", Toast.LENGTH_SHORT).show();
break;
}
drawerLayout.closeDrawer(GravityCompat.END);
return true;
}
}
edit add navigation_drawer.xml
<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawe_layout"
android:fitsSystemWindows="true"
tools:openDrawer="end">
<!--set drawer open from right-->
<include layout="#layout/activity_main"/>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/navigation_view"
android:background="#color/colorGray"
android:fitsSystemWindows="true"
app:headerLayout="#layout/navigation_header"
app:menu="#menu/navigation_menu"
app:theme="#style/NavigationDrawerStyle"
android:layout_gravity="end"/>
<!--set drawer open from right-->
</android.support.v4.widget.DrawerLayout>
Your setContentView in onCreate is setting it to R.layout.navigation_drawer. You didn't provide an example of that, but instead provided an example of R.layout.fragment_main. I'm thinking you want that one to be your layout instead. So in onCreate in your activity set your content view to that layout instead:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
... // The rest of your code here
}

Cannot change TextView between two activities?

I'm attempting to change a TextView between two activities. The problem is, when I change the text in the other activity from main activity, it works fine, the screen goes to the other activity and the text has been changed. However I have another button which takes me to the other activity from Main, but the newly updated text has disappeared when I press it. Any help?
MyActivity.java
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
final EditText et = (EditText) findViewById(R.id.editText1);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MyActivity.this, Second.class);
intent.putExtra("thetext", et.getText().toString());
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onClickGoToActivity(View view) {
setContentView(R.layout.second);
}
}
Second.java
public class Second extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(getIntent().getExtras().getString("thetext"));
}
}
activity_my.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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MyActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editText1"
android:layout_centerHorizontal="true"
android:hint="Change me"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Add text in other activity"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/go_to_activity_button"
android:text="Go to activity"
android:layout_centerHorizontal="true"
android:layout_marginTop="200dp"
android:onClick="onClickGoToActivity"/>
</RelativeLayout>
second.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView1"
android:textSize="30sp"/>
</LinearLayout>
AndroidManifest.xml
Second class activity:
I presume the problem lies here:
public void onClickGoToActivity(View view) {
setContentView(R.layout.second);
}
where the newly changed TextView is being reset back to the original layout (where the TextView is empty with no text). I'm not sure how to fix this as I'm new to Android.
Thank you.
changing content view of activity is a bad idea to start another activity. Simply you just do the same thing which is
public void onClickGoToActivity(View view) {
Intent intent = new Intent(MyActivity.this, Second.class);
intent.putExtra("thetext", et.getText().toString());
startActivity(intent);
}

Android - View has no ID - why?

I have a class that is supposed to call another activity depending on which button has been clicked. This is done by checking the available IDs.
My problem is: The view that is passed to my class has no id, or rather, its value is NO_ID. What puzzles me is that the view, which is a button, does have an ID.
public class StrengthOrganizer extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_strength_organizer);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_strength_organizer, menu);
return true;
}
public void notifyActivity(View view) {
Intent intent = null;
int id = view.getId();
switch(id){
case R.id.button_log_book_launcher:
intent = new Intent(this, LogBook.class);
break;
case R.id.button_programming_launcher:
intent = new Intent(this, Programming.class);
break;
case R.id.button_visualizer_launcher:
intent = new Intent(this, Visualizer.class);
break;
default:
return;
}
startActivity(intent);
}
}
The corresponding XML file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical" >
<Button android:name="#+id/button_log_book_launcher"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:text="#string/button_log_book_launcher"
android:onClick="notifyActivity" />
<Button android:name="#+id/button_programming_launcher"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:text="#string/button_programming_launcher"
android:onClick="notifyActivity" />
<Button android:name="#+id/button_visualizer_launcher"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:text="#string/button_visualizer_launcher"
android:onClick="notifyActivity" />
</LinearLayout>
Why does the view object have no ID if it's been give in the XML file?
You used android:name instead of android:id in your XML to assign the ids. Use the latter instead.

Categories

Resources