toolbar back button error Android - java

I want to add a Back button in a toolbar that I created because I deleted the default one to have the material design effect with some tabs, but every time I add the code to make that button appear, Android gives an exception saying this:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.juan.sdfnsdfnskdfnskdfmsfd, PID: 13348
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.support.v4.widget.DrawerLayout.getDrawerLockMode(int)' on a null object reference
at android.support.v7.app.ActionBarDrawerToggle.toggle(ActionBarDrawerToggle.java:284)
at android.support.v7.app.ActionBarDrawerToggle$1.onClick(ActionBarDrawerToggle.java:202)
at android.view.View.performClick(View.java:6308)
at android.view.View$PerformClick.run(View.java:23969)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6823)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1557)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)
I do not understand what it means with a null object reference if I only write the corresponding code in the toolbar that I created.
This is the toolbar.xml:
<android.support.v7.widget.Toolbar 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="wrap_content"
android:background="#color/toolbar_morado"
android:id="#+id/toolbar_lista_compras"
android:minHeight="?attr/actionBarSize">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/contador_toolbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lista de compras"
android:textSize="18sp"
android:textColor="#ffffff"/>
</RelativeLayout>
</android.support.v7.widget.Toolbar>
This is where I implement the toolbar:
<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="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:id="#+id/appBarLayoutCalcular">
<include layout="#layout/toolbar"></include>
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tablayoutCalcular"
app:tabGravity="fill"
app:tabMode="fixed"
android:background="#color/toolbar_anaranjado"
app:tabTextAppearance="#style/myTabSize"
app:tabIndicatorColor="#5c1be1"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewPagerCalcular"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
This is my class:
public class CalculateMaterials extends AppCompatActivity{
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
Toolbar toolbar;
NavigationView navigationView;
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;
String tabSeleccionado;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calcular_materiales);
toolbar = (Toolbar)findViewById(R.id.toolbar_shopping_list);
toolbar.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.toolbar_anaranjado));
setSupportActionBar(toolbar);
// text for the toolbar
TextView textoToolbar = (TextView)findViewById(R.id.contador_toolbar);
textoToolbar.setText("Calcular los materiales");
// status bar color
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(ContextCompat.getColor(getApplicationContext(), R.color.statusBar_anaranjado));
}
// adding toolbar back button
// this is where I have the error
if (toolbar != null) {
toolbar.setNavigationIcon(R.drawable.backButton);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
navigationView = (NavigationView)findViewById(R.id.navigationView);
tabLayout = (TabLayout)findViewById(R.id.tablayoutCalcular);
viewPager = (ViewPager)findViewById(R.id.viewPagerCalcular);
// adding the tabs
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addFragments(new FragmentCalcular(), "Con area");
viewPagerAdapter.addFragments(new FragmentCalcular2(), "Con metros");
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
I also try with:
// add back arrow to toolbar
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
That also gives the same error.
So, Can anyone help me with this problem?
Edit
Thanks to everyone who tried to help me with this problem. I finally found the error.
Some time ago, I tried to add a navigationView in all the activities, but I forgot to delete the necessary code in the class, that's why the drawerLayout doesnt appears in the xml.
So, when I delete the drawerLayout variable, everything works!

Try this
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});

Try this.
toolbar = (Toolbar) findViewById(R.id.toolbar_editprofile);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false):
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.back_arrow));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});

It seems like drawerLayout is null. I can't able to find find your "drawer_layout" in XML.
Make sure you are using the same id for the navigation drawer in findViewById(R.id.drawer_layout) and in the layout file.

First thing where is your DrawerLayout ? i cant find it from your question may be you forgot to post it or not created yet.
make sure you have to declare correct ID for DrawerLayout so check drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout); of drawer_layout.xml
Error Line: i have found error in this line may be this is not your answer but should have to correct you
TextView textoToolbar = (TextView)findViewById(R.id.contador_toolbar);
Try This
toolbar = (Toolbar)findViewById(R.id.toolbar_shopping_list);
toolbar.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.toolbar_anaranjado));
setSupportActionBar(toolbar);
// text for the toolbar
TextView textoToolbar = (TextView)toolbar.findViewById(R.id.contador_toolbar);
textoToolbar.setText("Calcular los materiales");

In onCreate method paste this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolBarGig);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
after this you have to override method:-
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
Try this. Hope it will helps you!

First initialize the toolbar bar for back button
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
then call back button method this code is enough to go to previous
activity else you can use intent method inside onBackPressed method to
go back
//method on back button click
#Override
public void onBackPressed() {
super.onBackPressed();
/*OR
Intent forgot_password = new Intent( AddItemActivity.this, HomeActivity.class);
startActivity(forgot_password);
finish();
}*/
back button click functionality
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}

Related

My hamburguer icon in action bar doesn't open the drawer

I have a problem with my hamburguer icon, if I touch don't open the drawer.
My drawer only works with the action bar layout, but I need it transparent and only can make with the toolbar, I'm brazilian and sorry for the errors of english
img :
img of the toolbar
my 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="false"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize">
</android.support.v7.widget.Toolbar>
</RelativeLayout>
<include layout="#layout/content_main" />
</android.support.design.widget.CoordinatorLayout>
my code:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
ActionBarDrawerToggle toggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitleTextColor(Color.parseColor("#ffffff"));
toolbar.setBackgroundColor(Color.TRANSPARENT);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
Window window = this.getWindow();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(Color.TRANSPARENT);
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.frame_Layout, new Fragment_Inicio());
fragmentTransaction.disallowAddToBackStack();
fragmentTransaction.commit();
NavigationView navigationView = findViewById(R.id.nav_view_inthebox);
navigationView.setNavigationItemSelectedListener(this);
Helper h = new Helper();
ImageButton callflex = findViewById(R.id.nav_logo);
h.Abrir_link_externo_botao(callflex,"https://www.callflex.com.br", this);
ImageButton linkedin = findViewById(R.id.nav_linkedin);
h.Abrir_link_externo_botao(linkedin,"https://www.linkedin.com/company-beta/949222/", this);
ImageButton instagram = findViewById(R.id.nav_instagram);
h.Abrir_link_externo_botao(instagram,"https://www.instagram.com/callflexbr/", this);
ImageButton facebook = findViewById(R.id.nav_facebook);
h.Abrir_link_externo_botao(facebook,"https://www.facebook.com/callflex/", this);
ImageButton youtube = findViewById(R.id.nav_youtube);
h.Abrir_link_externo_botao(youtube,"https://www.youtube.com/channel/UCyMBD5Pcu6nHUlDij_N-iRw", this);
}
public void setActionBarTitle(String title) {
getSupportActionBar().setTitle(title);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}else {
super.onBackPressed();
}
}
#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 (toggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
Can someone help me? I need this hamburguer icon work.
Basically the layout was overlapping the status bar, as said in the comment of darwind, I arranged by inverting and putting the include in the right place.

How can I nest fragments with a navigation drawer?

I've been trying for the last few hours to search around SO, but I couldn't find a solution outside of trying to create a workaround. I'm trying to create a navigation drawer for my app, but to do so I had to end up trying to change my base activity into a fragment. This is the result:
public class ToolReaderActivity extends Fragment implements ToolListFragment.OnToolSelectedListener, CompatActionBarNavListener, OnClickListener {
boolean mIsDualPane = false;
Context c;
ToolListFragment mToolListFragment;
InfoFragment mInfoFragment;
Fragment mContent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
c = getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.onepane_with_bar, container, false);
// find our fragments
mToolListFragment = (ToolListFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.toolList);
mInfoFragment = (InfoFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.toolInfo);
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.toolList, mToolListFragment).commit();
FragmentTransaction transaction2 = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.toolInfo, mInfoFragment).commit();
mToolListFragment.setContext(c);
mToolListFragment.setOnToolSelectedListener(this);
View infoView = getView().findViewById(R.id.toolInfo);
mIsDualPane = infoView != null && infoView.getVisibility() == View.VISIBLE;
int catIndex = savedInstanceState == null ? 0 : savedInstanceState.getInt("catIndex", 0);
setUpActionBar(mIsDualPane, catIndex);
mToolListFragment.setSelectable(mIsDualPane);
restoreSelection(savedInstanceState);
if (savedInstanceState != null) {
//Restore the fragment's instance
mContent = getActivity().getSupportFragmentManager().getFragment(savedInstanceState, "mContent");
}
return rootView;
}
...
...
...
}
The intended output is a activity with a navigation drawer and thus a fragment. The fragment contains this main activity ToolReaderActivity (named so because it was formerly an activity) which has 1-2 fragments inside of it. It's a ListFragment with a fragment showing the selected items information (as either another fragment if mDualPane is true or launched as a seperate activity otherwise).
I can't figure out a way to get this to work, I've tired changing the order that things are done using onCreate, onCreateView, onActivityCreated, but the error I keep getting is that mToolsListFragment is null at mToolsListFragment.setContext(c);
You can simply create NavigationDrawer with the code below.
public class MainActivity extends AppCompatActivity
{
private NavigationView mNavigationView;
private DrawerLayout mDrawerLayout;
private Toolbar toolbar;
private ActionBarDrawerToggle mDrawerToggle;
private FragmentActivity fragment;
private FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initDrawerNavigation();
fragmentManager = getFragmentManager();
}
public void initDrawerNavigation()
{
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(R.string.app_name);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener()
{
#Override
public boolean onNavigationItemSelected(MenuItem item)
{
item.setChecked(true);
switch (item.getItemId())
{
case R.id.st_menu:
fragment = new FirstFragment();
break;
case R.id.nd_menu:
fragment = new Second Fragment();
break;
}
fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
mDrawerLayout.closeDrawers();
return true;
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.drawer_open,
R.string.drawer_close)
{
// Called when a drawer has settled in a completely closed state.
public void onDrawerClosed(View view)
{
super.onDrawerClosed(view);
}
// Called when a drawer has settled in a completely open state.
public void onDrawerOpened(View drawerView)
{
super.onDrawerOpened(drawerView);
}
};
mDrawerLayout.addDrawerListener(mDrawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId())
{
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START); // OPEN DRAWER
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here you have activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:theme="#style/ThemeOverlay.AppCompat.ActionBar" />
<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:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<include
layout="#layout/your_layout" />
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
app:menu="#menu/navigation_items" />
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
your_layout can be anything you want. Now you define your FirstFragment class like here:
public class FirstFragment extends Fragment
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
ViewGroup view = (ViewGroup) inflater.inflate(R.layout.target_layout, container, false);
return view;
}
}
You can also refer to this question Navigation Drawer to switch between activities if you want to switch between activities and not fragments. Hope this helps.

Custom toolbar on android navigation drawer

Im new to android development and am really struggling to implement a more custom toolbar (or action bar) when using the navigation drawer created in android studio. When I created the navigation drawer activity from the template, the file that seems to be defining the tool bar is app_bar_main.xml
here is app_bar_main.xml
<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:title="Press"
android:titleTextColor="#FFFFFF"
/>
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
As you can see, I have tried to change the title (to press) and text color of the tool bar, however when running it, nothing changes and it still just says MainActivity which is what my Navigation drawer activity is called. How can I define this toolbar so I can customize it (center the title, make the background transparent, remove settings button, etc. I do need to keep the hamburger icon to open the drawer obviously)
Thanks for the future help everyone! Let me know if I need to provide any other pieces of my code
Setting the values inside of xml for the toolbar has never worked for me either. You should do them pragmatically. If you are generating the code from Android Studio, you will see inside of onCreate that it is setting the toolbar to the ActionBar:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
One possible option is to remove setSupportActionbar().
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
toolbar.setTitle("Testing");
toolbar.setTitleTextColor(ContextCompat.getColor(this, R.color.colorAccent));
toolbar.inflateMenu(R.menu.menu_main);
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
return false;
}
});
}
The other is to call getSupprtActionBar()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitleTextColor(ContextCompat.getColor(this, R.color.colorAccent));
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle("Testing");
}
}
/**
* Here is where you would handle the actionbar items.
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main2, menu);
return true;
}

android.view.View.setVisibility(int) crashes the new activity [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
So recently I'm trying to implement a FAB that will expand into a new activity but it crashes after the FAB was pressed.
Moreover from this question where I followed the steps on implementing it: FloatingActionButton expand into a new activity
Logcat:
Process: com.example.jovie.canteen, PID: 6953
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setVisibility(int)' on a null object reference
at com.example.jovie.canteen.Home$1$2.run(Home.java:105)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Home.java
public class Home extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
CoordinatorLayout homeLayout;
private GoogleApiClient client;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private RevealLayout mRevealLayout;
View mViewToReveal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
homeLayout = (CoordinatorLayout) findViewById(R.id.CoordinatorLayout);
setSupportActionBar(toolbar);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
mRevealLayout = (RevealLayout) findViewById(R.id.reveal_layout);
final View mRevealView=(View)
findViewById(R.id.reveal_view);
final FloatingActionButton mFab = (FloatingActionButton) findViewById(R.id.fab);
mFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mFab.setClickable(false); // Avoid naughty guys clicking FAB again and again...
int[] location = new int[2];
mFab.getLocationOnScreen(location);
location[0] += mFab.getWidth() / 2;
location[1] += mFab.getHeight() / 2;
final Intent intent = new Intent(Home.this, SearchActivity.class);
mRevealView.setVisibility(View.VISIBLE);
mRevealLayout.setVisibility(View.VISIBLE);
mRevealLayout.show(location[0], location[1]); // Expand from center of FAB. Actually, it just plays reveal animation.
mFab.postDelayed(new Runnable() {
#Override
public void run() {
startActivity(intent);
/**
* Without using R.anim.hold, the screen will flash because of transition
* of Activities.
*/
overridePendingTransition(0, R.anim.hold);
}
}, 600); // 600 is default duration of reveal animation in RevealLayout
mFab.postDelayed(new Runnable() {
#Override
public void run() {
mFab.setClickable(true);
mRevealLayout.setVisibility(View.INVISIBLE);
mViewToReveal.setVisibility(View.INVISIBLE);
}
}, 960); // Or some numbers larger than 600.
}
});
client = new GoogleApiClient.Builder(Home.this).addApi(AppIndex.API).build();
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);
}
activity_home.xml
<com.example.jovie.canteen.RevealLayout
android:id="#+id/reveal_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="invisible">
<View
android:id="#+id/reveal_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="invisible"/>
</com.example.jovie.canteen.RevealLayout>
<include
layout="#layout/app_bar_home"
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_home"
app:menu="#menu/activity_home_drawer"
android:background="#ffffff" />
However the null on android.view.View.setVisibility(int) is pointing at mViewToReveal.setVisibility(View.INVISIBLE); and not sure where exactly I need to look for, please help.
Because you never instantiated mViewToReveal
add this in onCreate
mViewToReveal = findViewById(R.id.reveal_view);
mViewToReveal hasn't been initialized.
Because you did not pass the reference of any view to mViewToReveal that's why it's null and throwing error "Attempt to invoke virtual method 'void android.view.View.setVisibility(int)' on a null object reference", need to pass reference to mViewToReveal before doing any activity on it
mViewToReveal =(View) findViewById(R.id.<id_of_ViewToReveal>);
It's because you never instantiated mViewToReveal.

Android Programming Error "No view found for id for fragment " with Google Maps

So I am using the default Navigation Drawer for my Android Application. What I'm trying to do is linking a button to a fragment I created.
In the fragment I created, I am trying to open up Google Maps.
Whenever I click on the button however, I get this crash:
This is the generated error (i have no syntax errors):
E/FragmentManager: No view found for id 0x7f0d0089 (com.example.x.x:id/mapView) for fragment LocationFragment{35b5044 #1 id=0x7f0d0089}
This is the code from the default menu (I try to only put the needed code):
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);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (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);
FragmentManager fm = getFragmentManager();
}
In the same default Navigation drawer, we also have the onNavigationItemSelected(MenuItem item) function, that does an action when you click on the menu item, this is where I make the FragmentManager call my LocationFragment:
public boolean onNavigationItemSelected(MenuItem item) {
FragmentManager fm = getFragmentManager();
int id = item.getItemId();
if (id == R.id.nav_camara) {
// Handle the camera action
} else if (id == R.id.nav_share) {
fm.beginTransaction().replace(R.id.mapView, new LocationFragment()).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
And here we have the LocationFragment Java class (witht he most important function included):
public class LocationFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflate and return the layout
View v = inflater.inflate(R.layout.location_fragment, container,
false);
mMapView = (MapView) v.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();// needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
googleMap = mMapView.getMap();
// latitude and longitude
double latitude = 17.385044;
double longitude = 78.486671;
// create marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title("Hello
return v;
}
The layout file (xml) of the LocationFragment (called location_fragment.xml):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.gms.maps.MapView
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
I do not understand why I get the error, since I have checked all ID's in all classes for maybe 100 times. I seem be stuck here. Any help would be appreciated
Thanks in advance
Added 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>
From this , it says: Replace method replaces an existing fragment that was added to a container.
public abstract FragmentTransaction replace (int containerViewId, Fragment fragment)
Where containerViewId is a container. I dont think MapView is a container. So instead of:
fm.beginTransaction().replace(R.id.mapView, new LocationFragment()).commit();
It should be:
fm.beginTransaction().replace(R.id.mapViewContainer, new LocationFragment()).commit();
Where mapViewContainer is:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent" android:id="#+id/mapViewContainer">
Hope this help.

Categories