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

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.

Related

Can't set Text of TextView

I wanted to have the Text of a TextView changed to whatever the username of the active user is, but the method updateUI() always returns this error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.cocko.industries.einkaufshelfer.shopper, PID: 18704
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cocko.industries.einkaufshelfer.shopper/com.cocko.industries.einkaufshelfer.shopper.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
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.cocko.industries.einkaufshelfer.shopper.MainActivity.updateUI(MainActivity.java:203)
at com.cocko.industries.einkaufshelfer.shopper.MainActivity.onCreate(MainActivity.java:76)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
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)
So what's the problem? It seems to me as if the TextView can't be found and is therefore null. But why? And how can I fix that? Below you can find the MainActivity class with the onCreate and updateUI method and the fragment that I used.
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
private NavigationView nav_view;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mAuth = FirebaseAuth.getInstance();
nav_view = findViewById(R.id.nav_view);
nav_view.setNavigationItemSelectedListener(this);
drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.nav_drawer_open, R.string.nav_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
try {
Intent intent = getIntent();
if (intent.getStringExtra("activity").equals("register")) {
getSupportFragmentManager().beginTransaction().replace(R.id.framgment_container, new UserprofileFragment()).commit();
}
} catch (NullPointerException noIntentExtra) {
getSupportFragmentManager().beginTransaction().replace(R.id.framgment_container, new AssignmentsFragment()).commit();
}
if (mAuth.getCurrentUser() != null){
updateUI();
}
}
And the updateUI function is as follows.
public void updateUI() {
TextView textView = findViewById(R.id.textview_assignemntsheader);
textView.setText("Test");
}
Here's the layout for my fragment, that is fragment_assignments.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">
<TextView
android:id="#+id/textview_assignemntsheader"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:text="#string/textview_assigmentsHeader"
android:textAlignment="center"
android:textAppearance="#style/TextAppearance.AppCompat.Display1"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textview_assignemntsheader">
<LinearLayout
android:id="#+id/linearlayout_assignments"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
And the layout for my activity is activity_main.xml:
<?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:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.appcompat.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/framgment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<com.google.android.material.navigation.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/menu" />
</androidx.drawerlayout.widget.DrawerLayout>
you can't find your textView in MainActivity because it is not in the main_activity.xml, so updateUI should be in UserProfile Fragment.
in OnCreateView
try this :
View view = inflater.inflate(R.layout.fragment_assignments, container,false);
TextView text=view.findViewById(R.id.textview_assignemntsheader);
Where do you inflate fragment_assignments.xml?
in this line, you inflate main_activity.xml
setContentView(R.layout.activity_main);
But, textview_assignemntsheader is in another XML file and can`t find it and returns null.
findViewById will search for ID only in the inflated view.
Move UpdateUI function to UserProfile (where fragment_assignments.xml is inflated)
In your MainActivity you are inflating the activity_main layout which does not have the TextView. Hence you are getting the NullPointerException while trying to find the TextView and assign some text to it.
In the onCreate method of your MainActivity class tries to set a text to a TextView which is not there or not inflated. The fragment_assignments.xml layout might be inflated in your fragment, and hence you will find the layout reference there in your fragment.
Looks like you want to pass the auth information to your fragment and set some value there. In that case, you can just pass the information using a bundle while doing the fragment transaction.
Hence, you might have the following function for your fragment transaction in your activity.
public void launchAssignmentFragment() {
AssignmentFragment frag = new AssignmentFragment();
Bundle bundle = new Bundle();
if (mAuth.getCurrentUser() != null) {
bundle.putBoolean("auth", true);
} else {
bundle.putBoolean("auth", false);
}
// set Arguments to be passed to the fragment
frag.setArguments(bundle);
// Now load the fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, frag);
transaction.addToBackStack(null);
transaction.commit();
}
Now from the onCreateView of your fragment, you can do something like this.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout. fragment_assignments, parent, false);
TextView tv = rootView.findViewById(R.id.textview_assignemntsheader);
// Get the passed-in value here
boolean auth = getArguments().getBoolean("auth");
if (auth) tv.setText("Success");
else tv.setText("Fail");
return rootView;
}
And finally, update your onCreate in the MainActivity as follows.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mAuth = FirebaseAuth.getInstance();
nav_view = findViewById(R.id.nav_view);
nav_view.setNavigationItemSelectedListener(this);
drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.nav_drawer_open, R.string.nav_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
try {
Intent intent = getIntent();
if (intent.getStringExtra("activity").equals("register")) {
getSupportFragmentManager().beginTransaction().replace(R.id.framgment_container, new UserprofileFragment()).commit();
}
} catch (NullPointerException noIntentExtra) {
getSupportFragmentManager().beginTransaction().replace(R.id.framgment_container, new AssignmentsFragment()).commit();
}
if (mAuth.getCurrentUser() != null){
launchAssignmentFragment(); // launch the fragment maybe?
}
}
I hope that helps!

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.

toolbar back button error Android

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);
}
}

null container in fragment oncreate method

I'm trying to show my fragment in another activity. At first everything was fine but after editing code my fragment don't shows up. This is my main activity content XML code:
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="ir.aftabeshafa.shafadoc.MainActivity"
tools:showIn="#layout/app_bar_main">
<fragment
android:id="#+id/headlines_fragment"
android:name="ir.aftabeshafa.shafadoc.CatFrag"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
And fragment class:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.card_front, container, false);
for (int i = 0; i < imgs.size(); i++) {
CatModel catModel = new CatModel();
catModel.txt = cat[i];
catModel.imgid = imgs.get(i);
arrayList.add(catModel);
}
recyclerView = (RecyclerView) inflater.inflate(R.layout.card_front, container, false).findViewById(R.id.recycler);
StaggeredGridLayoutManager gridLayoutManager =
new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView.setHasFixedSize(true);
catAdapter = new CatAdapter(arrayList);
recyclerView.setAdapter(catAdapter);
return view;
}
Main Activity class:
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();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
When I debugging my app the container in fragment class is null. Why is this happening?
You are assigning recyclverView from a newly inflated layout when you should be working with the layout you already inflated previously and assigned to view.
This means the view you are returning still has an empty recyclerView. To fix this change:
recyclerView = (RecyclerView) inflater.inflate(R.layout.card_front, container, false).findViewById(R.id.recycler);
To:
recyclerView = (RecyclerView) view.findViewById(R.id.recycler);
so that you use the recyclerView associated with the view you are returning.
I found my problem it was findviewbyid in fragment class. I changed this:
recyclerView = (RecyclerView) inflater.inflate(R.layout.card_front, container, false).findViewById(R.id.recycler);
to this:
recyclerView = (RecyclerView) view.findViewById(R.id.recycler);

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