com.google.firebase.database.DatabaseException: Invalid Firebase Database path - java

when I try to store my location's latitude and longitude on my database I get this error
01-02 11:54:30.820 24616-24616/? E/Zygote: no v2
01-02 11:54:30.830 24616-24616/? E/SELinux: [DEBUG]
get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
01-02 11:54:33.823 24616-24616/com.rescuex_za.rescuex
E/AndroidRuntime: FATAL EXCEPTION: main
Process:
com.rescuex_za.rescuex,
PID: 24616
com.google.firebase.database.
DatabaseException:
Invalid Firebase Database path:
https://rescuex-8f9c9.firebaseio.com/Users/NcZ0McVHEuRfaMv39gHbDlpjI1X2. Firebase Database paths must not contain
'.', '#', '$', '[', or ']'
at com.google.android.gms.internal.zzelv.zzqh(Unknown Source)
at com.google.firebase.database.DatabaseReference.child(Unknown Source)
at com.rescuex_za.rescuex.MenuActivity.addEmergencyChat(MenuActivity.java:247)
at com.rescuex_za.rescuex.MenuActivity.access$100(MenuActivity.java:55)
at com.rescuex_za.rescuex.MenuActivity$1.onClick(MenuActivity.java:106)
at android.view.View.performClick(View.java:5076)
at android.view.View$PerformClick.run(View.java:20279)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5910)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
this is my class where i send the location's latitude AND Longitude
public class MenuActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,
OnMapReadyCallback,
ConnectionCallbacks,
OnConnectionFailedListener {
private static final String TAG = "RescueX";
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private DatabaseReference mLocationDatabase;
ImageButton fakeCallBtn;
Button mRescue;
ImageButton notif;
ImageButton flash;
private Double lati;
private GoogleMap mMap;
LocationManager locationManager;
private DatabaseReference mRootRef;
private String mCurrentUserId;
private String userName;
private DatabaseReference user_id;
private String mChatUser;
private String message;
private String value_lat = null;
private String value_long = null;
private FirebaseAuth mAuth;
private DatabaseReference mUserRef;
LocationTrack locationTrack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
FirebaseApp.initializeApp(this);
mRootRef = FirebaseDatabase.getInstance().getReference();
mLocationDatabase = mRootRef.child("EmergencyMessages");
mAuth = FirebaseAuth.getInstance();
mCurrentUserId = mAuth.getCurrentUser().getUid();
user_id = FirebaseDatabase.getInstance().getReference().child("Users").child(mCurrentUserId);
mChatUser = user_id.getRef().toString();
buildGoogleApiClient();
mRescue = (Button)findViewById(R.id.rescue);
mRescue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addEmergencyMessage();
addEmergencyChat();
}
});
fakeCallBtn = (ImageButton) findViewById(R.id.fake_callbtn);
fakeCallBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent fakecallIntent = new Intent(MenuActivity.this, FakeCalling.class);
startActivity(fakecallIntent);
}
});
flash = (ImageButton) findViewById(R.id.flash);
flash.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent flashIntent = new Intent(MenuActivity.this, FlashLight.class);
startActivity(flashIntent);
}
});
notif = (ImageButton) findViewById(R.id.notification_btn);
notif.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent notificationIntent = new Intent(MenuActivity.this, Notifications.class);
startActivity(notificationIntent);
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("RescueX ");
if (mAuth.getCurrentUser() != null) {
mUserRef = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid());
mUserRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userName = dataSnapshot.child("name").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
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);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Log.e("fist","error");
return ;
}
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//get latitude
double latitude = location.getLatitude();
//get longitude
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
String str = addressList.get(0).getCountryName() + ",";
str += addressList.get(0).getLocality();
mMap.addMarker(new MarkerOptions().position(latLng).title(str));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10.2f));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
private void addEmergencyChat() {
value_lat = String.valueOf(mLastLocation.getLatitude()).replace(".","d");
value_long = String.valueOf(mLastLocation.getLongitude()).replace(".","d");
String current_user_ref="Emergency_Messages/"+mCurrentUserId+"/"+mChatUser;
String chat_user_ref= "Emergency_Messages/"+mChatUser+"/"+mCurrentUserId;
DatabaseReference chat_push_key = mRootRef.child("Emergency_Messages").child(mCurrentUserId).
child(mChatUser).push();
String push_key = chat_push_key.getKey();
Map messageMap = new HashMap();
messageMap.put("userName", userName);
messageMap.put("latitude",value_lat);
messageMap.put("longitude", value_long);
messageMap.put("from",mCurrentUserId);
messageMap.put("seen",false);
messageMap.put("time", ServerValue.TIMESTAMP);
Map messageUserMap = new HashMap();
messageUserMap.put(current_user_ref+ "/"+push_key,messageMap);
messageUserMap.put(chat_user_ref+ "/"+push_key,messageMap);
mRootRef.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError!=null){
Log.d("TAG",databaseError.getMessage().toString());
}
}
});
}
private void addEmergencyMessage() {
mRootRef.child("Emergency_Chat").child(mCurrentUserId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.hasChild(mChatUser)){
Map chatAddMap = new HashMap();
chatAddMap.put("seen",false);
chatAddMap.put("timestamp", ServerValue.TIMESTAMP);
Map chatUserMap = new HashMap();
chatUserMap.put("Emergency_Chat/"+mCurrentUserId+"/"+mChatUser, chatAddMap);
chatUserMap.put("Emergency_Chat/"+mChatUser+"/"+mCurrentUserId, chatAddMap);
mRootRef.updateChildren(chatUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError!= null){
Toast.makeText(MenuActivity.this, "Error: "+databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
mGoogleApiClient.connect();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser == null){
sendToStart();
} else {
mUserRef.child("online").setValue("true");
}
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected())
mGoogleApiClient.disconnect();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser != null) {
mUserRef.child("online").setValue(ServerValue.TIMESTAMP);
}
}
private void sendToStart() {
Intent startIntent = new Intent(MenuActivity.this, Home.class);
startActivity(startIntent);
finish();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
#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) {
super.onCreateOptionsMenu(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) {
super.onOptionsItemSelected(item);
if(item.getItemId()== R.id.log_out){
FirebaseAuth.getInstance().signOut();
sendToStart();
}
//noinspection SimplifiableIfStatement
if (item.getItemId() == R.id.action_settings) {
Intent notifIntent= new Intent(MenuActivity.this, Settings.class);
startActivity(notifIntent);
}
if(item.getItemId() == R.id.all_users){
Intent usersIntent= new Intent(MenuActivity.this, UsersActivity.class);
startActivity(usersIntent);
}
return true;
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_profile_layout) {
Intent searchIntent = new Intent(MenuActivity.this, Profile.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_users_activity) {
Intent searchIntent = new Intent(MenuActivity.this, UsersActivity.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_history_layout) {
Intent searchIntent = new Intent(MenuActivity.this, History.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_help_layout) {
Intent searchIntent = new Intent(MenuActivity.this, Help.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_feedback_layout) {
Intent searchIntent = new Intent(MenuActivity.this, Feedback.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_signout_layout) {
Intent searchIntent = new Intent(MenuActivity.this, SignOut.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_friends_layout) {
Intent searchIntent = new Intent(MenuActivity.this, FriendsActivity.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_share) {
Intent searchIntent = new Intent(MenuActivity.this, Share.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#SuppressLint("MissingPermission")
#Override
public void onConnected(#Nullable Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null){
value_lat = String.valueOf(mLastLocation.getLatitude()).replace(".","d");
value_long = String.valueOf(mLastLocation.getLongitude()).replace(".","d");
}
}
#Override
public void onConnectionSuspended(int cause) {
Log.i(TAG,"Connection suspended");
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.i(TAG, " Connection Failed "+ connectionResult.getErrorMessage());
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
}
What I want to do is read the location that is being displayed when the user open's a page containing the above code, after reading the user's location I want to store those values in my database which I will later retrieve in another class.

Replacing the . with * didn't really work and from what Cao Minh Vu suggested that it might have a problem the mChatUser was pointing to a null value so I sorted that out and for may latitude and longitude is used:
String lat = String.ValueOf(latitude.getLatitude());
String long = String.valueOf(longitude.getLongitude());
Thanks to everyone who commented on my Post, I wasn't going to identify the problem because there's too many lines in my code it was hard to identify which one was giving me a problem

Related

How to retrieve data from firebase for if else condition in java

I tried to make a different condition based on firebase database data. for example if the "Status" field data has value "Aktif" then the marker color will change to blue and when the "Status" value change into "Nonaktif" then the marker color will change into red. I already to use this code, but when tried to run it have the problem "error: incompatible types: cannot be converted to Context".
So how can i fix this problem? i will put the database structure here Firebase structure
private NavigationView navigationView;
private TextView namapengguna, emailpengguna;
private ImageView imageView2;
private View headerView;
DrawerLayout drawerLayout;
MapView mapView;
public MapboxMap mapboxMap;
private LocationManager manager;
private PermissionsManager permissionsManager;
private LocationComponent locationComponent;
Marker myMarker;
private final int MIN_TIME = 1000;
private final int MIN_DISTANCE = 1;
private FirebaseUser user;
private DatabaseReference root;
private StorageReference reference;
private String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this,"pk.eyJ1IjoiaGFuZGlrYW1lZGlhbWFydGEiLCJhIjoiY2ttb2o1MWQ2MHp5cDJ3bHcyM3RkN2VvdiJ9.VOmbzomxo3nMMWLcmF2l0g");
setContentView(R.layout.activity_dashboard);
manager = (LocationManager) getSystemService(LOCATION_SERVICE);
mapView = (MapView)findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
drawerLayout = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
headerView = navigationView.getHeaderView(0);
namapengguna = (TextView) headerView.findViewById(R.id.namalengkap);
emailpengguna = (TextView) headerView.findViewById(R.id.emailpengguna);
imageView2 = findViewById(R.id.imageview2);
imageView2 = (ImageView) headerView.findViewById(R.id.imageview2);
user = FirebaseAuth.getInstance().getCurrentUser();
root = FirebaseDatabase.getInstance().getReference();
reference = FirebaseStorage.getInstance().getReference();
userID = user.getUid();
root.child("Users").child(userID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User userProfile = snapshot.getValue(User.class);
if (userProfile != null) {
String fullName = userProfile.fullname;
String email = userProfile.email;
namapengguna.setText(fullName);
emailpengguna.setText(email);
if (snapshot.hasChild("image")){
String image2 =snapshot.child("image").getValue().toString();
Picasso.get().load(image2).into(imageView2);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(Dashboard.this, "Terjadi Kesalahan Pada Database", Toast.LENGTH_LONG).show();
}
});
}
public void ClickMenu(View view) {
openDrawer(drawerLayout);
}
public static void openDrawer(DrawerLayout drawerLayout) {
drawerLayout.openDrawer(GravityCompat.START);
}
public void ClickLogo(View view) {
closeDrawer(drawerLayout);
}
public static void closeDrawer(DrawerLayout drawerLayout) {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
}
}
public void ClickHome(View view) {
recreate();
}
public void ClickUtama(View view) {
redirectActivity(this, Utama.class);
}
public void ClickAboutUs(View view) {
redirectActivity(this, AboutUs.class);
}
public void ClickLogout(View view) {
logout(this);
}
public static void logout(Activity activity) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("Logout");
builder.setMessage("Are you sure want to logout?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
activity.finishAffinity();
System.exit(0);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
public static void redirectActivity(Activity activity, Class aClass) {
Intent intent = new Intent(activity, aClass);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
return false;
}
#Override
public void onMapReady(#NonNull final MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
root.child("otoped").addValueEventListener(new ValueEventListener() {
Query q = FirebaseDatabase.getInstance().getReference("otoped").orderByChild("Status").equalTo("0");
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
MyLocation location = dataSnapshot.getValue(MyLocation.class);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng loc = new LatLng(latitude,longitude);
if (q != null){
myMarker = mapboxMap.addMarker(new MarkerOptions().icon(IconFactory.getInstance(this).fromResource(R.drawable.ic_markerbiru)));
myMarker.setPosition(loc);
}else{
myMarker = mapboxMap.addMarker(new MarkerOptions().icon(IconFactory.getInstance(this).fromResource(R.drawable.markerblue)).position(loc).title("Otoped1"));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
enableLocationComponent(style);
Drawable drawable = ResourcesCompat.getDrawable(getResources(),R.drawable.ic_baseline_location_on_24,null);
Bitmap mBitmap = BitmapUtils.getBitmapFromDrawable(drawable);
}
});
}
private void enableLocationComponent(#NonNull Style loadedMapStyle) {
if (PermissionsManager.areLocationPermissionsGranted(Dashboard.this)){
LocationComponent locationComponent = mapboxMap.getLocationComponent();
locationComponent.activateLocationComponent(
LocationComponentActivationOptions.builder(Dashboard.this, loadedMapStyle).build());
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
return;
}
locationComponent.setLocationComponentEnabled(true);
locationComponent.setCameraMode(CameraMode.TRACKING);
locationComponent.setRenderMode(RenderMode.COMPASS);
} else {
permissionsManager = new PermissionsManager((PermissionsListener) this);
permissionsManager.requestLocationPermissions(this);
}
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
#Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
#Override
public void onPause() {
super.onPause();
closeDrawer(drawerLayout);
mapView.onPause();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onLocationChanged(#NonNull Location location) {
if (location != null){
saveLocation(location);
}else {
Toast.makeText(this, "No Location", Toast.LENGTH_SHORT).show();
}
}
private void saveLocation(Location location) {
root.child("otoped").setValue(location);
}
}
I Got problem when tried to edit this code
#Override
public void onMapReady(#NonNull final MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
root.child("otoped").addValueEventListener(new ValueEventListener() {
Query q = FirebaseDatabase.getInstance().getReference("otoped").orderByChild("Status").equalTo("0");
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
MyLocation location = dataSnapshot.getValue(MyLocation.class);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng loc = new LatLng(latitude,longitude);
if (q != null){
myMarker = mapboxMap.addMarker(new MarkerOptions().icon(IconFactory.getInstance(this).fromResource(R.drawable.ic_markerbiru)));
myMarker.setPosition(loc);
}else{
myMarker = mapboxMap.addMarker(new MarkerOptions().icon(IconFactory.getInstance(this).fromResource(R.drawable.markerblue)).position(loc).title("Otoped1"));
}
}

Can't create an all in one share option

I have created a floating button and give it id fab
When people will click on it every share option that is installed in the mobile will pop up at once and the user can choose where to share the URL.
I created it through intent but it's not working rather crashing. please help me. Give me a small piece of code.
main_activity java
Button buttonDonor;
Button buttonInfo;
Button needBlood;
public static String donorId = "no";
SharedPreferences sharedPreferences;
public static Double lat = 0.0;
public static Double lng = 0.0;
private final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 1;
GoogleApiClient mGoogleApiClient;
LocationManager locationManager;
LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Connecting to the database
database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("donors");
/**
* Wiring up every thing
*/
//sharebutton
buttonInfo = (Button) findViewById(R.id.fab);
buttonInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "Sharing URL");
i.putExtra(Intent.EXTRA_TEXT, "http://google.com");
startActivity(Intent.createChooser(i, "Share URL"));
}
});
buttonInfo = (Button) findViewById(R.id.btn_info);
Animation slideUpAnimation = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.information);
buttonInfo.startAnimation(slideUpAnimation);
buttonInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Information.class));
}
});
buttonInfo = (Button) findViewById(R.id.developer);
Animation slideUpAnimation1 = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.developer);
buttonInfo.startAnimation(slideUpAnimation1);
buttonInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, About.class));
}
});
buttonInfo = (Button) findViewById(R.id.request);
Animation slideUpAnimation2 = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.request_blood);
buttonInfo.startAnimation(slideUpAnimation2);
buttonInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, RequestBlood.class));
}
});
buttonInfo = (Button) findViewById(R.id.check_request);
Animation slideUpAnimation3 = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.check_request);
buttonInfo.startAnimation(slideUpAnimation3);
buttonInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, RequestList.class));
}
});
needBlood = (Button) findViewById(R.id.btn_need_blood);
Animation slideUpAnimation4 = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.need_blood);
needBlood.startAnimation(slideUpAnimation4);
needBlood.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, NeedBlood.class));
}
});
buttonDonor = (Button) findViewById(R.id.btn_donor_profile);
Animation slideUpAnimation6 = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.be_donor);
buttonDonor.startAnimation(slideUpAnimation6);
if (donorId.toString().equals("no")) {
buttonDonor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, DonorForm.class));
}
});
} else {
}
/**
* Initializing variable
*/
try {
donorId = sharedPreferences.getString("id", "no");
} catch (Exception e) {
e.printStackTrace();
}
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
lat = location.getLatitude();
lng = location.getLongitude();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(GPS_PROVIDER)) {
Toast.makeText(MainActivity.this, "Please Turn on Location", Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
MainActivity.this.startActivity(myIntent);
}
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) {
/**
* Crating a location request
*/
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
return;
}
locationManager.requestLocationUpdates(GPS_PROVIDER, 1000, 1, locationListener);
}
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
boolean doubleBackToExitPressedOnce = false;
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click Back twice to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
}
Issue at buttonInfo = (Button) findViewById(R.id.fab). Because fab is FloatingActionButton and you cast it to Button type.
Replace your share code portion. Like,
FloatingActionButton fabBtn = (Button) findViewById(R.id.fab);
fabBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "Sharing URL");
i.putExtra(Intent.EXTRA_TEXT, "http://google.com");
startActivity(Intent.createChooser(i, "Share URL"));
}
});
Caused by: java.lang.ClassCastException: android.support.design.widget.FloatingActionButton cannot be cast to android.widget.Button
at com.nissan.dnmcbloodbank.MainActivity.onCreate(MainActivity.java:72)
Replace this line
Button buttonInfo;
with
FloatingActionButton buttonInfo;
and this line
buttonInfo = (Button) findViewById(R.id.fab);
with
buttonInfo = (FloatingActionButton) findViewById(R.id.fab);

java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
when I am trying to run app it automatically crashing showing an error
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'java.lang.String
com.google.firebase.auth.FirebaseUser.getUid()' on a null object
reference
at com.example.akhilkumar.chitchat.MainActivity.onCreate(MainActivity.java:55)
error pointing to
currentUserID = mAuth.getCurrentUser().getUid();
public class MainActivity extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private RecyclerView postList;
private Toolbar mToolbar;
private ActionBarDrawerToggle actionBarDrawerToggle;
private FirebaseAuth mAuth;
private DatabaseReference userRef;
private CircleImageView navProfileImage;
private TextView navProfileUserName;
String currentUserID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
userRef = FirebaseDatabase.getInstance().getReference().child("Users");
/*
mToolbar = (Toolbar)findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
*/
getSupportActionBar().setTitle("Home");
drawerLayout = (DrawerLayout)findViewById(R.id.drawable_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayout, R.string.drawer_open, R.string.drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigationView = (NavigationView)findViewById(R.id.navigation_view);
View navView = navigationView.inflateHeaderView(R.layout.navigation_header);
navProfileImage = (CircleImageView)navView.findViewById(R.id.nav_profile_image);
navProfileUserName =(TextView)navView.findViewById(R.id.nav_user_full_name);
userRef.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();
navProfileUserName.setText(fullname);
}
if(dataSnapshot.hasChild("profileimage"))
{
String image = dataSnapshot.child("profileimage").getValue().toString();
Picasso.get().load(image).placeholder(R.drawable.profile).into(navProfileImage);
}
else
{
Toast.makeText(MainActivity.this, "Profile name do not exists...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
UserMenuSelector(item);
return false;
}
});
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser == null){
SendUserToLoginActivity();
}
else{
CheckUserExistence();
}
}
private void CheckUserExistence() {
final String current_user_id = mAuth.getCurrentUser().getUid();
userRef.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(MainActivity.this, SetupActivity.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(setupIntent);
finish();
}
private void SendUserToLoginActivity() {
Intent loginIntenet = new Intent(MainActivity.this, LoginActivity.class);
loginIntenet.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntenet);
finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(actionBarDrawerToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
private void UserMenuSelector(MenuItem item) {
switch (item.getItemId()){
case R.id.nav_profile:
Toast.makeText(this,"Profile",Toast.LENGTH_LONG).show();
break;
case R.id.nav_home:
Toast.makeText(this,"Home",Toast.LENGTH_LONG).show();
break;
case R.id.nav_friends:
Toast.makeText(this,"Friends",Toast.LENGTH_LONG).show();
break;
case R.id.nav_find_friends:
Toast.makeText(this,"Find Friends",Toast.LENGTH_LONG).show();
break;
case R.id.nav_messages:
Toast.makeText(this,"Messages",Toast.LENGTH_LONG).show();
break;
case R.id.nav_settings:
Toast.makeText(this,"Settings",Toast.LENGTH_LONG).show();
break;
case R.id.nav_logout:
mAuth.signOut();
SendUserToLoginActivity();
Toast.makeText(this,"Logout Successfully",Toast.LENGTH_LONG).show();
break;
case R.id.nav_about_app:
Toast.makeText(this,"About",Toast.LENGTH_LONG).show();
break;
}
}
}
The following line of code:
currentUserID = mAuth.getCurrentUser().getUid();
May produce NullPointerException. So to solve this, you need to check first for nullity. So please use the following lines of code:
FirebaseUser mFirebaseUser = mAuth.getCurrentUser();
if(mFirebaseUser != null) {
currentUserID = mFirebaseUser.getUid(); //Do what you need to do with the id
}
You are accessing mAuth in onStart method but you are initializing it in onCreate. So that's why you are getting this error.
So write the following code in onCreate() method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser == null){
SendUserToLoginActivity();
}
else{
CheckUserExistence();
}
}

Application crashes when SetContentView set back to main activity

When I set content view on another layout its works perfectly, but when I set content view back to main layout its crashes.
My Main class and everything on it. Everything happens in public void firstTime().
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private MapFragment mapsFragment;
static MainActivity can;
static FloatingActionButton fab;
static FloatingActionButton show;
private String encoded_string;
private Bitmap bitmap;
private String picturePath;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
private void initializeMapsFragment() {
FragmentTransaction mTransaction = getSupportFragmentManager().beginTransaction();
mapsFragment = new MapFragment();
SupportMapFragment supportMapFragment = mapsFragment;
mTransaction.add(R.id.map, supportMapFragment);
mTransaction.commit();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("--***** MAP ", "::Loading Map");
can = this;
setContentView(R.layout.activity_main);
initializeMapsFragment();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fab = (FloatingActionButton) findViewById(R.id.fab);
show = (FloatingActionButton) findViewById(R.id.show);
show.hide();
fab.hide();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
callPopup();
}
});
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stats();
}
});
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);
Button searchButton = (Button) findViewById(R.id.searchButton);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText searchView = (EditText) findViewById(R.id.searchView1);
String text = searchView.getText().toString();
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input
// text
addresses = geocoder.getFromLocationName(text, 3);
if (addresses != null && !addresses.equals(""))
search(addresses);
} catch (Exception e) {
}
}
});
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
protected void search(List<Address> addresses) {
Address address = (Address) addresses.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
MapFragment.mapView.moveCamera(CameraUpdateFactory.newLatLng(latLng));
MapFragment.mapView.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#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);
}
#RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
FragmentManager fm = getFragmentManager();
android.support.v4.app.FragmentManager sFm = getSupportFragmentManager();
int id = item.getItemId();
if (id == R.id.nav_camera) {
if (!mapsFragment.isAdded())
sFm.beginTransaction().add(R.id.map, mapsFragment).commit();
else
sFm.beginTransaction().show(mapsFragment).commit();
} else if (id == R.id.nav_share) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "Check this app out --> link.kys";
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Best Free Parking app");
sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void firstTime() {
setContentView(R.layout.firsttime);
(findViewById(R.id.cancelBut))
.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
setContentView(R.layout.activity_main);
}
});
}
public static void load(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(can);
if (!prefs.getBoolean("firstTime", false)) {
can.firstTime();
//SharedPreferences.Editor editor = prefs.edit();
//editor.putBoolean("firstTime", true);
//editor.commit();
}
}
private void stats() {
setContentView(R.layout.stats);
RatingBar ratingbar = (RatingBar) findViewById(R.id.ratingBar);
ratingbar.setRating((float) 2.0);
ratingbar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
ratingBar.setRating((float) 2.0);
}
});
((Button) findViewById(R.id.cancBut)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setContentView(R.layout.content_main);
}
});
}
private void callPopup() {
final PopupWindow popupWindow;
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
popupWindow = new PopupWindow(popupView,
DrawerLayout.LayoutParams.WRAP_CONTENT, DrawerLayout.LayoutParams.MATCH_PARENT,
true);
popupWindow.setTouchable(true);
popupWindow.setFocusable(true);
popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);
final EditText name = (EditText) popupView.findViewById(R.id.edtimageName);
((Button) popupView.findViewById(R.id.plcBut)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectPhoto();
}
});
((Button) popupView.findViewById(R.id.saveBtn))
.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void onClick(View arg0) {
new Encode_image().execute();
popupWindow.dismiss();
}
});
((Button) popupView.findViewById(R.id.cancelbtutton))
.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
popupWindow.dismiss();
}
});
}
private void selectPhoto() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 10);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 10 && resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
}
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
private class Encode_image extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
bitmap = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
bitmap.recycle();
byte[] array = stream.toByteArray();
encoded_string = Base64.encodeToString(array, 0);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
makeRequest();
}
}
private void makeRequest() {
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.POST, "http://185.80.129.86/upload.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> map = new HashMap<>();
map.put("encoded_string", encoded_string);
map.put("image_name", "testing123.jpg");
return map;
}
};
requestQueue.add(request);
}
}
Error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.robertas.parking.bestfreeparking, PID: 3501
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:3936)
at android.view.ViewGroup.addView(ViewGroup.java:3786)
at android.view.ViewGroup.addView(ViewGroup.java:3758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:810)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:143)
at com.robertas.parking.bestfreeparking.MainActivity$4.onClick(MainActivity.java:245)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Make changes this
Log.d("--***** MAP ", "::Loading Map");
can = this;
setContentView(R.layout.activity_main);
initializeMapsFragment();

how to pass latitude and longitude data to navigation drawer activity

i am getting null data on my recyclerview, i am passing latitude and longitude data using place picker, its working properly on my MapActivity. but when i m trying to store that data on my NavigationDrawer item activity, its getting null,
here is my code of MapActivity
public class MapsActivity extends AppCompatActivity implements
OnMapReadyCallback, NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayShowHomeEnabled(true);
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);
} else {
mMapFragment.getMapAsync(this);
}
} catch (Exception e) {
e.printStackTrace();
}
initialize();
setupDrawer();
}
private void initialize() {
search = (Button) findViewById(R.id.btnSerch);
assert search != null;
search.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnSerch) {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, this);
final Double latitude = place.getLatLng().latitude;
final Double longitude = place.getLatLng().longitude;
final String placeName = String.valueOf(place.getName());
final float radius = 0.5f;
LatLng loc2 = new LatLng(latitude, longitude);
marker2 = new MarkerOptions().position(loc2).title(placeName).visible(true);
mMap.addMarker(marker2);
mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(latitude, longitude)));
}
}
}
private void setupDrawer() {
try {
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);
mDrawerLayout.addDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
Intent intent = null;
if (item.getItemId() == R.id.navigation_item_1) {
mDrawerLayout.closeDrawer(GravityCompat.START);
intent = new Intent(MapsActivity.this, LocationList.class);
startActivity(intent);
return true;
}
if (item.getItemId() == R.id.navigation_item_2) {
mDrawerLayout.closeDrawer(GravityCompat.START);
intent = new Intent(this, AboutUs.class);
startActivity(intent);
return true;
}
if (item.getItemId() == R.id.navigation_item_3) {
mDrawerLayout.closeDrawer(GravityCompat.START);
intent = new Intent(this, Help.class);
startActivity(intent);
return true;
}
return false;
}
In my LocationList class i have recycleview and i m trying to set latitude logtitude data on it. how do i do that.
here is my code of LocationListActivity
public class LocationList extends AppCompatActivity {
private List<Locations> locationsList = new ArrayList<>();
private RecyclerView recyclerView;
private LocationAdapter mAdapter;
int PLACE_PICKER_REQUEST = 1;
String placeName;
Double latitude, longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_list);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mAdapter = new LocationAdapter(locationsList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
prepareLocationData();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, this);
latitude = place.getLatLng().latitude;
longitude = place.getLatLng().longitude;
placeName = String.valueOf(place.getName());
}
}
}
private void prepareLocationData() {
Locations locations = new Locations(placeName, latitude, longitude);
locationsList.add(locations);
mAdapter.notifyDataSetChanged();
}
}
when i run the code, its getting null, i dont know how to pass data, plz help me.. here is my cardview image.
You can add the parameters to your intent and retrieve them in your LocationActivity.
Please see below :
Set parameters to your intent
#Override
public boolean onNavigationItemSelected(MenuItem item) {
Intent intent = null;
if (item.getItemId() == R.id.navigation_item_1) {
mDrawerLayout.closeDrawer(GravityCompat.START);
intent = new Intent(MapsActivity.this, LocationList.class);
intent.putExtra("longitude_key", longitude);
intent.putExtra("latitude_key", latitude);
startActivity(intent);
return true;
}
Retrieve the parameters in your LocationActivity
...
Double latitude, longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_list);
if (getIntent() != null) {
longitude = getIntent().getDoubleExtra("longitude_key", 0); // set to 0 if not found
latitude = getIntent().getDoubleExtra("latitude_key", 0); // set to 0 if not found
}
Hope it helps.

Categories

Resources