Can't get onDataChange to run first in Android [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
This activity displays geofences to the map. They're added as objects to an arraylist and then used by initArea() and are shown on the map. My issue is initArea() runs before onDataChange() so nothing is added to the arraylist and a null pointer exception is thrown. I want onDatachange() to run first so that the arraylist is populated. Thanks in advance :)
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GeoQueryEventListener {
private static final String TAG = "Maps";
private GoogleMap mMap;
private LocationRequest locationRequest;
private LocationCallback locationCallback;
private FusedLocationProviderClient fusedLocationProviderClient;
private Marker currentLocation;
private DatabaseReference locationRef;
private GeoFire geofire;
private List<LatLng> geoFence;
ArrayList<geofenceObj> geoTemp = new ArrayList<>();
private String userID;
private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;
private int check;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
FirebaseUser user = mAuth.getCurrentUser();
userID = user.getUid();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
}
};
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
showData(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Dexter.withActivity(this)
.withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
buildLocationRequest();
buildlocationcallback();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MapsActivity.this);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(MapsActivity.this);
initArea();
settingGeofire();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
Toast.makeText(MapsActivity.this, "Permissions not enabled ", Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
}
}).check();
}
private void showData(DataSnapshot dataSnapshot) {
geoTemp.clear();
for(DataSnapshot i : dataSnapshot.getChildren()) {
for(int j=1; j<=dataSnapshot.child("users").child(userID).getChildrenCount(); j++) {
String ID = String.valueOf(j);
if (i.child(userID).child(ID).getValue() != null) {
geofenceObj geofence = new geofenceObj();
geofence.setName(Objects.requireNonNull(i.child(userID).child(ID).getValue(geofenceObj.class)).getName());
geofence.setRadius(Objects.requireNonNull(i.child(userID).child(ID).getValue(geofenceObj.class)).getRadius());
geofence.setLat(Objects.requireNonNull(i.child(userID).child(ID).getValue(geofenceObj.class)).getLat());
geofence.setLng(Objects.requireNonNull(i.child(userID).child(ID).getValue(geofenceObj.class)).getLng());
geoTemp.add(geofence);
Log.d(TAG, "Added " + geofence.getName());
}
}
}
}
private void initArea() {
geoFence = new ArrayList<>();
geoFence.add(new LatLng(0, 0));
for(int i = 0; i <= geoTemp.size(); i++){
geoFence.add(new LatLng(geoTemp.get(i).getLat(), geoTemp.get(i).getLat()));
}
Log.d(TAG, "Initialised Area");
}

You can't change the order in which asynchronous data is loaded. But what you can change is when you initialize the map that depends on the data. So move the call to initArea() into the onDataChange (or the showData) method, so that is runs after the data has been loaded.
private void showData(DataSnapshot dataSnapshot) {
geoTemp.clear();
for(DataSnapshot i : dataSnapshot.getChildren()) {
for(int j=1; j<=dataSnapshot.child("users").child(userID).getChildrenCount(); j++) {
String ID = String.valueOf(j);
if (i.child(userID).child(ID).getValue() != null) {
geofenceObj geofence = new geofenceObj();
geofence.setName(Objects.requireNonNull(i.child(userID).child(ID).getValue(geofenceObj.class)).getName());
geofence.setRadius(Objects.requireNonNull(i.child(userID).child(ID).getValue(geofenceObj.class)).getRadius());
geofence.setLat(Objects.requireNonNull(i.child(userID).child(ID).getValue(geofenceObj.class)).getLat());
geofence.setLng(Objects.requireNonNull(i.child(userID).child(ID).getValue(geofenceObj.class)).getLng());
geoTemp.add(geofence);
Log.d(TAG, "Added " + geofence.getName());
}
}
}
// Now that the data is loaded and processed, we can initialize the map
initArea();
}

Related

read a realtime database node

hi guys I would like as a title to read a single node created previously in my realtime firebase database, the database is thus created:
Users
---- UID1
---- Email:
---- Fullname:
---- Phone:
---- Coins:
---- UID2
---- Email:
---- Fullname:
---- Phone:
---- Coins:
so my database has a structure like the one shown and I need to read in onDataChange and then write the data in a TextView.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_coins_);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Utenti");
myRef.child("Rapp Coins %").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String coinsRapp = dataSnapshot.getValue(String.class);
mCoins.setText(coinsRapp);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
this method I used doesn't work as I can't get it to take the data I need.
I need to take the Coins value: within each different logged user, so each logged in user reads his data.
I the UID value that identifies each user, I created it based on his mobile number, so each user has his own mobile number that identifies him as UID.
this is all my code, as you can see the data that saves the UID is contained in mPhone, which was saved and then brought into this activity through the SharedPreferences.
public class PageCoins_Activity extends AppCompatActivity implements RewardedVideoAdListener {
private static final String TAG = MainActivity.class.getName();
private FirebaseAuth mAuth;
private AdView mBannerTop;
private AdView mBannerBot;
private RewardedVideoAd mRewardedVideoAd;
public double Coins;
double coinsOp = 0.00;
double coinsCl = 0.00;
double coinssum = 0.00;
Button mButton;
Button mPhonebtn;
TextView mCoinscounter;
TextView mCoins;
FirebaseDatabase mDatabase;
EditText mPhoneEdt;
TextView mPhone;
#Override
protected void onStart(){
super.onStart();
updateUI();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_coins_);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Utenti");
myRef.child("Rapp Coins %").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String coinsRapp = dataSnapshot.getValue(String.class);
mCoins.setText(coinsRapp);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
mAuth = FirebaseAuth.getInstance();
initFirebase();
//counter CRD
mCoinscounter = (TextView)findViewById(R.id.Textcoins);
mButton = (Button)findViewById(R.id.btn2);
mPhoneEdt = (EditText)findViewById(R.id.NumberPhEdt);
mPhone = (TextView) findViewById(R.id.NumberPhTxt);
mCoins = (TextView)findViewById(R.id.txtGen);
mPhonebtn = (Button)findViewById(R.id.buttonPhone);
//mPhoneEdt.setVisibility(View.GONE);
//mPhone.setVisibility(View.VISIBLE);
findViewById(R.id.btn2).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
}
// Write a message to the database
DatabaseReference myRef = mDatabase.getReference();
myRef.child("Utenti").child(mPhone.getText().toString()).child("Rapp Coins Day %").setValue(mCoinscounter.getText().toString());
}
});
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(this);
//Set Orientation Portrait
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Banner Top View Coins
mBannerTop = (AdView) findViewById(R.id.adViewTopcoins);
AdRequest adRequest = new AdRequest.Builder().setRequestAgent("android_studio:ad_template").build();
mBannerTop.loadAd(adRequest);
// Banner Bot View Coins
mBannerBot = (AdView) findViewById(R.id.adViewBotcoins);
AdRequest adRequest1 = new AdRequest.Builder().setRequestAgent("android_studio:ad_template").build();
mBannerBot.loadAd(adRequest1);
getnumberprefs();
//ADMob Video
loadRewardedVideoAd();
}
private void getnumberprefs() {
SharedPreferences numb = getSharedPreferences(Register_Activity.NUMB, MODE_PRIVATE);
String numberphn = numb.getString(Register_Activity.KEY_NUMB,null);
mPhone.setText(numberphn);
}
//boolean changepgcoins = true;
public void changeNumber(View view) {
/*if (changepgcoins == true){
mPhoneEdt.setVisibility(View.GONE);
mPhone.setVisibility(View.VISIBLE);
changepgcoins = false;
}else{
mPhoneEdt.setVisibility(View.VISIBLE);
mPhone.setVisibility(View.GONE);
changepgcoins = true;
}*/
}
private void initFirebase() {
mDatabase = FirebaseDatabase.getInstance();
}
public void HomeClick(View view){
Intent intenthome = new Intent(this, MainActivity.class);
finish();
startActivity(intenthome);
}
public void displayCrd (double amount){
mCoinscounter.setText(String.format("%.2f", amount));
}
private void loadRewardedVideoAd() {
mRewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917",
new AdRequest.Builder().build());
}
public void logout(View view) {
mAuth.signOut();
updateUI();
}
private void updateUI() {
FirebaseUser currentuser = mAuth.getCurrentUser();
if(currentuser == null){
Intent intTologin = new Intent(this, Login_Activity.class);
finish();
startActivity(intTologin);
}
}
#Override
public void onRewardedVideoAdLoaded() {
Log.d(TAG, "Video Caricato");
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewardedVideoStarted() {
}
#Override
public void onRewardedVideoAdClosed() {
loadRewardedVideoAd();
}
#Override
public void onRewarded(RewardItem rewardItem) {
Toast.makeText(this, " RAPp " + " COINS " + " : " + rewardItem.getAmount(), Toast.LENGTH_LONG).show();
Coins += rewardItem.getAmount();
displayCrd(Coins/40200*100);
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
Log.d(TAG, "Caricamento Fallito");
}
#Override
public void onRewardedVideoCompleted() {
loadRewardedVideoAd();
}
#Override
protected void onDestroy() {
if (!isEmpty(mCoins)){
String coinsopen = mCoins.getText().toString();
String coinscounter = mCoinscounter.getText().toString();
coinsOp = Double.parseDouble(String.format(coinsopen.replace(',', '.'), "%.2f"));
coinsCl = Double.parseDouble(String.format(coinscounter.replace(',', '.'), "%.2f"));
coinssum = (coinsOp + coinsCl);
mCoinscounter.setText(String.valueOf(coinssum));
// Write a message to the database
DatabaseReference myRef = mDatabase.getReference();
myRef.child("Utenti").child(mPhone.getText().toString()).child("Rapp Coins %").setValue(mCoinscounter.getText().toString());
}else{
// Write a message to the database
DatabaseReference myRef = mDatabase.getReference();
myRef.child("Utenti").child(mPhone.getText().toString()).child("Rapp Coins %").setValue(mCoinscounter.getText().toString());
}
super.onDestroy();
}
private boolean isEmpty(TextView mCoins) {
String input = mCoins.getText().toString();
return input.length() == 0.00;
}
}
I really ask for help on the solution of this thing because it's the last thing I need to finish and I can't thank you.
{
"Utenti" : {
"3********4" : {
"E-Mail" : "",
"Full Name" : "",
"Phone" : "",
"Rapp Coins %" : "",
"Rapp Coins Day %" : ""
},
"3********1" : {
"E-Mail" : "",
"Full Name" : "",
"Phone" : "",
"Rapp Coins %" : "",
"Rapp Coins Day %" : ""
},
}
}
this is my database so composed.

Google Firebase method onDataChange() is not called

I've got a problem with reading data from google firebase. It seems like the method onDataChange is not called no matter if I change data in the database or not and I don't know why. What makes me curious is that I am able to write data into the database. I would be very thankful if someone could help me. Here is my code:
public class MainActivity extends AppCompatActivity implements LocationListener, View.OnClickListener {
MapView mapView;
MyLocationNewOverlay myLocationOverlay;
private static final String TAG = "MainActivity";
String content = "a";
String author = "b";
Double latitude = 53.2;
Double longitude = 11.5;
private ItemizedIconOverlay<OverlayItem> messagesOverlay;
private List<OverlayItem> items = new ArrayList<>();
private long totalNumberChilds;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set up the mapView and show the MyLocationOverlay
mapView = findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setMultiTouchControls(true);
mapView.getController().setZoom(5);
messagesOverlay = new ItemizedIconOverlay<OverlayItem>(items, getResources().getDrawable(R.drawable.briefumschlag), null, this);
myLocationOverlay = new MyLocationNewOverlay(new GpsMyLocationProvider(getApplicationContext()), mapView);
myLocationOverlay.enableMyLocation();
mapView.getOverlays().add(messagesOverlay);
mapView.getOverlays().add(myLocationOverlay);
GeoPoint point = this.myLocationOverlay.getMyLocation();
if(point==null){
return;
} else {
mapView.getController().animateTo(point);
}
//initialize the Overlay for the Messages
//messagesOverlay.addItem(new OverlayItem(author, "", new GeoPoint(latitude, longitude)));
//declare the database variables in onCreate
//NOTE: Unless you are signed in, this will not be useable.
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("message");
// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
messagesOverlay.removeAllItems();
Toast.makeText(MainActivity.this, "yesss", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDataChange: Successsfully called!");
for (DataSnapshot ds : dataSnapshot.getChildren()) {
//Message message = new Message();
//String author1 = ds.child("messageAuthor").getValue(String.class);
//String content1 = ds.child("messageContent").getValue(String.class);
//Double latitude1 = ds.child("messageLatitude").getValue(Double.class);
//Double longitude1 = ds.child("messageLongitude").getValue(Double.class);
//messagesOverlay.addItem(new OverlayItem("by" + author1, "", new GeoPoint(latitude1, longitude1)));
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
});
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.testButton) {
addMessage();
}
}
public void addMessage() {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("message");
String id = myRef.push().getKey();
Message message = new Message(author, content, latitude, longitude);
myRef.child(id).setValue(message);
Toast.makeText(this, "Message added", Toast.LENGTH_LONG).show();
}
#Override
public void onLocationChanged(Location location) {
GeoPoint point = new GeoPoint(location);
if(point==null){
return;
} else {
mapView.getController().animateTo(point);
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
I just found the error, I removed the lines
if(point==null){
return;
} else {
mapView.getController().animateTo(point);
}
and now the onDataChange method is called. Thank you so much for your help!

How to make simple user sign in with just username (firebase)

I am completely noob (again sorry about my ignorance in this field I relly need help) in java and I need to make an app with firebase. Here is my register account code(its all the code I have copied from GitHub :P) I want to make it just to register with username, the register with email and password functionality and the verification sending future completely to be disabled , also I need to make it to go on a different activity or simply to login the user and show the posts feed. I hope someone could help me:
public class SignupActivity extends BaseActivity {
private static final String TAG = "SignupActivity";
private Context mContext = SignupActivity.this;
//firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FireBaseMethods fireBaseMethods;
private String email, handleName, password;
private EditText mHandleName, mEmail, mPassword;
private Button mButtonRegister;
private TextView loadingPleaseWait;
private ProgressBar mProgressBar;
//firebase Database
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
boolean isExisted;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
fireBaseMethods = new FireBaseMethods(mContext);
Log.d(TAG, "onCreate: started");
initWidgets();
setupFirebaseAuth();
init();
}
#Override
protected void performOnCreate(Bundle state) {
}
private void init() {
mButtonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handleName = mHandleName.getText().toString();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(mEmail.getText().toString());
stringBuilder.append("");
email = stringBuilder.toString();
password = mPassword.getText().toString();
if (validate()) {
mProgressBar.setVisibility(View.VISIBLE);
loadingPleaseWait.setVisibility(View.VISIBLE);
fireBaseMethods.registerNewEmail(handleName, email, password);
}
}
});
}
/*
Initialize the activity widgets
*/
private void initWidgets() {
Log.d(TAG, "initWidgets: Initialize Widgets");
mHandleName = findViewById(R.id.handle_name);
mEmail = findViewById(R.id.input_email_signup);
mPassword = findViewById(R.id.input_password_signup);
mButtonRegister = findViewById(R.id.btn_signup);
mProgressBar = findViewById(R.id.progressBar);
loadingPleaseWait = findViewById(R.id.loading_signup);
mProgressBar.setVisibility(View.GONE);
loadingPleaseWait.setVisibility(View.GONE);
}
public boolean validate() {
boolean valid = true;
if (handleName.isEmpty() || handleName.length() < 3) {
mHandleName.setError("Внесете најмалку 3 карактери");
valid = false;
} else {
mHandleName.setError(null);
}
if (email.isEmpty()) {
mEmail.setError("Внесете валидна електронска пошта");
valid = false;
} else {
mEmail.setError(null);
}
if (password.isEmpty() || password.length() < 4) {
mPassword.setError("помеѓу 4 и 10 карактери");
valid = false;
} else {
mPassword.setError(null);
}
return valid;
}
/*
------------------------------------- Firebase ---------------------------------------------------
*/
/**
* Set up firebase auth object
*/
private void setupFirebaseAuth() {
Log.d(TAG, "setupFirebaseAuth: setting up firebase auth");
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//1st check: make sure handle name is not ready in use
if (fireBaseMethods.checkIfHandleNameAlreadyExists(handleName, dataSnapshot)) {
mHandleName.setError("Тој ник веќе постои");
isExisted = true;
}
//add new user to the database
fireBaseMethods.addNewUser(handleName, email);
Toast.makeText(mContext, "Регистрирањето беше успешно.Ви пративме верификација на email", Toast.LENGTH_SHORT).show();
mAuth.signOut();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
finish();
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
I do NOT advise the ability to sign up with ONLY a username. You lose the ability to recover an account.
However, you may take the username given to you, and append #fakeemail.com to the end of it and continue to use the email/password method.

Simultaneously Sending a message to Users who are on the same database

I have been trying to send a custom message in my database (Emergency_Contact) by a button click (mRescue), when a button is clicked it's going to check the user_id of the person who pressed the button after that check in Emergency_Contact for every person who has the senders_user_id as their child, If they have the sender_user_id as their child it sends them the message else it return a Toast message. I tried to run my code but it's crashing i don't know why.
this is my activity where this is carried out.
public class MenuActivity extends AppCompatActivity
{
Button mRescue;
private Double lati;
private GoogleMap mMap;
LocationManager locationManager;
private DatabaseReference mRootRef;
private String mCurrentUserId;
private String userName;
private String mChatUser;
private DatabaseReference mNotificationDatabase;
private String message;
private String value_lat = null;
private String value_long = null;
private FirebaseAuth mAuth;
private DatabaseReference mUserRef;
LocationTrack locationTrack;
private DatabaseReference usersDatabase;
private DatabaseReference emergencyContactDB;
private String user_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
FirebaseApp.initializeApp(this);
usersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
emergencyContactDB = FirebaseDatabase.getInstance().getReference().child("Emergency_Contact");
mNotificationDatabase = FirebaseDatabase.getInstance().getReference().child("Emergency_Notifications");
mRootRef = FirebaseDatabase.getInstance().getReference();
mLocationDatabase = mRootRef.child("EmergencyMessages");
mAuth = FirebaseAuth.getInstance();
gettingIntent();
mRescue = (Button)findViewById(R.id.rescue);
mRescue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
if(value_lat == null & value_long == null)
{
mRescue.setEnabled(false);
}
else
{
mRescue.setEnabled(true);
usersDatabase.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
final String user_db = dataSnapshot.child("user_id").getValue().toString();
if (!user_db.isEmpty())
{
user_id = dataSnapshot.child("user_id").getValue().toString();
emergencyContactDB.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
final String emergency_db = dataSnapshot.child(user_id).getValue().toString();
if (emergency_db.contains(mCurrentUserId))
{
addEmergencyMessage();
addEmergencyChat();
Toast.makeText(getApplicationContext(), "Emergency Alert message was successfully sent",Toast.LENGTH_LONG).show();
} else
{
Toast.makeText(getApplicationContext(), "You Do not have any emergency contacts. Please add them and try again.",Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
else {
Toast.makeText(getApplicationContext(), "The Database is Empty",Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Alerts");
toolbar.setTitleTextColor(android.graphics.Color.WHITE);
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) {
}
});
}
private void checkUser() {
if (mCurrentUserId == null) {
sendToStart();
}else{
mUserRef.child("online").setValue("true");
}
}
private void gettingIntent() {
Intent intent =getIntent();
mChatUser = intent.getStringExtra("user_id");
}
private void addEmergencyChat() {
value_lat = String.valueOf(mLastLocation.getLatitude());
value_long = String.valueOf(mLastLocation.getLongitude());
String current_user_ref="Emergency_Messages/"+mCurrentUserId+"/"+user_id;
String chat_user_ref= "Emergency_Messages/"+user_id+"/"+mCurrentUserId;
DatabaseReference chat_push_key = mRootRef.child("Emergency_Messages").child(mCurrentUserId).child(user_id).push();
String push_key = chat_push_key.getKey();
Map messageMap = new HashMap();
messageMap.put("userName", userName + " is in trouble on this location:"+"\nlatitude ="+value_lat +"\nlongitude ="+ value_long);
messageMap.put("open_location", "Tap Here to see "+userName+"'s location");
messageMap.put("type","text");
messageMap.put("latitude",value_lat);
messageMap.put("longitude", value_long);
messageMap.put("from",mCurrentUserId);
messageMap.put("seen",false);
messageMap.put("time", ServerValue.TIMESTAMP);
DatabaseReference newNotificationref = mRootRef.child("Emergency_Notifications").child(user_id).push();
String newNotificationId = newNotificationref.getKey();
HashMap<String, String> notificationData = new HashMap<>();
notificationData.put("from", mCurrentUserId);
notificationData.put("type", "alert");
Map messageNotifMap = new HashMap();
messageNotifMap.put("Emergency_Notifications/" + user_id + "/" + newNotificationId, notificationData);
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(user_id)){
Map chatAddMap = new HashMap();
chatAddMap.put("seen",false);
chatAddMap.put("timestamp", ServerValue.TIMESTAMP);
Map chatUserMap = new HashMap();
chatUserMap.put("Emergency_Chat/"+mCurrentUserId+"/"+user_id, chatAddMap);
chatUserMap.put("Emergency_Chat/"+user_id+"/"+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.
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser == null){
sendToStart();
} else{
mCurrentUserId = mAuth.getCurrentUser().getUid();
mUserRef.child("online").setValue("true");
}
}
#Override
protected void onStop() {
super.onStop();
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();
}
}
How can I send this message?
this is my logcat
02-12 07:01:23.046 32377-32377/? E/Zygote: no v2
02-12 07:01:23.056 32377-32377/? E/SELinux: [DEBUG] get_category:
variable seinfo: default sensitivity: NULL, cateogry: NULL
02-12 07:01:34.477 32377-32377/com.rescuex_za.rescuex E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.rescuex_za.rescuex, PID: 32377
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at com.rescuex_za.rescuex.MenuActivity$1$1.onDataChange(MenuActivity.java:128)
at com.google.android.gms.internal.zzegf.zza(Unknown Source)
at com.google.android.gms.internal.zzeia.zzbyc(Unknown Source)
at com.google.android.gms.internal.zzeig.run(Unknown Source)
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 happening because dataSnapshot is null and you are calling toString() on a null object reference. To solve this, check first the dataSnapshot for existens because using it.
if(dataSnapshot != null && dataSnapshot.exists()) {
//your logic
}
To only get the pJhp..., please use the following code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Emergency_Contact").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String key = ds.getKey();
Log.d("TAG", key);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(eventListener);

How to retrieve certain database child and display inside the ListView

How to retrieve/call userInfo from the following database, It is an authenticated user information
StudentInformation java class.
public class StudentInformation {
String name;
String ID;
String studentID;
String email;
String phone_num;
public StudentInformation() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public String getStudentID() {
return studentID;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone_num() {
return phone_num;
}
public void setPhone_num(String phone_num) {
this.phone_num = phone_num;
}
}
I've tried a lot of method, but the ListView still display none and the app suddenly stopped.
public class StudentInfoActivity extends AppCompatActivity {
//add Firebase Database stuff
private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;
private String userID;
ListView mListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_info);
mListView = (ListView) findViewById(R.id.listview);
//declare the database reference object. This is what we use to access the database.
//NOTE: Unless you are signed in, this will not be useable.
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
FirebaseUser user = mAuth.getCurrentUser();
userID = user.getUid();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
toastMessage("User Information");
} else {}
// ...
}
}; //end authlistener
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
showData(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} // end oncreate
private void showData(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
StudentInformation sInfo = new StudentInformation();
sInfo.setName(ds.child(userID).child("userInfo").getValue(StudentInformation.class).getName());
sInfo.setID(ds.child(userID).child("userInfo").getValue(StudentInformation.class).getID());
sInfo.setStudentID(ds.child(userID).child("userInfo").getValue(StudentInformation.class).getStudentID());
sInfo.setEmail(ds.child(userID).child("userInfo").getValue(StudentInformation.class).getEmail());
sInfo.setPhone_num(ds.child(userID).child("userInfo").getValue(StudentInformation.class).getPhone_num());
ArrayList<String> array = new ArrayList<>();
array.add(sInfo.getName());
array.add(sInfo.getID());
array.add(sInfo.getStudentID());
array.add(sInfo.getEmail());
array.add(sInfo.getPhone_num());
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,array);
mListView.setAdapter(adapter);
}
} //end showdata
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void toastMessage(String message){
Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
}
} // end class
This is the code Im using. I've been wondering about the getchildren method, did I do something wrong in the code ?. Can anyone help me with this ?
You can go with FirebaseListAdapter .Here you won't have to manage any changes or attach listener and everything in the list gets updated when there is any change in server
To get the data please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userInfoRef = rootRef.child("users").child(userID).child("userInfo");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String ID = ds.child("ID").getValue(String.class);
String email = ds.child("email").getValue(String.class);
String name = ds.child("name").getValue(String.class);
String phone_num = ds.child("phone_num").getValue(String.class);
String studentID = ds.child("studentID").getValue(String.class);
Log.d("TAG", ID + " / " + email + " / " + name + " / " + phone_num + " / " + studentID);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userInfoRef.addListenerForSingleValueEvent(eventListener);

Categories