I've been trying to add a Nav Drawer to my app. I have this MapsActivty which is my main activity.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
public GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#SuppressWarnings("StatementWithEmptyBody")
public void onMapSearch(View view) {
EditText locationSearch = (EditText) findViewById(R.id.editText);
String location = locationSearch.getText().toString();
List<Address> addressList = null;
if (location != null || !location.equals("")) {
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
public void onNormalMap(View view) {
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
public void onSatelliteMap(View view) {
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
}
public void onTerrainMap(View view) {
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
}
public void onHybridMap(View view) {
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
}
public static double lng;
public static double lat;
#Override
public void onMapReady(final GoogleMap googleMap) {
mMap = googleMap;
Button btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent (v.getContext(), RegistroInfo.class);
intent.putExtra("longitud", String.valueOf(lng));
intent.putExtra("latitud", String.valueOf(lat));
startActivityForResult(intent, 0);
} });
//View v;
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng point) {
mMap.addMarker(new MarkerOptions().position(point).title("Custom location").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
RegistroInfo regis = new RegistroInfo();
lng = point.longitude;
lat = point.latitude;
}
});
// Add a marker in Sydney and move the camera
LatLng cusco = new LatLng(-13.537733, -71.903838);
mMap.addMarker(new MarkerOptions().position(cusco).title("Cusco, Peru"));
float zoomLevel = 16; //This goes up to 21
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(cusco, zoomLevel));
mMap.moveCamera(CameraUpdateFactory.newLatLng(cusco));
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
return;
}
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setIndoorLevelPickerEnabled(true);}}
NOTICE that a use extends FragmentActivityand i saw that i could use extends MenuActivity from my MenuActivity I tried this post [Same Navigation Drawer in different Activities)
From my Menu Activity i have some items, which are the MapsActivity( nav_MenuPrincipal ), PerfilActivity(another activity showing information of current user) nav_perfil, NormalMap(style of map) nav_normal, SatelliteMap(style of map) nav_satellite, TerrainMap(style of map)nav_terrainmap, HybridMap(style of map)nav_hybrid
Here goes the MenuActivity
public class MenuActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
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();
}
}
#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, 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_MenuPrincipal) {
startActivity(new Intent(this, MapsActivity.class));
return true;
}
else if (id == R.id.nav_perfil) {
}
else if (id == R.id.nav_suggestions) {
} else if (id == R.id.nav_normalmap) {
} else if (id == R.id.nav_satellitemap) {
} else if (id == R.id.nav_terrainmap) {
} else if (id == R.id.nav_hybridmap) {
} else if (id == R.id.nav_aboutus) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Notice that I've tried this if (id == R.id.nav_MenuPrincipal) { startActivity(new Intent(this, MapsActivity.class)); return true; }, it works but not showing the menu bar.
For the items called Normal, Satellite, Terrain, Hybridi just want to change the style of the map for the MapsActivity
Now I'm using a LoginActivity which is already connected to a DB on a Hosting, it has the intent filter. Then i want to show my MainActivity (MapsActivity) but with that Menu (NavigationDrawer)
Thank you very much.
Sorry if I'm not very clear, its my first time here
here is your solution
public class MapsActivity extends AppCompatActivity implements
OnMapReadyCallback, NavigationView.OnNavigationItemSelectedListener,
OnClickListener {
private GoogleMap mMap;
private NavigationView mDrawer;
private DrawerLayout mDrawerLayout;
SupportMapFragment mMapFragment;
private ActionBarDrawerToggle mDrawerToggle;
private Button search;
int PLACE_PICKER_REQUEST = 1;
String placeName, address;
private static final float ALPHA_DIM_VALUE = 0.1f;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mMapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
try {
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
overridePendingTransition(R.anim.push_up_in,
R.anim.push_up_out);
} else {
mMapFragment.getMapAsync(this);
overridePendingTransition(R.anim.push_up_out,
R.anim.push_up_in);
}
} catch (Exception e) {
e.printStackTrace();
}
setupDrawer();
mDrawerLayout.addDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
private void showErrorToast() {
Toast.makeText(getApplicationContext(), getApplicationContext().getString(R.string.Toast_Error), Toast.LENGTH_SHORT).show();
}
private void setupDrawer() {
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
mDrawer = (NavigationView) findViewById(R.id.mNavDrawer);
assert mDrawer != null;
mDrawer.setNavigationItemSelectedListener(this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.string.DrawerOpen,
R.string.DrawerClose) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.addDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
Intent intent = null;
if (item.getItemId() == R.id.navigation_item_1) {
mDrawerLayout.closeDrawer(GravityCompat.START);
intent = new Intent(this, LocationList.class);
startActivity(intent);
overridePendingTransition(R.anim.push_up_in,
R.anim.push_up_out);
finish();
return true;
}
if (item.getItemId() == R.id.navigation_item_2) {
mDrawerLayout.closeDrawer(GravityCompat.START);
intent = new Intent(this, MapsActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.push_up_in,
R.anim.push_up_out);
finish();
return true;
}
mDrawerLayout.closeDrawers();
return true;
}
#Override
protected void onPostCreate(#Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (id == android.R.id.home) {
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
}
just copy reliable code.. and have any doubt about Map then ask me.. i have all your solution regarding map.
Related
I am trying to show the current location in the textview that is in Toolbar, whenever I get the location, the app crashes. Because it cannot show the location in the TextView in the toolbar. need help.
here is the code of mainactivity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, LocationListener {
private TextView address;
private LocationManager locationManager;
private boolean gps;
private double Latitude;
private double Longitude;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
address = (TextView) findViewById(R.id.textView2);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
gps = locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);
if(!gps){
showSettingAlert();
}
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M);
{
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]
{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.INTERNET}, 10);
return;
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, (LocationListener) this);
}
}
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);
}
private void showSettingAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle("GPS settings");
alertDialog.setMessage("GPS is off.Do you want to go to the Settings menu?");
// positive button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
MainActivity.this.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates((LocationListener) this);
}
#Override
public void onLocationChanged(Location location) {
Latitude = (location.getLatitude());
Longitude = (location.getLongitude());
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = new ArrayList<>();
try {
addresses = geocoder.getFromLocation(Latitude,Longitude,1);
} catch (IOException e) {
e.printStackTrace();
}
String cityName = addresses.get(0).getLocality().toString();
String sublocal = addresses.get(0).getSubLocality().toString();
String addr = sublocal + ", " +cityName;
address.setText(addr);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
#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) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_camera) {
} 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;
}
}
now I am getting the address of my current location, but whenever it tries to show in the address = (TextView) findViewById(R.id.searchEditText); it shows error and app crashes. Here is the toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
local:popupTheme="#style/AppTheme.PopupOverlay"
local:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<TextView
android:id="#+id/searchEditText"
android:text="Getting Location"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>
</android.support.v7.widget.Toolbar>
LogCat is here.
12-13 17:03:48.566 30101-30101/com.wanderalchemy.wanderalchemydraft1 D/AndroidRuntime: Shutting down VM
12-13 17:03:48.568 30101-30101/com.wanderalchemy.wanderalchemydraft1 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.wanderalchemy.wanderalchemydraft1, PID: 30101
java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference
at com.wanderalchemy.wanderalchemydraft1.MainActivity.onLocationChanged(MainActivity.java:159)
at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:290)
at android.location.LocationManager$ListenerTransport.-wrap0(LocationManager.java)
at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:235)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5811)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:681)
12-13 17:03:54.641 30101-30112/com.wanderalchemy.wanderalchemydraft1 I/System: FinalizerDaemon: finalize objects = 38
12-13 17:03:54.647 30101-30157/com.wanderalchemy.wanderalchemydraft1 D/OpenGLRenderer: ~CanvasContext() 0xaf797000
12-13 17:04:03.404 30101-30101/com.wanderalchemy.wanderalchemydraft1 I/Process: Sending signal. PID: 30101 SIG: 9
Use this
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
address = (TextView) toolbar.findViewById(R.id.searchEditText);
Instead of this
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
address = (TextView) findViewById(R.id.searchEditText);
EDIT
List<Address> addresses = new ArrayList();
Try this
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
address = (TextView)toolbar.findViewById(R.id.searchEditText);
I am trying to handle NavigationView click listener for back button but it is not working.
navigationView.setOnClickListener may be enough but may be it's due to some other reason that's why added full class
MainActivity.class
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private ActionBarDrawerToggle toggle;
private DrawerLayout drawerLayout;
private NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
resetActionBar();
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
onBackPressed();
}
});
getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.content_fragment, new CameraFragment()).commit();
}
#Override
public void onBackPressed() {
//super.onBackPressed();
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.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == android.R.id.home)
{
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
onBackPressed();
else
drawerLayout.openDrawer(navigationView);
return true;
}else 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();
Fragment fragment = null;
if (id == R.id.nav_camera) {
// Handle the camera action
fragment = new CameraFragment();
} else if (id == R.id.nav_gallery) {
fragment = new GalleryFragment();
} else if (id == R.id.nav_slideshow) {
fragment = new SlideShowFragment();
} 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);
if(fragment!=null){
if(item.isChecked())
{
if(getSupportFragmentManager().getBackStackEntryCount()==0){
drawer.closeDrawers();
}else{
removeAllFragments();
getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.content_fragment, fragment).commit();
drawer.closeDrawer(GravityCompat.START);
}
}else{
removeAllFragments();
getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.content_fragment, fragment).commit();
drawer.closeDrawer(GravityCompat.START);
}
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void removeAllFragments(){
getSupportFragmentManager().popBackStackImmediate(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
public void replaceFragment(final Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.replace(R.id.content_fragment, fragment).addToBackStack("")
.commit();
}
public void updateDrawerIcon() {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
try {
Log.i("", "BackStackCount: " + getSupportFragmentManager().getBackStackEntryCount());
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
toggle.setDrawerIndicatorEnabled(false);
else
toggle.setDrawerIndicatorEnabled(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}, 50);
}
public void resetActionBar()
{
//display home
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
public void setActionBarTitle(String title) {
getSupportActionBar().setTitle(title);
}
}
Answer found by Mike M Comment:
remove navigation.setOnClickListener and replace it to
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
onBackPressed();
}
});
Hi im try to find location in fragment. but i cannot get location.
LocationManager locationmanager= (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE); return null.how can i fix it
SocialFragment.java
public class SocialFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_maps, container, false);
mMapView = (MapView) rootView.findViewById(R.id.map);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
// For dropping a marker at a point on the Map
LatLng sydney = new LatLng(-34, 151);
googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker Title").snippet("Marker Description"));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
LocationManager locationmanager= (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationmanager.getBestProvider(criteria, false);
if (ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
}
});
return rootView;
}
#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();
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
ArrayList country, city, districts;
StringBuffer stringBuffer = new StringBuffer();
String response;
#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);
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new TabFragment()).commit();
try {
City();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
#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;
}}
Please add logcat errors or result for more details. Meanwhile try this in your onMapready:
// enable location buttons
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// fetch last location if any from provider - GPS.
final LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
final Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc == null) {
final LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(final Location location) {
// getting location of user
final double latitude = location.getLatitude();
final double longitude = location.getLongitude();
// do something with Latlng
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
// do something
}
#Override
public void onProviderDisabled(String provider) {
// notify user "GPS or Network provider" not available
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 500, locationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 500, locationListener);
}
else {
// do something with last know location
}
Try by putting
LocationManager locationmanager= (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE); outside of onMapReady
I'm completely new at Android. I was quite surprised that Android Studio does not have a template for navigation between fragments. I have spent several days now, but still cannot make my code work properly.
I have single activity and two fragments - MainFragment and AboutFragment. About is accessible via drawer menu item. I want to return to MainFragment by pressing back action bar button. The problem is button is not working. Can anyone help me?
Complete minimal Android Studio project:
test.zip
Here is my activity class:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener,
MainFragment.OnFragmentInteractionListener, AboutFragment.OnFragmentInteractionListener {
private DrawerLayout drawer;
private boolean zOrderSet = false;
private ActionBarDrawerToggle toggleListener;
private FragmentManager.OnBackStackChangedListener mOnBackStackChangedListener =
new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
syncActionBarArrowState();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggleListener = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
if (!zOrderSet) {
drawer.bringChildToFront(drawerView);
drawer.requestLayout();
drawer.invalidate();
zOrderSet = true;
}
}
public void onDrawerClosed(View view) {
syncActionBarArrowState();
}
public void onDrawerOpened(View drawerView) {
toggleListener.setDrawerIndicatorEnabled(true);
}
};
drawer.setDrawerListener(toggleListener);
toggleListener.syncState();
getSupportFragmentManager().addOnBackStackChangedListener(mOnBackStackChangedListener);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getSupportFragmentManager().beginTransaction().replace(R.id.flContent, MainFragment.newInstance("", "")).commit();
}
#Override
protected void onDestroy() {
getSupportFragmentManager().removeOnBackStackChangedListener(mOnBackStackChangedListener);
super.onDestroy();
}
private void syncActionBarArrowState() {
boolean empty = getSupportFragmentManager().getBackStackEntryCount() == 0;
toggleListener.setDrawerIndicatorEnabled(empty);
getSupportActionBar().setDisplayHomeAsUpEnabled(!empty);
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (toggleListener.isDrawerIndicatorEnabled() && toggleListener.onOptionsItemSelected(item)) {
return true;
}
int id = item.getItemId();
if (id == android.R.id.home && getSupportFragmentManager().popBackStackImmediate()) {
return true;
}
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
FragmentTransaction ta = getSupportFragmentManager().beginTransaction();
try {
switch (item.getItemId()) {
case R.id.nav_restart:
ta.replace(R.id.flContent, MainFragment.class.newInstance());
break;
case R.id.nav_about:
ta.replace(R.id.flContent, AboutFragment.class.newInstance()).addToBackStack(null);
break;
default:
return false;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
ta.commit();
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
}
#Override
public void onBackPressed(){
getActivity().getFragmentManager().beginTransaction().remove(this).commit();
}
In my Activity I have a drawer list that pops from the right but I'm not able to move the drawer toggle from the left to the right side. Please if somebody can help me solve this issue.I just want to move the toggle to the right of the action bar.
package com.parse.starter;
import com.parse.ParseUser;
public class UserDrawer extends AppCompatActivity {
//Declaring Variables
private ListView DrawerList;
private ArrayAdapter<String> Adapter;
private ActionBarDrawerToggle DrawerToggle;
private DrawerLayout DrawerLayout;
private String ActivityTitle;
final ParseUser currentUser = ParseUser.getCurrentUser();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_drawer);
DrawerList = (ListView) findViewById(R.id.navList);
DrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
Button Sample = (Button) findViewById(R.id.button);
}
//Method To Add Items To The List View
private void addDrawerItems() {
String[] DArray = {"Job List", "Notifications", "Messages", "Log Out"};
Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, DArray);
DrawerList.setAdapter(Adapter);
DrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
Intent i0 = new Intent(UserDrawer.this, Set_Info.class);
startActivity(i0);
} else if (position == 1) {
//Intent i1 = new Intent(Drawer1.this, AddPatient.class);
//startActivity(i1);
} else if (position == 2) {
//Intent i2 = new Intent(Drawer1.this, Notifications.class);
//startActivity(i2);
} else if (position == 3) {
//Intent i3 = new Intent(Drawer1.this, Message_Log.class);
//startActivity(i3);
} else if (position == 4) {
Intent i4 = new Intent(UserDrawer.this, MainActivity.class);
startActivity(i4);
Toast.makeText(getApplicationContext(), "You are Logged Out", Toast.LENGTH_LONG).show();
finish();
}
}
});
}
private void setupDrawer() {
DrawerToggle = new ActionBarDrawerToggle(this, DrawerLayout,
R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Menu");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(ActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
DrawerToggle.setDrawerIndicatorEnabled(true);
DrawerLayout.setDrawerListener(DrawerToggle);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item != null && item.getItemId()==android.R.id.home){
if(DrawerLayout.isDrawerOpen(Gravity.RIGHT)){
//Notice the Gravity.Right
DrawerLayout.closeDrawer(Gravity.RIGHT);
}else{
DrawerLayout.openDrawer(Gravity.RIGHT);
}
}
return false;
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
DrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
DrawerToggle.onConfigurationChanged(newConfig);
}
#SuppressWarnings("ResourceType")
public void SampleClick(View view) {
try {
Intent i = new Intent(UserDrawer.this,Set_Info.class);
startActivity(i);
} catch (Exception e) {
}
}
}