I i am working with firebase realtime database.. I retrieved data and everything but my main problem is that the data is not being displayed unless i press back button.. I went through stacks everywhere it suggested to notifyDataSetChanged(); which i did before, but still no luck. As i am using GridLayout i cant use the adapter in the addListeneOnDatachange function as it shows error saying that it is not allowed to add the adapter there for my RecyclerViewAdapter.
package my.unimas.a50200siswa.studentattendancemonitoringsystem;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class HomeActivity extends AppCompatActivity {
String userID;
List<CourseModel> listCourse;
TextView btnSignOut, UserName;
/*---- Firebase Database stuff ----*/
FirebaseAuth mAuth;
FirebaseUser user;
FirebaseAuth.AuthStateListener mAuthListener;
DatabaseReference myRef;
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
/*-------Finding View---------*/
btnSignOut = (TextView) findViewById(R.id.btnsignout_home);
UserName = findViewById(R.id.username);
RecyclerView myrv = findViewById(R.id.recyclerviewcourse);
myrv.setLayoutManager(new GridLayoutManager(this,2));
// CourseCode();
btnSignOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAuth.signOut();
}
});
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() == null) {
startActivity(new Intent(HomeActivity.this, SignInActivity.class));
}
}
};
/* ----------------- Firebase Elements -----------------*/
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
userID = user.getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
myRef = rootRef.child("Users");
/*------------------------------------------------------------------*/
listCourse = new ArrayList<>();
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String userName = dataSnapshot.child(userID).child("userName").getValue(String.class);
UserName.setText(userName);
String coursecode[] = new String[10];
String coursename[] = new String[10];
listCourse.clear();
if (dataSnapshot.exists()) {
int i = 1;
for (DataSnapshot dataSnapshot1 : dataSnapshot.child(userID).child("Course").getChildren()) {
coursecode[i]= dataSnapshot1.getKey();
coursename[i]=dataSnapshot.child(userID).child("Course").child(coursecode[i]).child("CourseName").getValue(String.class);
listCourse.add(new CourseModel(userID,coursecode[i],coursename[i]));
i++;
}
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("Hello", "Failed to read value.", error.toException());
}
});
RecyclerViewAdapterCourse myAdapter = new RecyclerViewAdapterCourse(this,listCourse);
myAdapter.notifyDataSetChanged();
myrv.setAdapter(myAdapter);
}
}
You need to call myAdapter.notifyDataSetChanged() every time the data changes. In your case this means you need to call it at the end of the onDataChanged(DataSnapShot dataSnapShot) function.
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String userName = dataSnapshot.child(userID).child("userName").getValue(String.class);
UserName.setText(userName);
String coursecode[] = new String[10];
String coursename[] = new String[10];
listCourse.clear();
if (dataSnapshot.exists()) {
int i = 1;
for (DataSnapshot dataSnapshot1 : dataSnapshot.child(userID).child("Course").getChildren()) {
coursecode[i]= dataSnapshot1.getKey();
coursename[i]=dataSnapshot.child(userID).child("Course").child(coursecode[i]).child("CourseName").getValue(String.class);
listCourse.add(new CourseModel(userID,coursecode[i],coursename[i]));
i++;
}
}
myAdapter.notifyDataSetChanged()
}
Related
I want to get data from Firebase database and put it in an object.
I can see I correctly access the data in database, but cannot put it in my object.
FirebaseMethods
package com.example.android.instagramclone.Utils;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.example.android.instagramclone.R;
import com.example.android.instagramclone.models.User;
import com.example.android.instagramclone.models.UserAccountSettings;
import com.example.android.instagramclone.models.UserSettings;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class FirebaseMethods {
private static final String TAG = "FirebaseMethods";
private Context mContext;
//Firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseDatabase database;
private DatabaseReference reference;
private String userid;
/**
* constructor
*
* #param mContext
*/
public FirebaseMethods(Context mContext) {
mAuth = FirebaseAuth.getInstance();
//initialize database.
database = FirebaseDatabase.getInstance();
reference = database.getReference();
this.mContext = mContext;
if (mAuth.getCurrentUser() != null) {
//userID is unique to each user.
userid = mAuth.getCurrentUser().getUid();
}
}
/**
* add information to the users nodes.
* add information to the account setting node.
*
* #param username
* #param email
* #param description
* #param website
* #param profile_photo
*/
public void addNewUser(String username, String email, String description, String website, String profile_photo) {
//setting up user personal info.
User user = new User(StringManupulation.condenseUsername(username), 1, email, username);
//reference a node;
reference.child(mContext.getString(R.string.dbname_users)).child(userid).setValue(user);
//setting up userAccountSetting
UserAccountSettings settings = new UserAccountSettings(
description,
username,
0,
0,
0,
"",
StringManupulation.condenseUsername(username),
website
);
reference.child(mContext.getString(R.string.dbname_user_account_settings))
.child(userid)
.setValue(settings);
}
/**
* setting up FirebaseAuthentificationListener.
*/
private void updateUI() {
Log.d(TAG, "updateUI: started.");
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
Log.d(TAG, "onAuthStateChanged: successfully logged in.");
} else {
Log.d(TAG, "onAuthStateChanged: authentification failed.");
}
}
};
}
/**
* retrieve the account settings from Forebase database.
*
* #param dataSnapshot
* #return
*/
public UserSettings getUserSettings(DataSnapshot dataSnapshot) {
Log.d(TAG, "getUserAccountSettings: retrieving user acoount settings from firebase.");
UserAccountSettings settings = new UserAccountSettings();
User user = new User();
//Read through all the major nodes.
for (DataSnapshot ds : dataSnapshot.getChildren()) {
// If the name of a node is "user_account_setings".
if (ds.getKey().equals(mContext.getString(R.string.dbname_user_account_settings))) {
Log.d(TAG, "getUserAccountSettings: datasnapshot: "+ ds);
try {
//Setting display_name.
settings.setDisplay_name(ds.child(userid)
.getValue(UserAccountSettings.class)
.getDisplay_name());
Log.d(TAG, "getUserSettings: " + settings.getDisplay_name());
//Setting username.
settings.setUsername(ds.child(userid)
.getValue(UserAccountSettings.class)
.getUsername());
//Setting website.
settings.setWebsite(ds.child(userid)
.getValue(UserAccountSettings.class)
.getWebsite());
//Setting description.
settings.setDescription(ds.child(userid)
.getValue(UserAccountSettings.class)
.getDescription());
//Setting profile_photo.
settings.setProfile_photo(ds.child(userid)
.getValue(UserAccountSettings.class)
.getProfile_photo());
//Setting posts.
settings.setPost(ds.child(userid)
.getValue(UserAccountSettings.class)
.getPost());
//Setting followers.
settings.setFollowers(ds.child(userid)
.getValue(UserAccountSettings.class)
.getFollowers());
//Setting Followings.
settings.setFollowing(ds.child(userid)
.getValue(UserAccountSettings.class)
.getFollowing());
Log.d(TAG, "getUserAccountSettings: retrieved user_account_settings info.");
} catch (NullPointerException e) {
Log.e(TAG, "getUserAccountSettings: " + e.getMessage());
}
//users node
if (ds.getKey().equals(R.string.dbname_users)) {
Log.d(TAG, "getUserAccountSettings: dataSnapShot: " + ds);
try {
//Setting mail.
user.setMail(ds.child(userid)
.getValue(User.class)
.getMail());
//Setting username.
user.setUsername(ds.child(userid)
.getValue(User.class)
.getUsername());
//Setting phone_number.
user.setPhone_number(ds.child(userid)
.getValue(User.class)
.getPhone_number());
//Setting userID.
user.setUserID(ds.child(userid)
.getValue(User.class)
.getUserID());
Log.d(TAG, "getUserAccountSettings: retrieved user info.");
} catch (NullPointerException e) {
Log.e(TAG, "getUserAccountSettings: " + e.getMessage());
}
}
}
}
return new UserSettings(user, settings);
}
}
Profile Fragment
package com.example.android.instagramclone.Profile;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.example.android.instagramclone.R;
import com.example.android.instagramclone.Utils.BottomNavigationViewHelper;
import com.example.android.instagramclone.Utils.FirebaseMethods;
import com.example.android.instagramclone.Utils.GridImageAdapter;
import com.example.android.instagramclone.Utils.UniversalImageLoader;
import com.example.android.instagramclone.models.User;
import com.example.android.instagramclone.models.UserAccountSettings;
import com.example.android.instagramclone.models.UserSettings;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import de.hdodenhof.circleimageview.CircleImageView;
public class ProfileFragment extends Fragment {
private static final String TAG = "ProfileFragment";
private Context mContext;
private TextView mPosts;
private TextView mFollowers;
private TextView mFollowings;
private TextView mDisplayName;
private TextView mUserName;
private TextView mWebsite;
private TextView mDescription;
private ProgressBar mProgressBar;
private CircleImageView mProfilePhoto;
private GridView gridView;
private ImageView profileMenu;
private android.support.v7.widget.Toolbar toolbar;
private BottomNavigationView bottomNavigationView;
//For bottomNavigationView icons.
private static final int ACTIVITY_NUM = 4;
//The number of columns of gridView for pics uploaded.
private static final int NUM_GRID_COLUMNS = 3;
//Firebase things.
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseDatabase database;
private DatabaseReference myRef;
private FirebaseMethods mFirebaseMethods;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile, container, false);
Log.d(TAG, "onCreateView: started.");
//Setting up each widgets.
mDisplayName = (TextView) view.findViewById(R.id.display_name);
mUserName = (TextView) view.findViewById(R.id.username);
mPosts = (TextView) view.findViewById(R.id.tv_posts);
mFollowings = (TextView) view.findViewById(R.id.tvFollowing);
mFollowers = (TextView) view.findViewById(R.id.tvFollowers);
mWebsite = (TextView) view.findViewById(R.id.display_website);
mDescription = (TextView) view.findViewById(R.id.display_description);
mProfilePhoto = (CircleImageView) view.findViewById(R.id.profile_image);
mProgressBar = (ProgressBar) view.findViewById(R.id.profileProgressBar);
gridView = (GridView) view.findViewById(R.id.gridview);
toolbar = (android.support.v7.widget.Toolbar) view.findViewById(R.id.profileToolBar);
profileMenu = (ImageView) view.findViewById(R.id.profile_menu);
bottomNavigationView = (BottomNavigationView) view.findViewById(R.id.bottomNavViewBar);
mContext = getActivity();
mFirebaseMethods = new FirebaseMethods(getActivity());
//setting up progress bar
mProgressBar.setVisibility(View.GONE);
setupBottomNavigationView();
setupToolbar();
setUpFirebaseAuth();
return view;
}
/**
* Setting up information retrieving from FIrebaseDatabase.
* #param userSettings
*/
private void setProfileWidgets(UserSettings userSettings){
//Create instances.
User user = userSettings.getUser();
UserAccountSettings accountSettings = userSettings.getSettings();
Log.d(TAG, "setProfileWidgets: Setting Widgets with data retrieving from firebaseDatabase: " + accountSettings.toString());
//Set values to each views.
UniversalImageLoader.setImage(accountSettings.getProfile_photo(), mProfilePhoto, null, "");
mDisplayName.setText(accountSettings.getDisplay_name());
mUserName.setText(accountSettings.getUsername());
mWebsite.setText(accountSettings.getWebsite());
mDescription.setText(accountSettings.getDescription());
mPosts.setText(String.valueOf(accountSettings.getPost()));
mFollowers.setText(String.valueOf(accountSettings.getFollowers()));
mFollowings.setText(String.valueOf(accountSettings.getFollowing()));
}
/**
* setting up the toolBar on the top.
*/
private void setupToolbar() {
//アクションバーとしてtoolbarを使う
((ProfileActivity) getActivity()).setSupportActionBar(toolbar);
// When the toolbar button is tapped, navigate to Account setting page.
profileMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to account settings.");
Intent intent = new Intent(mContext, AccountSettingActivity.class);
startActivity(intent);
}
});
}
/**
* set up bottomNavigationView
*/
private void setupBottomNavigationView() {
Log.d(TAG, "setBottomNavigationView: setting up bottomNavigationView");
BottomNavigationViewHelper.enableNavigation(mContext, bottomNavigationView);
Menu menu = bottomNavigationView.getMenu();
MenuItem menuItem = menu.getItem(ACTIVITY_NUM);
menuItem.setChecked(false);
}
/**
* -----------------Firebase section starts------------------------*
*/
/**
* Setting up FirebaseAuth for Authentification of user
*/
private void setUpFirebaseAuth() {
Log.d(TAG, "setUpFirebaseAuth: started.");
mAuth = FirebaseAuth.getInstance();
//Preparing to get info from FirebaseDatabase.
database = FirebaseDatabase.getInstance();
myRef = database.getReference();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
Log.d(TAG, "onAuthStateChanged: User logged in.");
} else if (user == null) {
Log.d(TAG, "onAuthStateChanged: User not logged in.");
}
}
};
//Allow us to get data snapshot and read, write data.
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//retrieve user info from database.
setProfileWidgets(mFirebaseMethods.getUserSettings(dataSnapshot));
//retrieve images for the user in question.
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart: started.");
//user Authentification and update UI accordingly.
setUpFirebaseAuth();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop: started.");
if(mAuthListener != null ){
mAuth.removeAuthStateListener(mAuthListener);
}
}
/**
* -----------------Firebase section ends ------------------------*
*/
}
log.d in FirebaseMethods shows me the content of "ds" correctly, which means I can access the data correctly. However, when I see each value in the object "accountSettings" after put data in it, it shows me null for String, and 0 for long values, which are initialized values.
Could you tell me why this happens and how I can solve this problem?
Thanks in advance.
i dont know if this would will be useful but this is how i get data from firebase i set it.
private DatabaseReference mUsernameDatabase;
//
mUsernameDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid);
mUsernameDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String about = Objects.requireNonNull(dataSnapshot.child("about").getValue()).toString();
editAbout.setText(about);
String address = Objects.requireNonNull(dataSnapshot.child("address").getValue()).toString();
editAddress.setText(address);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(Profile.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Thanks all, I solved the problem.
That was because I had deleted the account I was logged in.
Not because of my code.
But I learned a lot from your answers.
Thanks again.
I am creating an app for real time gps tracking for a group of users. I managed to display every user location with a marker on the map (map activity - using Google Maps), and also to update the location on the map every 5 seconds (I update the 'longitude' and 'latitude' fields of the user in Firebase Database every 3 seconds, and then read this fields every 5 seconds and update all the markers on the map).
I tried walking around with 3 different phones, and noticed that not all the markers (its not always the same markers, but if some marker is stuck on one phone, the same marker is stuck on the other phones) are moving with me as I walk. They start moving in the beginning for a small amount of time and then they stop moving at all. After I keep walking for a while they suddenly update (jump to the current location) and then stuck again... Or in other words the updates of some of the markers happens with big delays.
What could be the reason for such delays and how can I fix it?
Pictures of my Firebase Database (Managers and Users):
Pictures of my Firebase Database - Managers
Pictures of my Firebase Database - Users
(I create a manager which represents a group, and the manager have a list of users that are in his group, and then I go through the list of users of the manager and update their location on Firebase Database. Then when a user click on 'map' button it goes through to GroupMapActivity and there I read the locations from Firebase Databse every 5 seconds and update the markers).
The code for updating the location on Firebase Database using service:
package com.example.lidor.findmygroup;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.HashMap;
import java.util.Map;
public class FindMeService extends IntentService
{
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
String userEmail = "", key = "";
LocationTrack locationTrack;
double longitude, latitude;
User user;
public FindMeService()
{
super("FindMeService");
}
#Override
protected void onHandleIntent(Intent intent)
{
firebaseDatabase = FirebaseDatabase.getInstance();
if (intent.hasExtra("email"))
userEmail = intent.getStringExtra("email").toString();
databaseReference = firebaseDatabase.getReference("USERS");
databaseReference.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
for (DataSnapshot d : dataSnapshot.getChildren())
{
User curUser = d.getValue(User.class);
if (userEmail.equals(curUser.Email))
{
key = d.getKey();
user = curUser;
break;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
while (true)
{
try
{
Thread.sleep(3000);
locationTrack = new LocationTrack(FindMeService.this);
if (locationTrack.canGetLocation())
{
longitude = locationTrack.getLongitude();
latitude = locationTrack.getLatitude();
databaseReference.child("USERS").child(key).
addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
Map<String, Object> updates = new HashMap<>();
for (DataSnapshot s : dataSnapshot.getChildren())
{
updates.put(s.getKey(), s.getValue());
}
updates.put("UserName", user.UserName);
updates.put("Age", user.Age);
updates.put("Phone", user.Phone);
updates.put("City", user.City);
updates.put("Email", user.Email);
updates.put("longitude", longitude);
updates.put("latitude", latitude);
updates.put("Is_In_Group", user.Is_In_Group);
updates.put("ManagerEmail", user.ManagerEmail);
updates.put("Is_Manager", user.Is_Manager);
updates.put("Is_Connected", user.Is_Connected);
databaseReference.child(key).updateChildren(updates);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
else
{
locationTrack.showSettingsAlert();
Toast.makeText(FindMeService.this, "No GPS signal",
Toast.LENGTH_LONG).show();
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
#Override
public void onDestroy()
{
super.onDestroy();
}
}
The Group Map Activity:
package com.example.lidor.findmygroup;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class GroupMapActivity extends FragmentActivity implements OnMapReadyCallback
{
private GoogleMap mMap;
Handler handler;
String email = "", managerEmail = "", managerKey = "";
int i = 0;
Marker marker;
FirebaseAuth firebaseAuth;
FirebaseDatabase firebaseDatabase, firebaseDatabase1, firebaseDatabase2;
DatabaseReference databaseReference, databaseReference1, databaseReference2;
Boolean endFor = false, endFor1 = false, endFor2 = false;
ProgressDialog progressDialog;
HashMap<String, Marker> markers;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group_map);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
firebaseDatabase1 = FirebaseDatabase.getInstance();
firebaseDatabase2 = FirebaseDatabase.getInstance();
//builder = new LatLngBounds.Builder();
Intent intent = getIntent();
if (intent.hasExtra("email")) email = intent.getStringExtra("email").toString();
markers = new HashMap<>();
progressDialog = new ProgressDialog(GroupMapActivity.this);
progressDialog.setMessage("Map Loading Please Wait...");
progressDialog.show();
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mMap = googleMap;
handler = new Handler();
handler.postDelayed(new Runnable()
{
public void run()
{
Real_Time_Group_Map();
progressDialog.dismiss();
handler.postDelayed(this, 1000);
}
}, 1000);
}
public void Real_Time_Group_Map()
{
// 1# -------------------------------------------------------------------------------------
databaseReference = firebaseDatabase.getReference("USERS");
databaseReference.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
for (DataSnapshot d : dataSnapshot.getChildren())
{
if (endFor) continue;
User curUser = d.getValue(User.class);
if (email.equals(curUser.Email))
{
endFor = true;
managerEmail = curUser.ManagerEmail;
databaseReference = firebaseDatabase.getReference("MANAGERS");
databaseReference.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
for (DataSnapshot d : dataSnapshot.getChildren())
{
if (endFor1) continue;
Manager curManager = d.getValue(Manager.class);
if (managerEmail.equals(curManager.Email))
{
endFor1 = true;
managerKey = d.getKey();
databaseReference1 = firebaseDatabase1.getReference("MANAGERS").
child(managerKey).child("Group Users");
databaseReference1.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
for (DataSnapshot d : dataSnapshot.getChildren())
{
final String curFriend = d.getValue().toString();
databaseReference2 = firebaseDatabase2.getReference("USERS");
databaseReference2.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
for (DataSnapshot d : dataSnapshot.getChildren())
{
User curUser = d.getValue(User.class);
String emailUser = curUser.Email;
if (curFriend.equals(emailUser))
{
LatLng location = new LatLng(
curUser.latitude, curUser.longitude);
Marker delMarker = markers.get(emailUser);
if (delMarker != null) delMarker.remove();
markers.remove(emailUser);
if (curUser.Is_Manager)
{
marker = mMap.addMarker(new MarkerOptions()
.position(location).title(curUser.UserName).icon(
BitmapDescriptorFactory.defaultMarker(
BitmapDescriptorFactory.HUE_BLUE)).
snippet(emailUser));
}
else
{
marker = mMap.addMarker(new MarkerOptions()
.position(location).title(curUser.UserName)
.snippet(emailUser));
}
markers.put(emailUser, marker);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(location,18));
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener()
{
#Override
public boolean onMarkerClick(Marker marker)
{
Intent intent = new Intent(GroupMapActivity.this, MemberActivity.class);
intent.putExtra("email", marker.getSnippet());
startActivity(intent);
return false;
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
break;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
break;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
I have an app that asks a series of questions. These questions are stored on the firebase db. I am trying to change the child node "Status" from the click of the button. The button being pressed for testing is button "AnswerA".
To date i have managed to change all "Status" nodes to the button press but i only want to change one at a time as the questions are being asked.
if (clickedButton.getText().equals(Common.questionList.get(index).getCorrectAnswer())) {
final FirebaseDatabase database = FirebaseDatabase.getInstance();
//db reference
final DatabaseReference ref = database.getReference("Questions");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot questionCode : dataSnapshot.getChildren()) {
String questionCodeKey = questionCode.getKey();
//Retrieve value at child node AnswerA
String correctAnswerString = questionCode.child("AnswerA").getValue(String.class);
//Take value of AnswerA and place it in new node "Status"
ref.child(questionCodeKey).child("Status").setValue(correctAnswerString);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
You are looping though all questions and performing the same logic on all of them. You want to select only the question you are interested in, e.g.:
for (DataSnapshot questionCode : dataSnapshot.getChildren()) {
String questionCodeKey = questionCode.getKey();
if (questionCodeKey.equals()) { // TODO: How you chose the child from your index
//Retrieve value at child node AnswerA
String correctAnswerString = questionCode.child("AnswerA").getValue(String.class);
//Take value of AnswerA and place it in new node "Status"
ref.child(questionCodeKey).child("Status").setValue(correctAnswerString);
}
}
Adding full playing activity for review,
import android.content.Intent;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.hiverecord.kee01.hiverecord.Common.Common;;
import com.hiverecord.kee01.hiverecord.Model.Question;
import com.hiverecord.kee01.hiverecord.Model.QuestionList;
import com.hiverecord.kee01.hiverecord.Model.User;
import com.squareup.picasso.Picasso;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
public class Playing extends AppCompatActivity implements View.OnClickListener {
final static long INTERVAL = 5000; //5sec
final static long TIMEOUT = 60000; //70 sec
int progressValue = 0;
CountDownTimer mCountDown;
int index=0,
thisQuestion=0,
totalQuestion,
correctAnswer;
ProgressBar progressBar;
ImageView question_image;
Button btnA,btnB;
TextView txtQuestionNum,question_text;
FirebaseDatabase database;
DatabaseReference test;
private int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playing);
database = FirebaseDatabase.getInstance();
test = database.getReference("Questions"); //get the reference
//Views
txtQuestionNum = findViewById(R.id.txtTotalQuestion);
question_text = findViewById(R.id.question_text);
question_image = findViewById(R.id.question_image);
progressBar = findViewById(R.id.progressBar);
btnA = findViewById(R.id.btnAnswerA);
btnB = findViewById(R.id.btnAnswerB);
btnA.setOnClickListener(this);
btnB.setOnClickListener(this);
}
#Override
public void onClick(View view) {
mCountDown.cancel();
if (index < totalQuestion)
{
Button clickedButton = (Button) view;
if (clickedButton.getText().equals(Common.questionList.get(index).getCorrectAnswer())) {
final FirebaseDatabase database = FirebaseDatabase.getInstance();
//db reference
final DatabaseReference ref = database.getReference("Questions");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot questionCode : dataSnapshot.getChildren()) {
String questionCodeKey = questionCode.getKey();
if (questionCodeKey.equals(Common.questionList.get(index).getKey())){
//Retrieve value at child node AnswerA
String correctAnswerString = questionCode.child("AnswerA").getValue(String.class);
//Take value of AnswerA and place it in new node "Status"
ref.child(questionCodeKey).child("Status").setValue(correctAnswerString);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
btnA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
correctAnswer++;
showQuestion(++index); //next question
}
});
}
else {
Map<String, Object> userUpdates = new HashMap<>();
//userUpdates.put("AnswerA", "");
//userUpdates.put("AnswerB", "NO");
test.updateChildren(userUpdates);
//choose answer false
Intent intent = new Intent(this,Done.class);
Bundle dataSend = new Bundle();
//dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL", totalQuestion);
dataSend.putInt("CORRECT", correctAnswer);
intent.putExtras(dataSend);
showQuestion(++index);
}
}
}
private void showQuestion(int index) {
if(index < totalQuestion)
{
thisQuestion++;
txtQuestionNum.setText(String.format("%d/%d",thisQuestion, totalQuestion));
progressBar.setProgress(0);
progressValue=0;
if(Common.questionList.get(index).getIsImageQuestion().equals("true"))
{
//if is image
Picasso.with(getBaseContext())
.load(Common.questionList.get(index).getQuestion())
.into(question_image);
question_image.setVisibility(View.VISIBLE);
question_text.setVisibility(View.VISIBLE);
}
else
{
question_text.setText(Common.questionList.get(index).getQuestion());
//If question is text, we will set image to invisible
question_image.setVisibility(View.INVISIBLE);
question_text.setVisibility(View.VISIBLE);
}
btnA.setText(Common.questionList.get(index).getAnswerA());
btnB.setText(Common.questionList.get(index).getAnswerB());
mCountDown.start(); //Start timer
}
else
{
//if it is a final question
Intent intent = new Intent(this,Done.class);
Bundle dataSend = new Bundle();
//dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL", totalQuestion);
dataSend.putInt("CORRECT", correctAnswer);
intent.putExtras(dataSend);
startActivity(intent);
finish();
}
}
#Override
protected void onResume() {
super.onResume();
totalQuestion = Common.questionList.size();
mCountDown = new CountDownTimer(TIMEOUT,INTERVAL) {
#Override
public void onTick(long minisec) {
progressBar.setProgress(progressValue);
progressValue++;
}
#Override
public void onFinish() {
mCountDown.cancel();
showQuestion(++index);
}
};
showQuestion(index);
}
}
Solution:
btnA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//logcat and show the index
Log.i("Button A Index accessed", index + "");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Get DataSnapShot of Children in ref Questions
for (DataSnapshot questionCode : dataSnapshot.getChildren()) {
String questionCodeKey = questionCode.getKey();
if (questionCodeKey.equals("0" + index)) {
//Retrieve value at child node AnswerA
String correctAnswerString = questionCode.child("AnswerA").getValue(String.class);
//Take value of AnswerA and place it in new node "Status"
ref.child(questionCodeKey).child("Status").setValue(correctAnswerString);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here is my code.
package com.example.manali.likeex;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class MainActivity2 extends Activity implements View.OnClickListener {
Button senlike;
private DatabaseReference mdatabase;
private DatabaseReference user1;
int c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Button sendlike = (Button) findViewById(R.id.b1);
mdatabase= FirebaseDatabase.getInstance().getReference();
user1=mdatabase.child("Teacher");
sendlike.setOnClickListener(this);
}
//when user clicks on button counter on firebase get increased
public void onClick(View view)
{
if(user1!=null)
{
c++;
}
//sets value to user1 node
user1.setValue(c);
}
public DatabaseReference getUser1()
{
return user1;
}
}
This code only increases counter when app is active. When we close the app, and restart it again. The counter starts again with 1. Hence I want to maintain this counter.
DatabaseReference upvotesRef = ref.child("server/saving-data/fireblog/posts/-JRHTHaIs-jNPLXOQivY/upvotes");
upvotesRef.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
Integer currentValue = mutableData.getValue(Integer.class);
if (currentValue == null) {
mutableData.setValue(1);
} else {
mutableData.setValue(currentValue + 1);
}
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean committed, DataSnapshot dataSnapshot) {
System.out.println("Transaction completed");
}
});
You could have a count column under your Teacher table:
App
---Teacher
------Count
Then with that you could query the count and put it in a variable so you could increment the value then update the value in firebase:
public void onClick(View view) {
DatabaseReference ref = mdatabase.child("Teacher");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int count = (int) dataSnapshot.child("count").getValue();
ref.child("count").setValue(count++);
}
#Override
public void onCancelled(FirebaseError firebaseError) { }
});
}
So I have Firebase Database that looks like this:
{
"lists" : {
"-KZh-vvPcPGVqC22k2Bo" : {
"dateCreated" : "2016-12-23",
"listDescription" : "My Christmas Wish List for 2016",
"listTitle" : "William's Christmas List",
"user" : "ztGAx7eplGeZgdjqnegrtbfuyUy2"
}
},
"users" : {
"8pJJuscerZRGdwGGImnWlCKSEed2" : {
"email" : "example#example.com",
"name" : "Alyson"
},
"ztGAx7eplGeZgdjqnegrtbfuyUy2" : {
"email" : "example#example.com",
"name" : "William"
}
}
}
I am trying to only return the lists objects where the user field equals the UID of the logged in user. That way the logged in user gets all his lists. But I am having trouble querying the data that is in lists because of the unique key that is generated by push() which I use to append to lists whenever a user creates a new list object. How do I go about querying lists so that I get only the lists that match the UID of the signed in user? I have this so far
package com.fanciestw.listpro;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
public class allList extends AppCompatActivity {
private FirebaseAuth mAuth = FirebaseAuth.getInstance();
private FirebaseAuth.AuthStateListener mAuthStateListener;
private FirebaseDatabase mDatabase = FirebaseDatabase.getInstance();
private DatabaseReference mList = mDatabase.getReference().child("lists");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_list);
mAuthStateListener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth){
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user != null) {
Log.d("User Activity", "User Signed In");
} else {
Log.d("User Activity", "User Signed Out");
signout(getCurrentFocus());
}
}
};
mList.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
List newList = dataSnapshot.getValue(List.class);
Log.d("List Returned", newList.listTitle + " " + newList.listDescription);
updateList();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
updateList();
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onStart(){
super.onStart();
Log.d("allList Activity", "onStart");
mAuth.addAuthStateListener(mAuthStateListener);
}
#Override
public void onStop(){
super.onStop();
Log.d("allList Activity", "onStop");
if(mAuthStateListener != null) mAuth.removeAuthStateListener(mAuthStateListener);
}
public void addNewList(View view){
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add New List");
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.add_new_list_form, null);
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(dialogView);
// Set up the buttons
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String title = ((EditText)dialogView.findViewById(R.id.add_list_title)).getText().toString();
String desc = ((EditText)dialogView.findViewById(R.id.add_list_desc)).getText().toString();
Log.d("New List Details", title + ", " + desc);
//TODO::Store created list with title and desc in database
List newList = new List(title, desc, mAuth.getCurrentUser().getUid());
String newListID = mList.push().getKey();
mList.child(newListID).setValue(newList);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
public void updateList(){
//Want to get lists where lists.user == firebaseAuth.getCurrentUser().UID();
}
public void signout(View view){
mAuth.signOut();
Intent intent = new Intent(this, login.class);
startActivity(intent);
}
}
Declare
private FirebaseAuth mAuth;
private FirebaseUser mCurrentUser;
private String userId = null;
Initialize
mAuth = FirebaseAuth.getInstance();
mCurrentUser = mAuth.getCurrentUser();
userId = mCurrentUser.getUid().toString();
String UIDstring = (String) dataSnapshot.child("users").getValue();
Determine
if (userId.equals(UIDstring)) {
//true
} else {
// false
}