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);
Related
here is my java code
that is the java code, I have added navigation profile activity then run it after retrieving the image and user name from the firebase. the navigation buttons are no more clickable
public class OwnerDrawer extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private FirebaseAuth OwnerAuth;
private DatabaseReference OwnerRef;
private CircleImageView OwnNavProfileImge;
private TextView OwnNavProfileName;
String currentUserID;
private NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_owner_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
OwnerAuth = FirebaseAuth.getInstance();
OwnerRef = FirebaseDatabase.getInstance().getReference().child("Users");
currentUserID = OwnerAuth.getCurrentUser().getUid();
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();
}
});
//for the navigation drawer button to open and close
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.addDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
View navView = navigationView.inflateHeaderView(R.layout.nav_header_owner_drawer);
OwnNavProfileName = (TextView)navView.findViewById(R.id.NavOwnerUserName);
OwnNavProfileImge = (CircleImageView)navView.findViewById(R.id.NavOwnerProfileImage);
OwnerRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if(dataSnapshot.exists()) {
if(dataSnapshot.hasChild("fullname"))
{
String fullname = dataSnapshot.child("fullname").getValue().toString();
OwnNavProfileName.setText(fullname);
}
if(dataSnapshot.hasChild("profileimage"))
{
String image = dataSnapshot.child("profileimage").getValue().toString();
Picasso.with(OwnerDrawer.this).load(image).placeholder(R.drawable.profile).into(OwnNavProfileImge);
}
else
{
Toast.makeText(OwnerDrawer.this, "Profile name does not exist...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = OwnerAuth.getCurrentUser();
if(currentUser == null)
{
SendUserTologinActivity();
}
else
{
CheckUserExistence();
}
}
// to see if the user validation and his authenticated so if not, the user will be send to the setup activity.
private void CheckUserExistence()
{
final String current_user_id = OwnerAuth.getCurrentUser().getUid();
OwnerRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if(!dataSnapshot.hasChild(current_user_id))
{
SendUserToSetupActivity();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void SendUserToSetupActivity()
{
Intent setupIntent = new Intent(OwnerDrawer.this, OwnerSetup.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(setupIntent);
finish();
}
private void SendUserTologinActivity() {
Intent loginIntent = new Intent(OwnerDrawer.this,OwnerLogin.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
// To open the menu button
#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_Home) {
Toast.makeText(this, "Home", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_Profile) {
Toast.makeText(this, "Profile", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_Posting_Cars) {
Toast.makeText(this, "Post Cars", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_Chat) {
Toast.makeText(this, "Chat", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_Edit_profile) {
Toast.makeText(this, "Edit Profile", Toast.LENGTH_SHORT).show();
}
else if (id == R.id.nav_Logout) {
OwnerAuth.signOut();
SendUserTologinActivity();
Toast.makeText(OwnerDrawer.this, "Logged Out Successfull...", Toast.LENGTH_SHORT).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
To receive callbacks when the user taps a list item in the drawer, implement the OnNavigationItemSelectedListener and attach it to your NavigationView by calling setNavigationItemSelectedListener().
You need to attach the navigationView to listener
navigationView.setNavigationItemSelectedListener(this);
Hope this helps.
I'm trying to detect the connection state of my app, but this is the Error am facing:
Failed to convert value of type java.util.HashMap to boolean
I am using Firebase. The error is on line:
boolean connected = dataSnapshot.getValue(Boolean.class);
So the Error comes in the OnDataFinishedLoading() method . Data was coming at first, but now I just want to detect the apps network connection. Below is my code:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public static String KEY_HEADLINES="headlines";
public static String KEY_DETAILS="details";
// private static final String TAG = "Ask Doctor App";
ProgressBar pb;
public List<NewsModel> newslist;
public NewsAdapter2 adapter;
private RecyclerView mRecyclerView;
private DatabaseReference mRef;
ImageView image_news;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// call the array list
newslist = new ArrayList<NewsModel>();
pb = (ProgressBar) findViewById(R.id.progressBarNews);
image_news =(ImageView) findViewById(R.id.image_news);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
//Enabling offline capabilities
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
// firebase initialisation......
mRef = FirebaseDatabase.getInstance().getReference("News");
// keep my data synced
mRef.keepSynced(true);
OnDataFinishedLoading();
// load data
//declare the toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//NetworkInfo netInfo = cm.getActiveNetworkInfo();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/* if (isOnline()) {
Snackbar.make(view, "Refreshing news ....", Snackbar.LENGTH_LONG)
.setAction("Thanks.", null).show();
} else {
Snackbar.make(view, "There's a Network problem", Snackbar.LENGTH_LONG)
.setAction("", null).show();
}
Snackbar.make(view, "Refreshing news ....", Snackbar.LENGTH_LONG)
.setAction("Thanks.", 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 OnDataFinishedLoading(){
mRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
boolean connected = dataSnapshot.getValue(Boolean.class);
if(connected) {
pb.setVisibility(View.INVISIBLE);
LoadData(dataSnapshot);
} else{
Toast.makeText(MainActivity.this,"No Network",Toast.LENGTH_LONG).show();
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
LoadData(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void LoadData (DataSnapshot dataSnapshot){
System.out.println(dataSnapshot.getValue());
NewsModel news_model =dataSnapshot.getValue(NewsModel.class);
newslist.add(news_model);
adapter = new NewsAdapter2(MainActivity.this, newslist);
mRecyclerView.setAdapter(adapter);
}
/* protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return 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.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();
Intent i;
if (id == R.id.hospitals) {
i = new Intent(MainActivity.this, HealthCentres.class);
startActivity(i);
} else if (id == R.id.doctors) {
i = new Intent(MainActivity.this, Doctors.class);
startActivity(i);
} /*else if (id == R.id.location) {
i = new Intent(MainActivity.this, Location.class);
startActivity(i);
} */else if (id == R.id.tips) {
i = new Intent(MainActivity.this, Tips.class);
startActivity(i);
} /*else if (id == R.id.faq) {
}
*/
/*
else if (id == R.id.suggestions) {
}
*/
else if (id == R.id.contacts) {
i= new Intent(MainActivity.this, ContactUs.class);
startActivity(i);
}
/*
else if (id == R.id.settings) {
}
*/
else if (id == R.id.about) {
i = new Intent(MainActivity.this, AboutUs.class);
startActivity(i);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Ok, so the core problem you're having is that Firebase is returning a Map, not a Boolean. That's because of the way you have this configured--every time a child is added, you try to look at the DataSnapshot (that's what the listener you setup does), and tries to get a Boolean value out. However, the Snapshot is the child added to the database (and not a boolean) so instead you get a map out.
If all you want to do is verify that a child was added successfully, I'd do the following:
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Object value = dataSnapshot.getValue();
if(value != null) {
pb.setVisibility(View.INVISIBLE);
LoadData(dataSnapshot);
} else{
Toast.makeText(MainActivity.this,"No Network",Toast.LENGTH_LONG).show();
}
}
However, this isn't really going to solve your network connectivity problem. It'll just do stuff whenever a non-null child gets added to the firebase object, which could happen frequently. Also in LoadData, you don't check to make sure that the object passed in isn't null.
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 am developing an app and want users to be able to use their phones horizontally or vertically, however, if I start in portrait and switch to landscape, the app crashes. It also crashes if I start landscape and switch to portrait.
Here is my AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme.NoActionBar"
android:screenOrientation="sensor">
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="#string/facebook_app_id"/>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar"
android:configChanges="screenSize|keyboardHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="net.sourceforge.zbar.android.CameraTest.CameraTestActivity" />
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:theme="#android:style/Theme.Translucent.NoTitleBar"
android:label="#string/app_name" />
</application>
I have already tried this this, but then the app cannot go to landscape as described here.
Here is the activity that it crashed in (MainActivity):
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, UserDelegate {
private static final int SCAN_COUPONS = 1;
public GoogleApiClient googleApiClient;
private Location lastLocation;
EditText zip;
public static User user;
public SharedPreferences sharedPreferences;
public static SQLiteDatabase database;
#Override
protected void onStart() {
googleApiClient.connect();
super.onStart();
}
#Override
protected void onStop() {
googleApiClient.disconnect();
super.onStop();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nav_bar_container);
/*
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
actionBar.setCustomView(R.layout.actionbar);
}
*/
sharedPreferences = this.getPreferences(Context.MODE_PRIVATE);
database = openOrCreateDatabase("CouponWallet", MODE_PRIVATE, null);
/*Typeface iconFont = FontManager.getTypeface(getApplicationContext(), FontManager.FONTAWESOME);
FontManager.markAsIconContainer(findViewById(R.id.content_main), iconFont);
FontManager.markAsIconContainer(findViewById(R.id.drawer_layout), iconFont);
//FontManager.markAsIconContainer(findViewById(R.id.nav_drawer), iconFont);
FontManager.markAsIconContainer(findViewById(R.id.top_toolbar), iconFont);
FontManager.markAsIconContainer(findViewById(R.id.bottom_toolbar), iconFont);*/
FontIconTypefaceHolder.init(getAssets(), "fonts/FontAwesome.ttf"); //allows for icons
// set up toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.top_toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle("Coupon Wallet");
toolbar.hideOverflowMenu();
FontManager.setFont(findViewById(R.id.top_toolbar), FontManager.getTypeface(this, FontManager.CANDY));
googleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
Log.v("onCreate", "api client created");
//set up drawer
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
new Thread(new Runnable() {
#Override
public void run() { // does ouside of ui thread
setIcons();
}
}).start();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
/*if(sharedPreferences.getInt("user_id", 0) == 0){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, new LoginFragment());
ft.addToBackStack(null);
ft.commit();
getSupportActionBar().setTitle("Login");
}*/
//user = new User(sharedPreferences.getInt("user_id", 1), database);
//if (Functions.isOnline()) {
Log.v("onCreate", "creating user " + sharedPreferences.getInt("user_id", 1));
this.user = new User(1, this);
//}
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
FragmentManager fm = getFragmentManager();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
if (fm.getBackStackEntryCount() > 0) {
fm.popBackStack();
} 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);
LayerDrawable layerDrawable = (LayerDrawable) menu.findItem(R.id.action_barcode).getIcon();
layerDrawable.setDrawableByLayerId(R.id.main_icon, Functions.getFAIcons(this).get("barcode"));
Functions.setBadgeCount(this, layerDrawable, 2, R.id.num_circle);
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();
if (id == R.id.action_barcode) {
final AlertDialog dialog = new AlertDialog.Builder(this).setView(R.layout.redeem_code_layout).create();
dialog.show();
Toolbar toolbar = (Toolbar) dialog.findViewById(R.id.redeem_toolbar);
toolbar.inflateMenu(R.menu.redeem_menu);
toolbar.setTitle("Redeem Codes");
toolbar.setNavigationIcon(Functions.getFAIcons(this).get("times"));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
toolbar.inflateMenu(R.menu.redeem_menu);
toolbar.hideOverflowMenu();
toolbar.setTitleTextColor(getResources().getColor(R.color.colorBlack));
FontManager.setFont(toolbar, FontManager.getTypeface(this, FontManager.CHAMPAGNE));
MenuItem help = toolbar.getMenu().add("Help");
help.setIcon(Functions.getFAIcons(this).get("question"));
help.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
Toast.makeText(getApplicationContext(), "Help Clicked", Toast.LENGTH_LONG).show();
return false;
}
});
final ImageView code = (ImageView) dialog.findViewById(R.id.redeem_code);
code.setImageDrawable(user.barcode);
Spinner spinner = (Spinner) dialog.findViewById(R.id.redeem_scan_type);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_item, new String[]{"Barcode", "QR Code", "PDF417", "Aztec"});
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
switch (i) {
case 0:
code.setImageDrawable(user.barcode);
break;
case 1:
code.setImageDrawable(user.qr_code);
break;
case 2:
code.setImageDrawable(user.pdf417);
break;
case 3:
code.setImageDrawable(user.aztec);
break;
}
/*for(int j = 0; j < 4; j++){
if (i != j) {
TextView item = ((TextView) adapterView.getChildAt(j));
item.setBackgroundColor(getResources().getColor(R.color.colorWhite));
item.setTextColor(getResources().getColor(R.color.colorGray));
} else {
TextView item = ((TextView) adapterView.getChildAt(j));
item.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
item.setTextColor(getResources().getColor(R.color.colorWhite));
}
}*/
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
code.setImageDrawable(user.barcode);
}
});
TextView textView = (TextView) dialog.findViewById(R.id.redeem_num);
long uid = user.id;
textView.setText(String.format(Locale.US, "%s%011d", "891", uid));
}
return super.onOptionsItemSelected(item);
}
/**
* #param item item selected in nav menu
* #return if view switch was successful
*/
//#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
Fragment fragment = null;
String title = "";
Toolbar toolbar = (Toolbar) findViewById(R.id.bottom_toolbar);
toolbar.getMenu().clear();
switch (id) { //based on which section was selected
case R.id.nav_search:
title = "Search";
fragment = new SearchFragment();
toolbar.setVisibility(View.VISIBLE);
toolbar.setNavigationIcon(Functions.getFAIcons(getApplicationContext()).get("gear"));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("bottom_toolbar", "horizontal clicked");
}
});
toolbar.inflateMenu(R.menu.my_wallet);
MenuItem map1 = toolbar.getMenu().getItem(0); //only item in the menu
map1.setIcon(Functions.getFAIcons(getApplicationContext()).get("map"));
map1.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
Log.v("bottom_toolbar", "map clicked");
return true;
}
});
break;
case R.id.nav_profile:
title = "Profile";
break;
case R.id.nav_notifications:
title = "Notifications";
break;
case R.id.nav_categories:
try {
lastLocation = getLastKnownLocation();
if (lastLocation != null) {
Log.v("categories", "Location accessed");
Bundle bundle2 = new Bundle();
bundle2.putDouble("lat", lastLocation.getLatitude());
bundle2.putDouble("lon", lastLocation.getLongitude());
bundle2.putString("type", "loc");
fragment = new CategoriesFragment();
fragment.setArguments(bundle2);
title = "Categories";
toolbar.setVisibility(View.VISIBLE);
toolbar.setNavigationIcon(Functions.getFAIcons(getApplicationContext()).get("gear"));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("bottom_toolbar", "horizontal clicked");
}
});
toolbar.inflateMenu(R.menu.categories);
break;
}
} catch (SecurityException e) { // if can't get location go straight to search
}
Log.v("categories", "Location not accessable");
Toast.makeText(this, "Turn on location services get faster results", Toast.LENGTH_LONG).show();
AlertDialog dialog2 = new AlertDialog.Builder(this).setView(R.layout.get_zip_dialog).setPositiveButton("Set", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
}).create();
dialog2.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialogInterface) {
dialogInterface.dismiss();
Toast.makeText(getApplicationContext(), "Cannot get local categories without location", Toast.LENGTH_LONG).show();
}
});
zip = (EditText) findViewById(R.id.zip_code);
dialog2.show();
break;
case R.id.nav_wallet:
fragment = new MyWalletFragment(); //sets up view
// setting up toolbars
title = "My Wallet";
toolbar.setVisibility(View.VISIBLE);
toolbar.setNavigationIcon(Functions.getFAIcons(getApplicationContext()).get("columns"));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("bottom_toolbar", "horizontal clicked");
}
});
toolbar.inflateMenu(R.menu.my_wallet);
MenuItem map = toolbar.getMenu().getItem(0); //only item in the menu
map.setIcon(Functions.getFAIcons(getApplicationContext()).get("map"));
map.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
Log.v("bottom_toolbar", "map clicked");
return true;
}
});
//toolbar.setLogo(R.id.horizontal);
break;
case R.id.nav_scan:
title = "Scan Coupons";
Intent intent = new Intent(this, CameraTestActivity.class);
startActivityForResult(intent, SCAN_COUPONS);
break;
case R.id.nav_map:
title = "Map";
break;
case R.id.nav_settings:
fragment = new SettingFragment(); //sets up view
title = "Settings";
break;
case R.id.nav_help:
title = "Help";
// Assuming the Help in the nav bar is the same as the settings menu
fragment = new HelpSettingsFragment();
break;
}
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(null);
ft.commit();
}
FontManager.setFont(findViewById(R.id.content_frame), FontManager.getTypeface(this, FontManager.CHAMPAGNE));
//noinspection ConstantConditions
getSupportActionBar().setTitle(title);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onLocationChanged(Location location) {
Log.v("onLocationChanged", "Location changed");
lastLocation = location;
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.v("onConnected", "connected");
try {
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
} catch (SecurityException e) {
e.printStackTrace();
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
/**
* Process a coupon scan
*
* #param requestCode Type of activity
* #param resultCode if result ok
* #param data the returned data
*/
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_CANCELED) {
Log.e("onActivityResult", "result canceled");
} else if (resultCode == RESULT_OK) {
if (requestCode == SCAN_COUPONS) {
String result = data.getStringExtra("result");
Toast.makeText(this, result, Toast.LENGTH_LONG).show();
Log.v("onActivityResult", result);
}
}
}
/**
* Set the icons in the drawer
*/
private void setIcons() {
Map<String, Drawable> map = Functions.getFAIcons(getApplicationContext());
int[] sections = {R.id.nav_search, R.id.nav_profile, R.id.nav_notifications, R.id.nav_categories, R.id.nav_wallet,
R.id.nav_scan, R.id.nav_map, R.id.nav_settings, R.id.nav_help};
Drawable[] icons = {map.get("search"), map.get("user"), map.get("bookmark"), map.get("list"), map.get("barcode"),
map.get("camera"), map.get("map_o"), map.get("gear"), map.get("question")};
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
Menu m = navigationView.getMenu();
for (int i = 0; i < sections.length; i++) {
MenuItem item = m.findItem(sections[i]);
item.setIcon(icons[i]);
}
}
/**
* Gets the last known Location
*
* #return The last known location
* #throws SecurityException if proper permissions not given
*/
private Location getLastKnownLocation() throws SecurityException {
LocationManager mLocationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
List<String> providers = mLocationManager.getProviders(true);
Location bestLocation = null;
Log.v("getLastKnownLocation", "looping through providers");
for (String provider : providers) {
Log.v("getLastKnownLocation", provider);
Location l = mLocationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
return bestLocation;
}
public void settingOnClick(View v) {
/*
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.logo_shortcut)
.setContentTitle("My notification")
.setContentText("Hello World!");
Intent resultIntent = new Intent(this, MainActivity.class);
// Because clicking the notification opens a new ("special") activity, there's
// no need to create an artificial back stack.
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
// Sets an ID for the notification
int mNotificationId = 001;
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mBuilder.setAutoCancel(true);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
*/
Fragment fragment = null;
switch (v.getId()) {
case R.id.setting_account:
case R.id.setting_userIcon:
fragment = new AccountSettingsFragment();
break;
case R.id.setting_location:
case R.id.setting_locationArrow:
fragment = new LocationSettingsFragment();
break;
case R.id.setting_notifications:
case R.id.setting_notificationIcon:
fragment = new NotificationSettingsFragment();
break;
case R.id.setting_help:
case R.id.setting_helpIcon:
fragment = new HelpSettingsFragment();
break;
case R.id.setting_contact:
case R.id.setting_contactIcon:
fragment = new ContactUsSettingsFragment();
break;
case R.id.setting_privacy:
case R.id.setting_privacyIcon:
fragment = new PrivacyPolicySettingsFragment();
break;
case R.id.setting_about:
case R.id.setting_aboutIcon:
fragment = new AboutSettingsFragment();
break;
case R.id.tutorial_loc_enterAnotherLocation:
fragment = new EnterAnotherLocation();
break;
case R.id.tutorial_1_saving:
case R.id.tutorial_2_saving:
case R.id.tutorial_3_saving:
fragment = new FirstTimeLocation();
break;
}
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(null);
ft.commit();
}
}
#Override
public void userFinished(User user) {
this.user = user;
Log.v("UserFinished", user.toString());
}
}
And the error that i get is here. It is a link to a .txt file as it brings the question over the character limit.
Hii for working in landscape and portrait mode, you have to use saved instance and restore saved instance or else your application values
googleApiClient,lastLocation,zip,user values may have null value and causes this issue
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putBoolean("MyBoolean", true);
savedInstanceState.putDouble("myDouble", 1.9);
savedInstanceState.putInt("MyInt", 1);
savedInstanceState.putString("MyString", "Welcome back to Android");
savedInstanceState.putParcelable("parcelable", "");
savedInstanceState.putSerializable("serializable", "");
}
The Bundle is essentially a way of storing a NVP ("Name-Value Pair") map, and it will get passed in to onCreate() and also onRestoreInstanceState() where you'd extract the values like this:
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
double myDouble = savedInstanceState.getDouble("myDouble");
int myInt = savedInstanceState.getInt("MyInt");
String myString = savedInstanceState.getString("MyString");
}
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.