App keeps crashing when fragments are replaced - android

I am trying to create a basic android app. I have a navigation drawer activity , a map fragment, and a profile fragment. Before implementing the map fragment, the application was running smoothly, but now it keeps crashing. I have resolved this problem before with simple fragment by implementing the nameOfFragment.OnFragmentInteractionListener method before. But there is no such thing for the map. How can I fix this?
this is my main activity code:
package georgia.languagelandscape;
//import android.app.FragmentManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class NavigationDrawerActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, ProfileFragment.OnFragmentInteractionListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawer);
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);
//me
navigationView.setItemIconTintList(null);
getSupportActionBar().setDisplayShowTitleEnabled(false);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.navigation_drawer, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
MapFragment mapFragment= new MapFragment();
ft.replace(R.id.content_replace, mapFragment);
ft.commit();
if (id == R.id.nav_feed) {
// Handle the camera action
} else if (id == R.id.nav_my_profile) {
ProfileFragment profileFragment= new ProfileFragment();
ft.replace(R.id.content_replace, profileFragment);
ft.commit();
} else if (id == R.id.nav_my_projects) {
} else if (id == R.id.nav_seetings) {
} else if (id == R.id.nav_log_out) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
}
and my map fragment code:
package georgia.languagelandscape;
//import android.app.Fragment;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
//import android.support.v4.app.Fragment;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link MapFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link MapFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class MapFragment extends SupportMapFragment implements OnMapReadyCallback {
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.fragment_map, 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();
}
SupportMapFragment mapFragment = ((SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.mapView));
mapFragment.getMapAsync(this);
// latitude and longitude
double latitude = 17.385044;
double longitude = 78.486671;
// create marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(17.385044, 78.486671)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Perform any camera updates here
return v;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
#Override
public void onMapReady(GoogleMap googleMap) {
}
}
My crash log:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
at georgia.languagelandscape.MapFragment.onCreateView(MapFragment.java:57)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2184)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1298)
at android.support.v4.app.FragmentManagerImpl.moveFragmentsToInvisible(FragmentManager.java:2323)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2136)
at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2092)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1998)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:709)
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:5451)
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)
Thank you!

Since your Fragment extends SupportMapFragment, there is no need to inflate any xml layout.
Your entire Fragment class can be reduced to just this:
public class MapFragment extends SupportMapFragment implements OnMapReadyCallback {
private GoogleMap mGoogleMap;
#Override
public void onResume() {
super.onResume();
if (mGoogleMap == null) {
getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
// latitude and longitude
double latitude = 17.385044;
double longitude = 78.486671;
// create marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(17.385044, 78.486671)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
}

SupportMapFragment mapFragment = ((SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.mapView));
mapFragment.getMapAsync(this);
there is no view being found and mapFragment is thus null.

I can't see the rest of your error logs. Normally if you scroll down further there will be a link pointing you to the line in your code where the problem originated.
However, you seem to be using the same id for your fragment as for your MapView. These should be different.

Related

MapFragment into Navigation Drawler Activity

I need use MapFragment when start NavigationDrawler Activity.
I try put map fragment into content_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:id="#+id/map"
android:name="com.it.irent.myapplicationtedt.MapsFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
But app crashed.
My MapsFragment class:
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsFragment extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps_fragment);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
I think problem in initialization in main class MainActivity, but I can't understand where and what I must initialize.
I hope for your help
import android.app.Fragment;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
FragmentManager fragmentManager;
MapsFragment mapsFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragmentManager = getSupportFragmentManager();
mapsFragment = new MapsFragment();
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);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
LogChat error :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.it.irent.myapplicationtedt, PID: 22147
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.it.irent.myapplicationtedt/com.it.irent.myapplicationtedt.MainActivity}: android.view.InflateException: Binary XML file line #6: Error inflating class fragment
This is wrong:
android:name="com.it.irent.myapplicationtedt.MapsFragment"
use:
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment" //change here
android:layout_width="match_parent"
android:layout_height="match_parent" />

Attempt to invoke virtual method 'void android.widget.LinearLayout.setVisibility(int)' on a null object reference

I have a navigation drawer activity and I'm trying to replace the mapFragment shown in the background with another fragment. The app always crashes.
Navigation drawer activity:
package georgia.languagelandscape;
//import android.app.FragmentManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
public class NavigationDrawerActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, ProfileFragment.OnFragmentInteractionListener, ReplaceFragment.OnFragmentInteractionListener{
MapFragment mapFragment= new MapFragment();
FragmentManager fm = getSupportFragmentManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawer);
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);
//me
navigationView.setItemIconTintList(null);
getSupportActionBar().setDisplayShowTitleEnabled(false);
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.content_replace, mapFragment);
ft.commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.navigation_drawer, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentTransaction ft = fm.beginTransaction();
ReplaceFragment replaceFragment=new ReplaceFragment();
ft.replace(R.id.content_replace, replaceFragment);
if (id == R.id.nav_feed) {
// Handle the camera action
} else if (id == R.id.nav_my_profile) {
LinearLayout map_layout=(LinearLayout)this.findViewById(R.id.dummyLayout);
map_layout.setVisibility(1);
fm.beginTransaction().hide(fm.findFragmentById(R.id.mapView)).commit();
// fm.beginTransaction().hide(getSupportFragmentManager().findFragmentById(mapFragment)).commit();
//fm.beginTransaction().hide(getSupportFragmentManager().findFragmentById(‌​mapFragment)).c‌​ommit();
//or getSupportFragmentManager().findFragmentById(R.id.mapFragmen‌​t).getView().setVisi‌​bility(View.INVISIBL‌​E);
ProfileFragment profileFragment= new ProfileFragment();
ft.replace(R.id.content_replace, profileFragment);
} else if (id == R.id.nav_my_projects) {
} else if (id == R.id.nav_seetings) {
} else if (id == R.id.nav_log_out) {
}
ft.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
}
MapFragment:
package georgia.languagelandscape;
//import android.app.Fragment;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
//import android.support.v4.app.Fragment;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link MapFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link MapFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class MapFragment extends SupportMapFragment implements OnMapReadyCallback {
private GoogleMap mGoogleMap;
#Override
public void onResume() {
super.onResume();
if (mGoogleMap == null) {
getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
// latitude and longitude
double latitude = 17.385044;
double longitude = 78.486671;
// create marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(17.385044, 78.486671)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
}
And Map fragment layout:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="georgia.languagelandscape.MapFragment">
<LinearLayout
android:id="#+id/dummyLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:visibility="gone" >
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
</FrameLayout>
I tried to do it without the linearLayout from the xml file, but it still doesn't work. I cannot use the destroy method or anything else because basically I am not returning a View. How can I hide the map?
Remove this line :
LinearLayout map_layout=(LinearLayout)this.findViewById(R.id.dummyLayout);
map_layout.setVisibility(1);
fm.beginTransaction().hide(fm.findFragmentById(R.id.mapView)).commit();
Check XML files again, If you are using v-16 or v-21 or v-13 or some other configuration files then it will give this NullPointer error.
I had this problem, I changed the files for different configurations and it worked.

Hide a Map in android studio

I am displaying a map in the content of a navigation drawer activity and I would like to be able to destroy the view when I click on an item from the drawer so I can show up another fragment. I cannot use a onDestroy method because my MapFragment doesn't have an inflater and other methods like a usual map. How can I hide the mapView?
The fragments just overlap with the map.
Main Activity:
package georgia.languagelandscape;
//import android.app.FragmentManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class NavigationDrawerActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, ProfileFragment.OnFragmentInteractionListener{
MapFragment mapFragment= new MapFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawer);
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);
//me
navigationView.setItemIconTintList(null);
getSupportActionBar().setDisplayShowTitleEnabled(false);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.content_replace, mapFragment);
ft.commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.navigation_drawer, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
if (id == R.id.nav_feed) {
// Handle the camera action
} else if (id == R.id.nav_my_profile) {
ProfileFragment profileFragment= new ProfileFragment();
ft.replace(R.id.content_replace, profileFragment);
} else if (id == R.id.nav_my_projects) {
} else if (id == R.id.nav_seetings) {
} else if (id == R.id.nav_log_out) {
}
ft.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
}
MapFragment:
package georgia.languagelandscape;
//import android.app.Fragment;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
//import android.support.v4.app.Fragment;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link MapFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link MapFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class MapFragment extends SupportMapFragment implements OnMapReadyCallback {
private GoogleMap mGoogleMap;
#Override
public void onResume() {
super.onResume();
if (mGoogleMap == null) {
getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
// latitude and longitude
double latitude = 17.385044;
double longitude = 78.486671;
// create marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(17.385044, 78.486671)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
}

How to use an alert dialog to search for an address in google maps api v2?

I've made an AlertDialog with an EditText, and I want that when the user clicks on 'Buscar' (positiveButton) the map shows a Marker in the address entered on the AlertDialog. So I think I need to pass the data from this EditText to the MapFragment in order to use the Geocoder with that data.
Here's my mainActivity.java with the AlertDialog:
package com.example.alex.testing_map;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
public class MapsActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private String location = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(
this, drawerLayout, toolbar, R.string.openDrawer, R.string.closeDrawer);
drawerLayout.setDrawerListener(drawerToggle);
drawerToggle.syncState();
Fragment fragment = new MapFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.frame_content, fragment);
ft.commit();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.add_item:
Intent intent = new Intent(this, AddMail.class);
this.startActivity(intent);
break;
case R.id.search:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Dirección");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("Buscar", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
location = input.getText().toString();
}
});
builder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()){
case R.id.mapa:
fragment = new MapFragment();
FragmentTransaction ft1 = getSupportFragmentManager().beginTransaction();
ft1.replace(R.id.frame_content, fragment);
ft1.commit();
getSupportActionBar().setTitle(R.string.app_name);
break;
case R.id.help:
fragment = new Help();
FragmentTransaction ft2 = getSupportFragmentManager().beginTransaction();
ft2.replace(R.id.frame_content, fragment);
ft2.commit();
getSupportActionBar().setTitle(item.getTitle());
break;
case R.id.about:
fragment = new About();
FragmentTransaction ft3 = getSupportFragmentManager().beginTransaction();
ft3.replace(R.id.frame_content, fragment);
ft3.commit();
getSupportActionBar().setTitle(item.getTitle());
break;
case R.id.rate:
Intent face = new Intent(Intent.ACTION_VIEW);
face.setData(Uri.parse("fb://profile/" + "100000914715145"));
startActivity(face);
break;
default:
return true;
}
DrawerLayout drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
}
And my MapFragment.java:
package com.example.alex.testing_map;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap mMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.map_fragment, viewGroup, false);
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
SupportMapFragment fragment = new SupportMapFragment();
transaction.replace(R.id.mapView, fragment);
transaction.commit();
fragment.getMapAsync(this);
return view;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
}
}
mMap.getUiSettings().setCompassEnabled(false);
mMap.getUiSettings().setIndoorLevelPickerEnabled(false);
mMap.getUiSettings().setMapToolbarEnabled(false);
mMap.getUiSettings().setRotateGesturesEnabled(false);
mMap.getUiSettings().setZoomControlsEnabled(false);
// Primer poso les coordenades i estableixo els punts (numerats amb lletres en castellà)
// i després afegeixo els marcadors, posant de localització
// el nom dels punts definits amb anterioritat
LocationManager locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
LatLng p1 = new LatLng(41.39355, 2.15473);
mMap.addMarker(new MarkerOptions().position(p1).icon(BitmapDescriptorFactory.fromResource(R.drawable.pointer_bici1)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18));
}
}
As I understand what you are trying to do, the AlertDialog you are showing is like a search dialog where you put in the address query and when the Buscar button is clicked, you want it to be sent to the MapFragment, where it will be used by your Geocoder.
To put it simply, the only issue you have is passing the location value from the EditText to the MapFragment. Looked around the community and found this answer on How to pass data from Activity to Fragment by using setArguments(), like so:
Bundle bundle = new Bundle();
bundle.putString(key, value); // preferred key and the location string you want
fragment.setArguments(bundle);
Then receive it in the Fragment like so:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext=getArguments().getString("message"); // replace "message" with the key you used.
return inflater.inflate(R.layout.fragment, container, false);
}
You can also use a listener, if you want.

Add google maps api v2 in a drawerlayout fragment

I have been trying to insert a map in a drawer layout with a fragment using Android Studio. I have already achieved to display a map, but I can't add markers to it. I wanted to know what am I doing wrong. And is there any other way to add a map to a drawer layout?
Here's my MainActivity:
package com.example.alex.testing_map;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MapsActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(
this, drawerLayout, toolbar, R.string.openDrawer, R.string.closeDrawer);
drawerLayout.setDrawerListener(drawerToggle);
drawerToggle.syncState();
Fragment fragment = new MapFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.frame_content, fragment);
ft.commit();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.add_item:
Intent intent = new Intent(this, AddMail.class);
this.startActivity(intent);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()){
case R.id.mapa:
fragment = new MapFragment();
FragmentTransaction ft1 = getSupportFragmentManager().beginTransaction();
ft1.replace(R.id.frame_content, fragment);
ft1.commit();
break;
case R.id.help:
fragment = new Help();
FragmentTransaction ft2 = getSupportFragmentManager().beginTransaction();
ft2.replace(R.id.frame_content, fragment);
ft2.commit();
break;
case R.id.about:
break;
default:
return true;
}
DrawerLayout drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
}
My MapFragment:
package com.example.alex.testing_map;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapFragment extends Fragment implements OnMapReadyCallback{
private GoogleMap mMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.map_fragment, viewGroup, false);
return view;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setCompassEnabled(false);
mMap.getUiSettings().setIndoorLevelPickerEnabled(false);
mMap.getUiSettings().setMapToolbarEnabled(false);
mMap.getUiSettings().setRotateGesturesEnabled(false);
mMap.getUiSettings().setZoomControlsEnabled(false);
LatLng p1 = new LatLng(41.39355, 2.15473);
mMap.addMarker(new MarkerOptions().position(p1));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(p1, 18));
}
}
With this everything runs well, but markers are not displayed. I've tried to add this (and all the variants I have found) to the MapFragment class, but it says "cannot resolve method 'getSupportFragmentManager' ":
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
My xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="513dp"
tools:context="com.example.alex.testing_map.MapsActivity"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
</RelativeLayout>
I found a solution!! I've followed the answer given by Boss here: Trying to put a map in a fragment activity
I've only changed a little thing. Instead of adding the fragment in the transaction, I have replaced it (in the MapFragment.java), and then in the onCreate in the MainActivity I've added the fragment instead of replacing it.
In the MainActivity (inside the onCreate):
Fragment fragment = new MapFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.frame_content, fragment);
ft.commit();

Categories

Resources