null container in fragment oncreate method - java

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

Related

Add a slide up panel in a fragment

I am having a difficult time adding a slide-up panel to one of my activities. I want to add a panel that goes to the middle ofo the screen and then all the way to the top of the application itself.
I want the screen to look similar to this image below.
this is my code for my MainActivity
public class MainActivity extends AppCompatActivity {
private DrawerLayout drawer;//sets what you see in the side panel
private AppBarConfiguration mAppBarConfiguration;//allows for user to press buttons
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ListView mylistview = findViewById(R.id.listView);
// ArrayList<String> myFamily = new ArrayList<String>();
// myFamily.add("Rob");
// myFamily.add("May");
//
// ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
// android.R.layout.simple_expandable_list_item_1, myFamily);
// mylistview.setAdapter(arrayAdapter);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
// FloatingActionButton fab = findViewById(R.id.fab); //this is for the message button; do not worry about it
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_account, R.id.nav_coupons, R.id.nav_settings)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
// ListView listView = findViewById(R.id.listView);
// listView.setAdapter(new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,
// new String[] {"THis","that ","when","where","why","is"}));
}
#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, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
this is my code for my home activity xml file
<?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"
android:background="#android:color/holo_red_light"
android:layout_gravity="bottom"
android:gravity="bottom"
app:umanoDragView="#id/dragview"
app:umanoOverlay="false"
app:umanoPanelHeight="68dp"
app:umanoParallaxOffset="100dp"
app:umanoScrollableView="#id/listView"
app:umanoShadowHeight="4dp">
<TextView
android:id="#+id/text_home"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:textAlignment="center"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
and this is my home fragment code for the view model
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
homeViewModel =
ViewModelProviders.of(this).get(HomeViewModel.class);
View root = inflater.inflate(R.layout.fragment_home, container, false);
final TextView textView = root.findViewById(R.id.text_home);
homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
return root;
}
}
I prefer to use this implementation of top sheet:
https://github.com/MedveDomg/AndroidTopSheet
You can customize whatever you need.

Navigation Drawer not loading layout with RecyclerView

I have my Events.java and event.xml layout, which has a recycler view & works fine when if I load the Event class directly. It looks like this:
However, if I load the navigation drawer, which then load the event.xml file, then I get the following screens with this error: "No adapter attached; skipping layout".
My issues is that why is the navigation menu not working and the event layout file not loading? As for my code, I think the following might be helpful.
Events.java
#Override
protected void onCreate(Bundle savedInstanceState) {
...
RecyclerView recyclerView = findViewById(R.id.events_rv_list);
EventsAdapter eventsAdapter = new EventsAdapter(this, eList, this);
recyclerView.setAdapter(eventsAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
events.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Events"
android:background="#ffff6c">
<android.support.v7.widget.RecyclerView
android:id="#+id/events_rv_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
</android.support.constraint.ConstraintLayout>
NavigationDrawer.java
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_drawer);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
}
...
Okay, I've found the solution. The error was that the adapter was not attached to the RecyclerView.
In the first picture, the adapter worked because it was stored in a normal layout file (non fragment) class, so the onCreate was being called from the events.java. Events.java then loaded the layout (events.xml) and also attached the adapters to the RecyclerView like so:
RecyclerView recyclerView = view.findViewById(R.id._events_recyclerview);
ADAPTE_CLASS adapter = new ADAPTE_CLASS(PASS DATA IF NECESSARY);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
Now same thing can be applied in a Fragment where you can add the above code to onCrateView method (with relevant class names & ids). So that's how you set a recyclerview adapter in a fragnent.
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.

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.

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