ActionBar hidden when starting fragment - java

I have an activity that correctly displays my ActionBar and it's items, however when I try to add a fragment to that activity the ActionBar disappears when that fragment is launched, or if I try to include the ActionBar it shows the bar but no title or MenuOptions.
Want I am trying to achieve is one activity, with the same ActionBar for all fragments, unless specified otherwise.
MainActivity.Java
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final HomeFragment homeFragment = new HomeFragment();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
if (savedInstanceState == null) {
getFragmentManager()
.beginTransaction()
.add(R.id.main_container, homeFragment)
.addToBackStack(null)
.commit();
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activity_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;
} else if (id == R.id.search_mag_icon){
// Open intent here
Intent i = new Intent(getApplicationContext(), SearchActivity.class);
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
HomeFragment.java
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<!-- Book icon and text -->
<ImageView
android:id="#+id/bookIcon"
android:layout_width="100dip"
android:layout_height="100dip"
android:layout_marginLeft="50dip"
android:layout_marginTop="110dip"
android:src="#drawable/book" />
<TextView
android:id="#+id/bookLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/bookIcon"
android:layout_marginLeft="20dip"
android:text="#string/bookLabel"
android:textColor="#color/colorAlt"
android:textStyle="bold" />
<!-- Barcode icon and text -->
<ImageView
android:id="#+id/barcodeIcon"
android:layout_width="95dip"
android:layout_height="95dip"
android:layout_marginLeft="260dip"
android:layout_marginTop="120dip"
android:src="#drawable/barcode" />
<TextView
android:id="#+id/barcodeLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/barcodeIcon"
android:layout_marginLeft="260dip"
android:paddingTop="5dip"
android:text="#string/barcodeLabel"
android:textColor="#color/colorAlt"
android:textStyle="bold" />
<!-- Message icon and text -->
<ImageView
android:id="#+id/messageIcon"
android:layout_width="100dip"
android:layout_height="100dip"
android:layout_marginLeft="50dip"
android:layout_marginTop="350dip"
android:src="#drawable/email" />
<TextView
android:id="#+id/messageLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/messageIcon"
android:layout_marginLeft="55dip"
android:text="#string/messageLabel"
android:textColor="#color/colorAlt"
android:textStyle="bold" />
<!-- List icon and text -->
<ImageView
android:id="#+id/listIcon"
android:layout_width="95dip"
android:layout_height="95dip"
android:layout_marginLeft="260dip"
android:layout_marginTop="350dip"
android:src="#drawable/list" />
<TextView
android:id="#+id/listLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/listIcon"
android:layout_marginLeft="273dip"
android:paddingTop="5dip"
android:text="#string/listLabel"
android:textColor="#color/colorAlt"
android:textStyle="bold" />
</RelativeLayout>
</FrameLayout>
activity_main
<?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:background="#FFF"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<include
android:layout_width="match_parent"
android:layout_height="match_parent"
layout="#layout/app_bar_main" />
<FrameLayout
android:id="#+id/main_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
</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"
android:fitsSystemWindows="true"
android:background="#color/colorPrimaryDark"
app:itemTextColor="#FFF"
app:itemIconTint="#FFF"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android">
<include layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- Book icon and text -->
<ImageView
android:id="#+id/bookIcon"
android:src="#drawable/book"
android:layout_width="100dip"
android:layout_height="100dip"
android:layout_marginLeft="50dip"
android:layout_marginTop = "110dip"
/>
<TextView
android:id="#+id/bookLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/bookLabel"
android:textColor="#color/colorAlt"
android:textStyle="bold"
android:layout_marginLeft="20dip"
android:layout_below="#+id/bookIcon" />
<!-- Barcode icon and text -->
<ImageView
android:id="#+id/barcodeIcon"
android:src="#drawable/barcode"
android:layout_width="95dip"
android:layout_height="95dip"
android:layout_marginLeft="260dip"
android:layout_marginTop = "120dip"
/>
<TextView
android:id="#+id/barcodeLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/barcodeLabel"
android:textColor="#color/colorAlt"
android:textStyle="bold"
android:layout_below="#+id/barcodeIcon"
android:paddingTop="5dip"
android:layout_marginLeft="260dip"/>
<!-- Message icon and text -->
<ImageView
android:id="#+id/messageIcon"
android:src="#drawable/email"
android:layout_width="100dip"
android:layout_height="100dip"
android:layout_marginLeft="50dip"
android:layout_marginTop = "350dip"
/>
<TextView
android:id="#+id/messageLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/messageLabel"
android:textColor="#color/colorAlt"
android:textStyle="bold"
android:layout_marginLeft="55dip"
android:layout_below="#+id/messageIcon" />
<!-- List icon and text -->
<ImageView
android:id="#+id/listIcon"
android:src="#drawable/list"
android:layout_width="95dip"
android:layout_height="95dip"
android:layout_marginLeft="260dip"
android:layout_marginTop = "350dip"
/>
<TextView
android:id="#+id/listLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/listLabel"
android:textColor="#color/colorAlt"
android:textStyle="bold"
android:layout_below="#+id/listIcon"
android:paddingTop="5dip"
android:layout_marginLeft="273dip"/>
</RelativeLayout>
Thank you for any help in advance.

modify layout
Put you ToolBar inside LinearLayout and Change Fragment with FrameLayout
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<include
android:layout_width="match_parent"
android:layout_height="match_parent"
layout="#layout/app_bar_main" />
<FrameLayout
android:id="#+id/main_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
</LinearLayout>
call Fragment from Activity
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.replace(R.id.main_container,homeFragment));
fragmentTransaction.commit();

Related

Why My hamburger icon in android app is not working it is not opening the navigation menu?

I am working on an app but there is a problem with hamburger icon as it is not working. It is not opening the navigation menu when i am clicking on it. what is the problem please tell me? I am trying to solve it but dont know what is the problem with it. I am new to code please help me.
Here is my fragment code
public class HomeFragment extends Fragment{
NavigationView navigationView;
ActionBarDrawerToggle toggle;
DrawerLayout drawerLayout;
Toolbar toolbar;
private int[] images;
private SliderAdapter sliderAdapter;
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
navigationView = view.findViewById(R.id.navmenu);
drawerLayout = view.findViewById(R.id.drawerlayout);
toolbar = view.findViewById(R.id.toolbar);
ActionBar mActionBar;
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
Objects.requireNonNull(((AppCompatActivity) getActivity()).getSupportActionBar()).setTitle("");
toggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, R.string.open, R.string.close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((AppCompatActivity) getActivity()).getSupportActionBar().setHomeAsUpIndicator(R.drawable.menu3);
return view;
}
}
Here is my XML file
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.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:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawerlayout"
tools:openDrawer="start"
android:background="#color/white"
tools:context=".HomeFragment">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/reddark"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/Theme.AppCompat.Light">
<ImageView
android:layout_width="150dp"
android:layout_height="50dp"
android:layout_gravity="center_horizontal"
android:src="#drawable/backsssososos" />
</androidx.appcompat.widget.Toolbar>
<RelativeLayout
android:id="#+id/search_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:background="#color/reddark"
android:padding="10dp"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<EditText
android:id="#+id/searchbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/searchbardesign"
android:backgroundTint="#F8F8F8"
android:drawableLeft="#android:drawable/ic_menu_camera"
android:drawableRight="#android:drawable/ic_menu_search"
android:drawablePadding="22dp"
android:gravity="left|center"
android:hint="Enter City,Colony name..."
android:imeOptions="actionSearch"
android:inputType="text"
android:maxLines="1"
android:padding="10dp"
android:textColor="#color/black"
android:textColorHint="#android:color/darker_gray"
android:textSize="16dp" />
</RelativeLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:id="#+id/nestedScrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clipToPadding="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:orientation="vertical">
<com.smarteist.autoimageslider.SliderView
android:id="#+id/imageSlider"
android:layout_width="match_parent"
android:layout_height="300dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:sliderAnimationDuration="600"
app:sliderAutoCycleDirection="back_and_forth"
app:sliderAutoCycleEnabled="true"
app:sliderIndicatorAnimationDuration="600"
app:sliderIndicatorGravity="center_horizontal|bottom"
app:sliderIndicatorMargin="15dp"
app:sliderIndicatorOrientation="horizontal"
app:sliderIndicatorPadding="3dp"
app:sliderIndicatorRadius="2dp"
app:sliderIndicatorSelectedColor="#5A5A5A"
app:sliderIndicatorUnselectedColor="#FFF"
app:sliderScrollTimeInSec="1"
app:sliderStartAutoCycle="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/text_file_2"></TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/text_file_2">
</TextView>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/navmenu"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:itemIconTint="#color/black"
android:theme="#style/NavigationDrawerStyle"
app:headerLayout="#layout/navheader"
app:itemTextColor="#151515"
app:menu="#menu/navigationmenu">
</com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>
you must attach toolbar in ActionBarDrawerToggle
mDrawerToogle = new ActionBarDrawerToggle(this, drawer,toolbar,R.string.navigation_drawer_open, R.string.navigation_drawer_close);
bar.setHomeButtonEnabled(true);
bar.setDisplayHomeAsUpEnabled(true);
mDrawerToogle.syncState();
drawer.setDrawerListener(mDrawerToogle);
you have to handle this action by yourself
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
drawerLayout.openDrawer(Gravity.LEFT);
return true;
}
return super.onOptionsItemSelected(item);
}
also syncState() call should be placed in onPostCreate or even in onResume
btw. your empty constructor should at least call super();

How to set title and back arrow button in toolbar for each fragment?

//Here is my fragment
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white">
<RelativeLayout
android:id="#+id/background"
android:layout_width="match_parent"
android:layout_height="#dimen/_420sdp"
android:background="#EAEAEA"
>
<RelativeLayout
android:id="#+id/home_bg_layout"
android:layout_width="match_parent"
android:layout_height="#dimen/_400sdp"
android:background="#drawable/sama">
<Button
android:id="#+id/bookAppointmentBtn"
android:layout_width="match_parent"
android:layout_height="#dimen/_55sdp"
android:layout_marginLeft="#dimen/_30sdp"
android:layout_marginRight="#dimen/_30sdp"
android:fontFamily="#string/roboto_light"
android:textSize="#dimen/_20sdp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="#dimen/_10sdp"
android:background="#drawable/book_appointmentbg"
android:textColor="#color/white"
android:text="#string/bookappointment" />
</RelativeLayout>
</RelativeLayout>
<Button
android:id="#+id/ContactNoBtn"
android:layout_width="match_parent"
android:layout_height="#dimen/_46sdp"
android:text="#string/shop_number"
android:textColor="#ffffff"
android:textSize="#dimen/_25sdp"
android:layout_below="#+id/discountsTv"
android:textAllCaps="false"
android:layout_marginRight="#dimen/_30sdp"
android:layout_marginTop="#dimen/_5sdp"
android:layout_marginLeft="#dimen/_30sdp"
android:background="#drawable/black_background"/>
<LinearLayout
android:id="#+id/servicesLinearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:layout_marginLeft="#dimen/_20sdp"
android:layout_marginRight="#dimen/_20sdp"
android:orientation="horizontal"
android:layout_below="#+id/servicesupperview"
>
<LinearLayout
android:id="#+id/menLayout"
android:layout_width="#dimen/_108sdp"
android:layout_height="#dimen/_27sdp"
android:layout_margin="#dimen/_10sdp"
android:layout_weight="1"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#string/roboto_medium"
android:textColor="#535353"
android:layout_marginStart="#dimen/_17sdp"
android:layout_marginTop="#dimen/_5sdp"
android:textSize="#dimen/_12sdp"
android:text="#string/mens"
/>
</LinearLayout>
<LinearLayout
android:id="#+id/womenLayout"
android:layout_width="#dimen/_108sdp"
android:layout_height="#dimen/_27sdp"
android:layout_margin="#dimen/_10sdp"
android:layout_weight="1"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#string/roboto_medium"
android:textSize="#dimen/_12sdp"
android:layout_marginStart="#dimen/_10sdp"
android:layout_marginTop="#dimen/_5sdp"
android:textColor="#535353"
android:text="#string/womens"
/>
</LinearLayout>
<LinearLayout
android:id="#+id/childrenLayout"
android:layout_width="#dimen/_108sdp"
android:layout_height="#dimen/_27sdp"
android:layout_margin="#dimen/_10sdp"
android:layout_weight="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/_12sdp"
android:fontFamily="#string/roboto_medium"
android:textColor="#535353"
android:layout_marginStart="#dimen/_20sdp"
android:layout_marginTop="#dimen/_5sdp"
android:text="#string/children_caps"
/>
</LinearLayout>
</LinearLayout>
</ScrollView>
</RelativeLayout>
I am having toolbar in MainActivity. This is my fragment i want to set title, image and back button inside the toolbar. Here i am using bottom navigation to change the fragments. Each and every fragment i want to set different title and image. I have to set title as center of the toolbar and back button as right corner of the toolbar.
In your MainActivity add these lines in OnCreate() method
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle("My Activity Title");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
To use Back arrow you can write this code outside onCreate()
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
Toast.makeText(this, "Back button pressed", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
In you fragment you can change title of Toolbar
getActivity().setTitle("My fragment Title");
You can Create custom Toolbar with ImageView and TextView with your arrow .
include_tool_bar.xml
<com.mastercard.wallet.ui.widget.CustomTextView
android:id="#+id/toolbar_title"
style="#style/Toolbar.TitleText"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical|left"
android:textSize="#dimen/px_48"
app:fontName="InterStateLight"
customviews:fontName="InterStateLight" />
<ImageView
android:id="#+id/toolbar_logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:contentDescription="#string/adaCitiPayLogoText"
android:src="#drawable/ab_logo"
android:visibility="gone" />
And Add Toolbar
Toolbar toolbar = (Toolbar) appCompatActivity.findViewById(R.id.toolbar);
ImageView logo = (ImageView) toolbar.findViewById(R.id.toolbar_logo);
CustomTextView textView = (CustomTextView) toolbar.findViewById(R.id.toolbar_title);
logo.setVisibility(View.VISIBLE);
logo.setImageResource(logoResourceId);
textView.setVisibility(View.GONE);
appCompatActivity.setSupportActionBar(toolbar);
appCompatActivity.getSupportActionBar().setDisplayShowTitleEnabled(false);
title of the toolbar can be changed from fragment calling this in onActivityCreated
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
((MainActivity) getActivity()).getSupportActionBar().setTitle(getString(R.string.menu_about_us));
((MainActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((MainActivity) getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);
}
in your activity make sure to add a toolbar like this.
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"/>
and set it in your activity
setSupportActionBar(findViewById(R.id.toolbar));
and for the back press just add a listener and do the needful.
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_action_back));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// pop up fragment or take another action
}
});

Android Object coming back null after onCreate

Android newbie here.
I'm trying to set an onClick event on a LinearLayout. But I keep getting the error
Attempt to invoke virtual method 'void android.widget.LinearLayout.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
Which, if I understand correctly means that the reference is null. Which doesn't make sense to me since I'm calling it after onCreate
Here's my code, anybody have any clues what I'm doing wrong?
MainActivity - The place with HERE! is where the crash is occuring
package ...
import ...
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
final NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
setNavHeaderOnClickAction();
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// ...
}
public void setNavHeaderOnClickAction(){
// HERE! Here's the problemsome area
LinearLayout navHeaderUser = (LinearLayout) findViewById(R.id.nav_header_user);
navHeaderUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Intent myIntent = new Intent(MainActivity.this, UserProfile.class);
// MainActivity.this.startActivity(myIntent);
// DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// drawer.closeDrawer(GravityCompat.START);
}
});
}
}
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:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
app_bar_main.xml
<?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"
tools:context="com.example.trevorwood.biggles.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include android:id="#+id/main_content" layout="#layout/content_blank"/>
<android.support.design.widget.AppBarLayout
android:id="#+id/search_button"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_gravity="top|end"
android:layout_margin="10dp"
android:background="#android:drawable/ic_menu_search">
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
nav_header_main.xml (layout) included in activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="120dp"
android:background="#drawable/side_nav_bar"
android:gravity="center"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<LinearLayout
android:id="#+id/nav_header_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal"
android:clickable="true">
<ImageView
android:id="#+id/imageView"
android:layout_width="60dp"
android:layout_height="60dp"
android:paddingTop="#dimen/nav_header_vertical_spacing"
app:srcCompat="#android:drawable/sym_def_app_icon"
android:clickable="false"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:clickable="false">
<TextView
android:id="#+id/textView"
android:layout_width="303dp"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:text="JohnSmith007"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:clickable="false"/>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1,500 points"
android:clickable="false"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
activity_main_drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group
android:id="#+id/grp1"
android:checkableBehavior="single">
<item
android:id="#+id/nav_home"
android:icon="#drawable/ic_menu_home"
android:title="Home" />
<item
android:id="#+id/nav_library"
android:icon="#drawable/ic_menu_book"
android:title="Library" />
<item
android:id="#+id/nav_create"
android:icon="#drawable/ic_menu_add"
android:title="Create" />
<item
android:id="#+id/nav_user"
android:icon="#drawable/ic_menu_user"
android:title="My Account" />
<item
android:id="#+id/nav_settings"
android:icon="#drawable/ic_menu_cog_wheel"
android:title="Settings" />
</group>
<group
android:id="#+id/grp2"
android:checkableBehavior="single">
<item
android:id="#+id/nav_about"
android:icon="#drawable/ic_menu_about"
android:title="About" />
<item
android:id="#+id/nav_sign_out"
android:icon="#drawable/ic_menu_sign_out"
android:title="Sign Out" />
</group>
</menu>
content_blank.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:layout_marginTop="70dp"
android:text="content_blank"/>
</LinearLayout>
NavigationView header is usually included this way:
<android.support.design.widget.NavigationView
android:id="#+id/nvView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#android:color/white"
app:headerLayout="#layout/main_drawer_header"
app:itemTextColor="#color/black"
app:menu="#menu/menu_main_drawer"
app:itemIconTint="#null"/>
Since support libraries version 23.1.0 NavigationView is using a RecyclerView and the header is added as one of RecyclerView's items.
Activity's findViewById won't find the header and its internals.
To get access to it you need to get the header from NavigationView and call findViewById relative to header view:
NavigationView navigationView = (NavigationView) findViewById(R.id.nvView);
View navHeaderview = navigationView.getHeaderView(0);
LinearLayout navHeaderUser = (LinearLayout) navHeaderview.findViewById(R.id.nav_header_user);
navHeaderUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Intent myIntent = new Intent(MainActivity.this, UserProfile.class);
// MainActivity.this.startActivity(myIntent);
// DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// drawer.closeDrawer(GravityCompat.START);
}
});
Hope I got it right and it'll work for you!

Hamburger menu is not correctly placed in android

Hi everyone i am working on hamburger menu in android application, where my problem is the hamburger menu is placed at wrong place(few steps down). I need the hamburger menu below my tool bar of window. please help me in this regard.
My java code:
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
// Creating Hamburger Menu
final TextView userName_ham = (TextView) this.findViewById(R.id.userName_hamburger);
ParseQuery<DriverDetails> query = new ParseQuery<DriverDetails>("driverDetails");
Log.d(TAG_NAME, "Driver Phone No" + driverPhoneNo);
query.whereEqualTo("PhoneNo", driverPhoneNo);
query.findInBackground(new FindCallback<DriverDetails>() {
#Override
public void done(List<DriverDetails> objects, ParseException e) {
if (e == null) {
if (objects.size() != 0) {
driverName = objects.get(0).getString("driverNameFirst");
Log.d(TAG_NAME, "DriverName inside" + driverName);
editor.putString("driverName", driverName);
editor.apply();
userName_ham.setText("Welcome " + driverName);
}
}
}
});
Log.d(TAG_NAME, "DriverName" + driverName);
mNavItems.add(new NavItem("Earnings", R.drawable.earnings));
mNavItems.add(new NavItem("History", R.drawable.history));
mNavItems.add(new NavItem("About", R.drawable.about));
mNavItems.add(new NavItem("Share", R.drawable.share));
mNavItems.add(new NavItem("Notification", R.drawable.notification));
mNavItems.add(new NavItem("Settings", R.drawable.settings));
mNavItems.add(new NavItem("Logout", R.drawable.logout));
// DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
// Populate the Navigation Drawer with options
mDrawerPane = (RelativeLayout) findViewById(R.id.drawerPane);
mDrawerList = (ListView) findViewById(R.id.navList);
DrawerListAdapter drawerAdapter = new DrawerListAdapter(this, mNavItems);
mDrawerList.setAdapter(drawerAdapter);
mDrawerList.setFitsSystemWindows(true);
// Drawer Item click listeners
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItemFromDrawer(position);
}
});
My xml file code:
<!-- The navigation drawer -->
<RelativeLayout
android:layout_width="280dp"
android:layout_height="match_parent"
android:id="#+id/drawerPane"
android:fitsSystemWindows="true"
android:layout_gravity="start">
<!-- Profile Box -->
<RelativeLayout
android:id="#+id/profileBox"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#color/colorPrimary"
android:padding="8dp" >
<ImageView
android:id="#+id/avatar"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/user"
android:clickable="false"
android:layout_marginTop="15dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="42dp"
android:layout_centerVertical="true"
android:layout_marginLeft="15dp"
android:layout_toRightOf="#+id/avatar"
android:orientation="vertical" >
<TextView
android:id="#+id/userName_hamburger"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome"
android:textColor="#fff"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/view_profile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginTop="4dp"
android:text="View Profile"
android:clickable="true"
android:textColor="#fff"
android:textSize="12sp" />
</LinearLayout>
</RelativeLayout>
<!-- List of Actions (pages) -->
<ListView
android:id="#+id/navList"
android:layout_width="280dp"
android:layout_height="match_parent"
android:layout_below="#+id/profileBox"
android:choiceMode="singleChoice"
android:background="#ffffffff" />
</RelativeLayout>
My activity xml file:
<?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:fitsSystemWindows="true"
tools:context=".ui.DriverScreenActivity">
<android.support.design.widget.AppBarLayout android:layout_width="match_parent"
android:layout_height="wrap_content" android:theme="#style/AppTheme.AppBarOverlay"/>
<include layout="#layout/content_customer_screen" />
<android.support.design.widget.FloatingActionButton android:id="#+id/logout"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginBottom="160sp"
android:scaleType="fitXY"
android:src="#drawable/btn_logout" />
</android.support.design.widget.CoordinatorLayout>

Navigation drawer cannot set text and image

Case_history_review.java
This is one of my java to use the nav bar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("E-care");
setSupportActionBar(toolbar);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView view = (NavigationView) findViewById(R.id.navigation_view);
view.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
Toast.makeText(Case_history_review.this, menuItem.getItemId() + " pressed", Toast.LENGTH_LONG).show();
Log.d(R.id.nav_1+"", menuItem.getItemId() + " ");
Intent intent = new Intent();
switch (menuItem.getItemId())
{
case R.id.nav_1:
break;
case R.id.nav_2:
intent.setClass(Case_history_review.this,queueshow.class);
//intent .putExtra("name", "Hello B Activity");
startActivity(intent);
break;
case R.id.nav_3:
intent.setClass(Case_history_review.this,Appointmentcreate.class);
//intent .putExtra("name", "Hello B Activity");
startActivity(intent);
break;
case R.id.nav_4:
intent.setClass(Case_history_review.this, AlarmActivity.class);
startActivity(intent);
break;
case R.id.nav_5:
intent.setClass(Case_history_review.this, PatientReport.class);
startActivity(intent);
break;
case R.id.nav_6:
intent.setClass(Case_history_review.this, TimeList.class);
startActivity(intent);
//logout
break;
}
menuItem.setChecked(true);
drawerLayout.closeDrawers();
return true;
}
});
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle( this, drawerLayout, toolbar, R.string.drawer_open , R.string.drawer_close){
#Override
public void onDrawerClosed(View drawerView) {
super .onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super .onDrawerOpened(drawerView);
}
};
db = new SQLiteHandler(getApplicationContext());
HashMap<String, String> dbuser = db.getUserDetails();
TextView name = (TextView) view.findViewById(R.id.drawer_name);
String username = dbuser.get("name");
Log.d("naem",username);
name.setText(username);
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
CirculaireNetworkImageView photo = (CirculaireNetworkImageView) view.findViewById(R.id.drawer_thumbnail);
photo.setImageUrl("http://192.168.43.216/test/" + dbuser.get("image"), imageLoader);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
These two lines get errors
name.setText(username);
photo.setImageUrl("http://192.168.43.216/test/" + dbuser.get("image"), imageLoader);
Error message:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.yuen.e_carei.Case_history_review.onCreate(Case_history_review.java:116)
layout/drawer_header.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="150dp"
android:background="#0097a7"
>
<com.example.yuen.CirculaireNetworkImageView
android:id="#+id/drawer_thumbnail"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_marginRight="8dp"
android:elevation="8dp"
android:layout_above="#+id/drawer_name"
android:layout_alignStart="#+id/drawer_name" />
<TextView
android:id="#+id/drawer_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="24dp"
android:layout_marginStart="24dp"
android:layout_alignParentBottom="true"
android:text="Eddard Stark"
android:textSize="14sp"
android:textColor="#fff"
android:textStyle="bold"
android:paddingBottom="8dp"
/>
</RelativeLayout>
menu/drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_1"
android:checked="true"
android:icon="#drawable/hi"
android:title="Case Review"/>
<item
android:id="#+id/nav_2"
android:icon="#drawable/hi"
android:title="Queue state"/>
<item
android:id="#+id/nav_3"
android:icon="#drawable/hi"
android:title="Create appointemnt"/>
<item
android:id="#+id/nav_4"
android:icon="#drawable/hi"
android:title="Alarm"/>
<item
android:id="#+id/nav_5"
android:icon="#drawable/hi"
android:title="Report"/>
<item
android:id="#+id/nav_6"
android:icon="#drawable/hi"
android:title="Logout"/>
</group>
</menu>
activity_case_history_solo.xml
<?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:fitsSystemWindows="true"
tools:context="com.example.yuen.e_carei.Case_history_review">
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<!-- your content layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.yuen.e_carei.Case_history_review">
<ImageView
android:src="#drawable/hi"
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/imageView2"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_toEndOf="#+id/imageView2"
android:layout_alignBottom="#+id/imageView2"
android:id="#+id/relativeLayout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name : "
android:textSize="25sp"
android:id="#+id/textView2"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ID : "
android:textSize="25sp"
android:id="#+id/idTag"
android:paddingLeft="11dp"
android:layout_below="#+id/textView2"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Chan Tai Man"
android:textSize="25sp"
android:id="#+id/nameResult"
android:paddingBottom="10dp"
android:layout_above="#+id/idResult"
android:layout_toEndOf="#+id/textView2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="N001"
android:textSize="25sp"
android:id="#+id/idResult"
android:layout_below="#+id/textView2"
android:layout_toEndOf="#+id/idTag" />
</RelativeLayout>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView_case_history"
android:layout_alignEnd="#+id/relativeLayout"
android:layout_below="#+id/imageView2" />
</RelativeLayout>
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/drawer_header"
app:menu="#menu/drawer" />
</android.support.v4.widget.DrawerLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
I want to change the text in the drawer_header to become other string. However, it can get the id but crash in the runtime. Please give me some helps to solve this. Thank You.
Error depicts that the TextView object is null, means there is no such textview exists in the layout that is currently running.
Did the textview present in the XML layout that you are calling? Which layout did you put the TextView?
Kindly check whether your activity is correct!!
The id that you use inside findViewById(R.id....) may be wrong. Double check that.
You have called the
TextView name = (TextView) view.findViewById(R.id.drawer_name);
in the Case_history_review.java but it seems that the above textView doesn't exists in your layout that you are calling. Probably you will be calling the below activity_case_history_solo.XML in the Activity and it doesn't has it. And the above TextView lies in the drawer_header.xml
Hope this helps you..!!

Categories