Add google maps api v2 in a drawerlayout fragment - android

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

Related

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.

run map fragment from navigation drawer

i have been using the navigation drawer and in case 1 i would like to run a google maps API inside a fragment.
but i get the following error:
'replace(int, android.app.Fragment)' in 'android.app.FragmentTransaction' cannot be applied to '(int, com.example.matant.test.MapFragment)'
this is the mainactivity:
package com.example.matant.test;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private ActionBarDrawerToggle actbartoggle;
private android.support.v7.app.ActionBar actionbar;
private DrawerLayout drawer;
private ListView navlist;
private FragmentTransaction frmt;
private FragmentManager frm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawer = (DrawerLayout)findViewById(R.id.drawer);
navlist = (ListView)findViewById(R.id.navlist);
ArrayList<String> navArr = new ArrayList<String>();
navArr.add("Home");
navArr.add("Playing List");
navArr.add("Manage List");
navArr.add("Logout");
navlist.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,navArr);
navlist.setAdapter(adapter);
navlist.setOnItemClickListener(this);
actbartoggle = new ActionBarDrawerToggle(this,drawer,R.string.opendrawer,R.string.closedrawer);
drawer.setDrawerListener(actbartoggle);
actionbar = getSupportActionBar();
actionbar.setDisplayShowHomeEnabled(true);
actionbar.setDisplayHomeAsUpEnabled(true);
frm = getFragmentManager();
loadDefFrag(0);
}
private void loadDefFrag(int i){
navlist.setItemChecked(i,true);
if(i==1){
MapFragment mapf = new MapFragment();
frmt = frm.beginTransaction();
frmt.replace(R.id.fragmentholder, mapf);
frmt.commit();
}else if (i==2){
Fragment2 fr2 = new Fragment2();
frmt = frm.beginTransaction();
frmt.replace(R.id.fragmentholder, fr2);
frmt.commit();
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actbartoggle.syncState();
}
#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) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}else if (id == android.R.id.home){
if(drawer.isDrawerOpen(navlist)){
drawer.closeDrawer(navlist);
}else{
drawer.openDrawer(navlist);
}
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch(position){
case 0:
break;
case 1:
loadDefFrag(position);
break;
case 2:
loadDefFrag(position);
break;
case 3:
break;
}
drawer.closeDrawer(navlist);
}
}
here you can see the mapactivity:
package com.example.matant.test;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.example.matant.test.R;
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 FragmentActivity implements OnMapReadyCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_map);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap map) {
// Add a marker in Sydney, Australia, and move the camera.
LatLng sydney = new LatLng(-34, 151);
map.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
map.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
main layout:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer"
>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragmentholder">
</FrameLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/navlist"
android:background="#dedede"
android:layout_gravity="start">
</ListView>
</android.support.v4.widget.DrawerLayout>
map 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="com.example.matant.test.MapFragment">
<!-- TODO: Update blank fragment layout -->
<fragment 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"
android:id="#+id/map"
tools:context=".MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment" />
</FrameLayout>
You are trying to replace an Activity using FragmentManager. Only a Fragment can be used here.
Either start you MapFragment using startActivity() or extend MapFragment from a Fragment like this
public class MapFragment extends Fragment implements OnMapReadyCallback {
If you follow the second approach you will have to change few other lines in code too where you need context using getActivity()

Navigation drawer Error in replace method while replac ing fragments in onclick event

I am trying to implement navigtion drawer this is my code and i am getting error while running the application.
this is the error in problems of eclipse.
Description Resource Path Location Type
The method replace(int, Fragment) in the type FragmentTransaction is not applicable for the arguments (int, Fragment) MainActivity.java /NavigationDrawer/src/com/example/navigationdrawer line 198 Java Problem.
This is my code of main activity
package com.example.testnav;
import android.os.Bundle;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private String[] drawerListViewItems;
private DrawerLayout drawerLayout;
private ListView drawerListView;
private ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get list items from strings.xml
drawerListViewItems = getResources().getStringArray(R.array.items);
// get ListView defined in activity_main.xml
drawerListView = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
drawerListView.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_listview_item, drawerListViewItems));
// 2. App Icon
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// 2.1 create ActionBarDrawerToggle
actionBarDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
drawerLayout, /* DrawerLayout object */
R.drawable.ic_launcher, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
);
// 2.2 Set actionBarDrawerToggle as the DrawerListener
drawerLayout.setDrawerListener(actionBarDrawerToggle);
// 2.3 enable and show "up" arrow
getActionBar().setDisplayHomeAsUpEnabled(true);
// just styling option
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
drawerListView.setOnItemClickListener(new DrawerItemClickListener());
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
actionBarDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// call ActionBarDrawerToggle.onOptionsItemSelected(), if it returns true
// then it has handled the app icon touch event
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
// Toast.makeText(MainActivity.this, ((TextView)view).getText(), Toast.LENGTH_LONG).show();
displayView(position);
drawerLayout.closeDrawer(drawerListView);
}
}
private void displayView(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new FragmentOne();
break;
case 1:
fragment = new FragmentTwo();
break;
case 2:
fragment = new FragmentThree();
break;
case 3:
fragment = new FragmentOne();
break;
case 4:
fragment = new FragmentOne();
break;
case 5:
fragment = new FragmentOne();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
drawerListView.setItemChecked(position, true);
drawerListView.setSelection(position);
//setTitle((TextView)view).getText());
drawerLayout.closeDrawer(drawerListView);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
}
and this is fragment
package com.example.testnav;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentOne extends Fragment {
public FragmentOne(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
return rootView;
}
}
this is my xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<ListView android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#666"
android:dividerHeight="1dp"
android:background="#333"
android:paddingLeft="15sp"
android:paddingRight="15sp"
/>
</android.support.v4.widget.DrawerLayout>
Try using FragmentActivity in place of Activity
public class MainActivity extends FragmentActivity
and
default:
fragment = new FragmentOne();
break;
I get the same error. Need to modify tow places, as follows.
First, use FragmentActivity
public class MainActivity extends FragmentActivity
Second, change getFragmentManager to getSupportFragmentManager:
FragmentManager fragmentManager = getSupportFragmentManager();

Categories

Resources