I'm trying to build a ticket booking app for an event and I managed to do the registration and log-in part. After the login, the user profile shows up which contains some TextViews about the name, age, email, etc. and I want to read the data from the real-time database and put it in TextView.I don't know what is the problem but the TextViews won't show the data.
User profile class
public class ProfilUser extends AppCompatActivity {
private FirebaseUser user;
private DatabaseReference referinta;
private String userID;
private Button delogare;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profil_user);
delogare = (Button) findViewById(R.id.delogare);
delogare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(ProfilUser.this,MainActivity.class));
}
});
user = FirebaseAuth.getInstance().getCurrentUser();;
userID = user.getUid();
referinta = FirebaseDatabase.getInstance("https://rezervarebileteveniment-default-rtdb.europe-west1.firebasedatabase.app").getReference("Users").child(userID);
TextView bunVenitTextView = (TextView) findViewById(R.id.bunVenit);
TextView numeTextView = (TextView) findViewById(R.id.getNume);
TextView prenumeTextView = (TextView) findViewById(R.id.getPrenume);
TextView varstaTextView = (TextView) findViewById(R.id.getVarsta);
TextView emailTextView = (TextView) findViewById(R.id.getAdresaEmail);
referinta.child(userID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User profilUser = snapshot.getValue(User.class);
if(profilUser != null){
String nume = profilUser.nume;
String prenume = profilUser.prenume;
String email = profilUser.email;
String varsta = profilUser.varsta;
bunVenitTextView.setText("Buna ziua, "+nume + " "+prenume +"!");
numeTextView.setText(nume);
prenumeTextView.setText(prenume);
emailTextView.setText(email);
varstaTextView.setText(varsta);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(ProfilUser.this,"Ceva nu a mers bine!", Toast.LENGTH_LONG).show();
}
});
}
}
User class
package oct.alx.rezervarebileteveniment;
public class User {
public String nume, prenume , varsta, email;
public User(){
}
public User(String nume, String prenume, String varsta, String email){
this.nume = nume;
this.prenume = prenume;
this.varsta = varsta;
this.email = email;
}
public String getNume(){
return nume;
}
public void setNume(String nume){
this.nume = nume;
}
public String getPrenume() {
return prenume;
}
public void setPrenume(String prenume) {
this.prenume = prenume;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getVarsta() {
return varsta;
}
public void setVarsta(String varsta) {
this.varsta = varsta;
}
}
The problem in your code lies in the fact that you're calling .child(userID) twice, once when you create the reference:
referinta = FirebaseDatabase.getInstance("https://rezervarebileteveniment-default-rtdb.europe-west1.firebasedatabase.app")
.getReference("Users")
.child(userID); //👈
And second time when you attach the listener:
referinta.child(userID).addListenerForSingleValueEvent(/*... /*);
// 👆
This means that you're trying to read the data from a location that doesn't exist. To solve this, you either remove that method call from the first line of code or from the second one.
P.S. To use encapsulation, try to make all fields in your class private:
private String nume, prenume , varsta, email;
Related
Update
I found the issue within my program, the values are actually being saved as seen within the database inspector
The activity for adding the values never displays the current values which is what I thought they should, from this activity I can only enter new values and save
I have a user object which is already created in a separate activity via recyclerview, I want to then click into each recycler view created and update the users data within that but my update user method is not updating or storing any data at all when I enter the new data in the fields.
I know this is due to my app not being able to identify which user I'm actually trying to update but I'm unsure how to assign the id to my user object and then search for the clicked on user's id within my updateUser method in the UserDetails activity?
See below my user object created within User entity
#Entity
public class User {
#PrimaryKey(autoGenerate = true)
public int uid = 0;
#ColumnInfo(name = "Username")
public String UserName;
#ColumnInfo(name = "Field1")
public String Value1;
#ColumnInfo(name = "Field2")
public String Value2;
#ColumnInfo(name = "Field3")
public String Value3;
#ColumnInfo(name = "Field4")
public String Value4;
#ColumnInfo(name = "Field5")
public String Value5;
#ColumnInfo(name = "Field6")
public String Value6;
#ColumnInfo(name = "Field7")
public String Value7;
#ColumnInfo(name = "Field8")
public String Value8;
#ColumnInfo(name = "Field9")
public String Value9;
#ColumnInfo(name = "Field10")
public String Value10;
public User() { this("", "", "", "", "", "", "", "", "", "", ""); }
public User(String UserName, String value1, String value2, String value3, String value4, String value5, String value6, String value7, String value8, String value9, String value10 ) {
setUserName(UserName);
setValue1(Value1);
setValue1(Value2);
setValue1(Value3);
setValue1(Value4);
setValue1(Value5);
setValue1(Value6);
setValue1(Value7);
setValue1(Value8);
setValue1(Value9);
setValue1(Value10);
}
public int getId() {
return uid;
}
public void setId(int id) {
this.uid = id;
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
// Field 1 value
public String getValue1() {
return Value1;
}
public void setValue1(String value1) {
Value1 = value1;
}
// Field 2 value
public String getValue2() {
return Value2;
}
public void setValue2(String value2) {
Value2 = value2;
}
// Field 3 value
public String getValue3() {
return Value3;
}
public void setValue3(String value3) {
Value3 = value3;
}
// Field 4 value
public String getValue4() {
return Value4;
}
public void setValue4(String value4) {
Value4 = value4;
}
// Field 5 value
public String getValue5() {
return Value5;
}
public void setValue5(String value5) {
Value5 = value5;
}
// Field 6 value
public String getValue6() {
return Value6;
}
public void setValue6(String value6) {
Value6 = value6;
}
// Field 7 value
public String getValue7() {
return Value7;
}
public void setValue7(String value7) {
Value7 = value7;
}
// Field 8 value
public String getValue8() {
return Value8;
}
public void setValue8(String value8) {
Value8 = value8;
}
// Field 9 value
public String getValue9() {
return Value9;
}
public void setValue9(String value9) {
Value9 = value9;
}
// Field 10 value
public String getValue10() {
return Value10;
}
public void setValue10(String value10) {
Value10 = value10;
}
}
See below my UserDao with my methods for inserting and updating a user
#Dao
public interface UserDao {
#Query("SELECT * FROM User")
List<User> getAllUsers();
#Query("SELECT * FROM User WHERE uid =:userID")
User getUser(int userID);
#Insert(onConflict = OnConflictStrategy.REPLACE)
void insertUser(User users);
#Query("UPDATE User SET Field1 =:Value1, Field2 =:Value2, Field3 =:Value3, Field4 =:Value4, Field5 =:Value5, Field6 =:Value6, " +
"Field7 =:Value7, Field8 =:Value8, Field6 =:Value9, Field6 =:Value9, Field10 =:Value10 WHERE uid = uid ")
void updateUser(String Value1, String Value2, String Value3, String Value4, String Value5, String Value6, String Value7,
String Value8, String Value9, String Value10);
#Update
void updateUser(User...users);
#Delete
void delete(User user);
}
See below my addnewuseractivity where a user is initially created
public class AddNewUserActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_new_user);
final EditText firstNameInput = findViewById(R.id.firstNameInput);
/* final EditText txtField1Value = findViewById(R.id.txtField1Value);
final EditText txtField2Value = findViewById(R.id.txtField2Value);
final EditText txtField3Value = findViewById(R.id.txtField3Value);
final EditText txtField4Value = findViewById(R.id.txtField4Value);
final EditText txtField5Value = findViewById(R.id.txtField5Value);
final EditText txtField6Value = findViewById(R.id.txtField6Value);
final EditText txtField7Value = findViewById(R.id.txtField7Value);
final EditText txtField8Value = findViewById(R.id.txtField8Value);
final EditText txtField9Value = findViewById(R.id.txtField9Value);
final EditText txtField10Value = findViewById(R.id.txtField10Value);
*/
Button saveButton = findViewById(R.id.saveButton);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveNewUser(firstNameInput.getText().toString()); /*, txtField1Value.getText().toString(), txtField2Value.getText().toString(),
txtField3Value.getText().toString(), txtField4Value.getText().toString(), txtField5Value.getText().toString(),
txtField6Value.getText().toString(), txtField7Value.getText().toString(), txtField8Value.getText().toString(),
txtField9Value.getText().toString(), txtField10Value.getText().toString());*/
}
});
}
public void saveNewUser(String firstName) {
AppDatabase db = AppDatabase.getDbInstance(this.getApplicationContext());
User user = new User();
user.UserName = firstName;
/*user.Value1 = value1;
user.Value2 = value2;
user.Value3 = value3;
user.Value4 = value4;
user.Value5 = value5;
user.Value6 = value6;
user.Value7 = value7;
user.Value8 = value8;
user.Value9 = value9;
user.Value10 = value10;*/
db.userDao().insertUser(user);
finish();
}
}
See below my userdetails activity where the created user's data is supposed to be updated on press
public class UserDetails extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_details);
final EditText txtField1Value = findViewById(R.id.txtField1Value);
final EditText txtField2Value = findViewById(R.id.txtField2Value);
final EditText txtField3Value = findViewById(R.id.txtField3Value);
final EditText txtField4Value = findViewById(R.id.txtField4Value);
final EditText txtField5Value = findViewById(R.id.txtField5Value);
final EditText txtField6Value = findViewById(R.id.txtField6Value);
final EditText txtField7Value = findViewById(R.id.txtField7Value);
final EditText txtField8Value = findViewById(R.id.txtField8Value);
final EditText txtField9Value = findViewById(R.id.txtField9Value);
final EditText txtField10Value = findViewById(R.id.txtField10Value);
Intent detailIntent = getIntent();
if (detailIntent != null) {
final int userId = detailIntent.getIntExtra("userId", -1);
if (userId != -1) {
Button saveButton = findViewById(R.id.saveButton2);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateUser(userId, txtField1Value.getText().toString(), txtField2Value.getText().toString(),
txtField3Value.getText().toString(), txtField4Value.getText().toString(), txtField5Value.getText().toString(),
txtField6Value.getText().toString(), txtField7Value.getText().toString(), txtField8Value.getText().toString(),
txtField9Value.getText().toString(), txtField10Value.getText().toString());
}
});
}
}
}
/* public User getUser(int userID)
{
return AppDatabase.getDbInstance(this.getApplicationContext()).userDao().getUser(userID);
}*/
public void updateUser( int userId, String value1, String value2, String value3, String value4, String value5, String value6, String value7,
String value8, String value9, String value10) {
AppDatabase db = AppDatabase.getDbInstance(this.getApplicationContext());
User user = db.userDao().getUser(userId);
user.Value1 = value1;
user.Value2 = value2;
user.Value3 = value3;
user.Value4 = value4;
user.Value5 = value5;
user.Value6 = value6;
user.Value7 = value7;
user.Value8 = value8;
user.Value9 = value9;
user.Value10 = value10;
db.userDao().updateUser(user);
finish();
}
}
See below my UserListAdapter and MainActivity for reference
public class UserListAdapter extends RecyclerView.Adapter<UserListAdapter.MyViewHolder> {
private Context context;
private List<User> userList;
private ItemClickListener clickListener;
public UserListAdapter(Context context) {
this.context = context;
}
public void setUserList(List<User> userList) {
this.userList = userList;
notifyDataSetChanged();
}
#NonNull
#Override
public UserListAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.recycler_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull UserListAdapter.MyViewHolder holder, #SuppressLint("RecyclerView") final int position) {
final User user = userList.get(position);
holder.tvFirstName.setText(this.userList.get(position).UserName);
/* holder.tvValue1.setText(this.userList.get(position).Value1);
holder.tvValue2.setText(this.userList.get(position).Value2);
holder.tvValue3.setText(this.userList.get(position).Value3);
holder.tvValue4.setText(this.userList.get(position).Value4);
holder.tvValue5.setText(this.userList.get(position).Value5);
holder.tvValue6.setText(this.userList.get(position).Value6);
holder.tvValue7.setText(this.userList.get(position).Value7);
holder.tvValue8.setText(this.userList.get(position).Value8);
holder.tvValue9.setText(this.userList.get(position).Value9);
holder.tvValue10.setText(this.userList.get(position).Value10);*/
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context , UserDetails.class);
context.startActivity(intent);
}
});
holder.deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AppDatabase.getDbInstance(context).userDao().delete(user);
userList.remove(user);
notifyItemRemoved(position);
}
});
}
#Override
public int getItemCount() {
return this.userList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView tvFirstName;
/* TextView tvValue1;
TextView tvValue2;
TextView tvValue3;
TextView tvValue4;
TextView tvValue5;
TextView tvValue6;
TextView tvValue7;
TextView tvValue8;
TextView tvValue9;
TextView tvValue10;*/
Button deleteBtn;
public MyViewHolder(View view) {
super(view);
tvFirstName = view.findViewById(R.id.tvFirstName);
/* tvValue1 = view.findViewById(R.id.tvField1Value);
tvValue2 = view.findViewById(R.id.tvField2Value);
tvValue3 = view.findViewById(R.id.tvField3Value);
tvValue4 = view.findViewById(R.id.tvField4Value);
tvValue5 = view.findViewById(R.id.tvField5Value);
tvValue6 = view.findViewById(R.id.tvField6Value);
tvValue7 = view.findViewById(R.id.tvField7Value);
tvValue8 = view.findViewById(R.id.tvField8Value);
tvValue9 = view.findViewById(R.id.tvField9Value);
tvValue10 = view.findViewById(R.id.tvField10Value);*/
deleteBtn = view.findViewById(R.id.deleteBtn);
}
}
public void setClickListener(ItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView userName;
public ViewHolder(View itemView) {
super(itemView);
userName = (TextView) itemView.findViewById(R.id.tvFirstName);
itemView.setTag(itemView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (clickListener != null) clickListener.onClick(view, getAdapterPosition());
}
}
}
public class MainActivity extends AppCompatActivity implements ItemClickListener{
private UserListAdapter userListAdapter;
private List<User> users;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button addNewUserButton = findViewById(R.id.addNewUserButton);
addNewUserButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(new Intent(MainActivity.this, AddNewUserActivity.class), 100);
}
});
initRecyclerView();
loadUserList();
}
private void initRecyclerView() {
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
recyclerView.addItemDecoration(dividerItemDecoration);
userListAdapter = new UserListAdapter(this);
recyclerView.setAdapter(userListAdapter);
}
private void loadUserList() {
AppDatabase db = AppDatabase.getDbInstance(this.getApplicationContext());
List<User> userList =db.userDao().getAllUsers();
userListAdapter.setUserList(userList);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode == 100) {
loadUserList();
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onClick(View view, int position) {
final User user = users.get(position);
}
}
When creating the User, Room auto-generates the primary key for you - uid.
When trying to update the User, it is you, who need to provide the uid.
public void updateUser(int usertID, String value1...value10) {
AppDatabase db = AppDatabase.getDbInstance(this.getApplicationContext());
User user = new User();
user.uid = userUID // <------------
user.Value1 = value1;
...
user.Value10 = value10;
db.userDao().updateUser(user);
finish();
}
I think you are missing passing the user ID to the detail activity as well.
UserListAdapter
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context , UserDetails.class);
intent.putExtra("userId", user.uid)
context.startActivity(intent);
}
});
UserDetails activity
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_details);
final EditText txtField1Value = findViewById(R.id.txtField1Value);
...
final EditText txtField10Value = findViewById(R.id.txtField10Value);
Intent detailIntent = getIntent();
if (detailIntent != null) {
int userId = detailIntent.getIntExtra("userId", -1);
if (userId != -1) {
Button saveButton = findViewById(R.id.saveButton2);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateUser(
userId
txtField1Value.getText().toString(),
...
txtField10Value.getText().toString());
}
});
}
}
}
In my Android app, I have a database repository to contact Firebase Realtime Database and a service layer with some methods. My SaveUserProfile method works but I keep getting a null pointer on my GetUserFromUid.
The 'user' object it returns is null and I don't know why. The node in my DB is called "users" (all lowercase) and I want to retrieve a user as a model via their userId and display the name and email onscreen.
Can anybody see where I'm going wrong?
My DbContext:
public class DbContext implements IDbContext {
User user = null;
Context context;
DatabaseReference databaseUsers = FirebaseDatabase.getInstance().getReference("users");
public DbContext(Context context){
super();
this.context = context;
}
#Override
public void AddUserAccount(User user1) {
databaseUsers.child(user1.userId).setValue(user1);
}
#Override
public User GetUserFromFirebase(String uid) {
databaseUsers.child(uid)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
user = dataSnapshot.getValue(User.class);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return user;
}
My DbService:
public class DbService implements IDbService {
//instance of DbContext for firebase handling
private DbContext dbContext;
public DbService(Context context){
super();
dbContext = new DbContext(context);
}
#Override
public User SaveUserProfile(User u) {
dbContext.AddUserAccount(u);
return u;
}
#Override
public User GetUserFromUid(String uid) {
User user = dbContext.GetUserFromFirebase(uid);
return user;
}
My User model:
public class User {
public String userId;
public String name;
public String email;
public String account;
//constructor required for calls to DataSnapshot.getValue(User.class)
public User(){
}
public User(String userId, String name, String email, String account) {
this.userId = userId;
this.name = name;
this.email = email;
this.account = account;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
My activity where I want to display the users' details:
public class DetailsActivity extends AppCompatActivity {
//tag
private static final String TAG = DetailsActivity.class.getSimpleName();
//firebase auth
private FirebaseAuth mAuth;
//variables
private TextView inputName, inputEmail;
private DatabaseReference mFirebaseDatabase;
private String userId;
public String currentUserAccount;
public String teacherAccountNav = "Teacher";
public User userDetails;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
inputName = findViewById(R.id.nameTextView);
inputEmail = findViewById(R.id.emailTextView);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
assert user != null;
userId = user.getUid();
getUserDetails(userId);
inputName.setText(userDetails.name);
inputEmail.setText(userDetails.email);
}
public User getUserDetails(String uid){
DbService dbService = new DbService(this);
userDetails = dbService.GetUserFromUid(uid);
return userDetails;
}
EDITS BELOW
My callback:
public interface Callback {
void myResponseCallback(User user);
}
My EDITED DbContext:
public class DbContext implements IDbContext {
User user = null;
Context context;
DatabaseReference databaseUsers = FirebaseDatabase.getInstance().getReference("users");
public DbContext(Context context) {
this.context = context;
}
#Override
public void AddUserAccount(User user1) {
databaseUsers.child(user1.userId).setValue(user1);
}
#Override
public void GetUserFromFirebase(String uid, final Callback callback) {
databaseUsers.child(uid)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
user = dataSnapshot.getValue(User.class);
callback.myResponseCallback(user);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
My EDITED DbService:
public class DbService implements IDbService {
//instance of DbContext for firebase handling
public DbContext dbContext;
public DbService(Context context){
super();
dbContext = new DbContext(context);
}
#Override
public User SaveUserProfile(User u) {
dbContext.AddUserAccount(u);
return u;
}
#Override
public User GetUserFromUid(String uid) {
final User[] user1 = {new User()};
dbContext.GetUserFromFirebase(uid, new Callback() {
#Override
public void myResponseCallback(User user) {
user1[0] = user;
}
});
return user1[0];
}
My EDITED Activity:
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
inputName = findViewById(R.id.nameTextView);
inputEmail = findViewById(R.id.emailTextView);
FirebaseDatabase mFirebaseInstance = FirebaseDatabase.getInstance();
//reference to 'users' node
mFirebaseDatabase = mFirebaseInstance.getReference("users");
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
assert user != null;
userId = user.getUid();
getUserFromFirebase(userId);
}
public void getUserFromFirebase(String uid){
userDetails = (new DbService(this)).GetUserFromUid(uid);
inputEmail.setText(userDetails.email);
inputName.setText(userDetails.name);
}
Debug BEFORE edits:
Debug AFTER edits:
As you can see from the debug, before the callback interface, userDetails was null. After the interface implementation, userDetails is not null but all of the object values are null. I don't know why this is as they are filled in the database. Any ideas?
I have checked the other questions. None of them solves my problem. I want to retrieve data from the Firebase Realtime Database's node "orderDetails" and show them in the RecyclerView
UserActivity.java
private DatabaseReference databaseReference;
RecyclerView ordersList;
FirebaseAuth firebaseAuth;
FirebaseUser firebaseUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
firebaseAuth = FirebaseAuth.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
String pickerUID = FirebaseAuth.getInstance().getCurrentUser().getUid();
try {
DatabaseReference mDatabaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference = mDatabaseReference.child("Pickers").child(pickerUID).child("orderDetails");
databaseReference.keepSynced(true);
ordersList = findViewById(R.id.recycler);
ordersList.setHasFixedSize(false);
ordersList.setLayoutManager(new LinearLayoutManager(this));
} catch (Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Orders,OrdersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Orders, OrdersViewHolder>
(Orders.class, R.layout.orders_list, OrdersViewHolder.class, databaseReference) {
#Override
protected void populateViewHolder(OrdersViewHolder ordersViewHolder, Orders orders, int i) {
try {
ordersViewHolder.setUserName(orders.getUserName());
ordersViewHolder.setUserAddress(orders.getUserAddress());
ordersViewHolder.setUserEmail(orders.getUserEmail());
ordersViewHolder.setDate(orders.getDate());
ordersViewHolder.setTime(orders.getTime());
ordersViewHolder.setUserUID(orders.getUserUID());
ordersViewHolder.setUserPhoneNumber(orders.getPhoneNumber());
} catch (Exception e) {
Toast.makeText(UserActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
};
ordersList.setAdapter(firebaseRecyclerAdapter);
}
public static class OrdersViewHolder extends RecyclerView.ViewHolder {
View view;
public TextView userUIDTV;
public OrdersViewHolder(View itemView) {
super(itemView);
view=itemView;
}
public void setUserName(String userName) {
TextView name = view.findViewById(R.id.userName);
name.setText(userName);
}
public void setUserAddress(String userAddress) {
TextView address = view.findViewById(R.id.userAddress);
address.setText(userAddress);
}
public void setUserEmail(String userEmail) {
TextView email = view.findViewById(R.id.userEmail);
email.setText(userEmail);
}
public void setDate(String date) {
TextView userDate = view.findViewById(R.id.date);
userDate.setText(date);
}
public void setTime(String time) {
TextView userTime = view.findViewById(R.id.time);
userTime.setText(time);
}
public void setUserUID(String userUID) {
userUIDTV = view.findViewById(R.id.userUID);
userUIDTV.setText(userUID);
}
public void setUserPhoneNumber(String userPhoneNumber) {
TextView phoneNumber = view.findViewById(R.id.userPhoneNumber);
phoneNumber.setText(userPhoneNumber);
}
}
}
Orders.java
public class Orders {
private String userName;
private String userAddress;
private String userEmail;
private String date;
private String time;
private String userUID;
private String phoneNumber;
public Orders(String userName, String userAddress, String userEmail, String date, String time, String phoneNumber, String userUID) {
this.userName = userName;
this.userAddress = userAddress;
this.userEmail = userEmail;
this.date = date;
this.time = time;
this.phoneNumber = phoneNumber;
this.userUID = userUID;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserAddress() {
return userAddress;
}
public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setUserPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getUserUID() {
return userUID;
}
public void setUserUID(String userUID) {
this.userUID = userUID;
}
public Orders() {
}
}
My Database
https://ibb.co/DCHfBDt
I want to get the data from the node "orderDetails"
How can I do it?
Change your database structure and add a random id under orderDetails:
orderDetails
randomId
date : date_value
phoneNumber : phoneNo_value
Now, when you do:
databaseReference = mDatabaseReference.child("Pickers").child(pickerUID).child("orderDetails");
it will retrieve the data of type Orders
I struggle to get data from Firebase for Android.
Please see my code.
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
Logger.log("onChildAdded:" + previousChildName);
// Logger.log( dataSnapshot.child("topicid").getValue(String.class));
//dataSnapshot.child("topicid").getValue();
mComment = new ArticleComment();
mComment = dataSnapshot.getValue(ArticleComment.class);
}
Here is ArticleComment class
public class ArticleComment {
private Date mCommentTime;
private String mComment;
private String mUID;
private String mName;
private int mColorRed;
private int mColorGreen;
private int mColorBlue;
public ArticleComment(){
}
public ArticleComment(Date time, String comment,String name,String uid,int[] color){
this.mCommentTime = time;
this.mComment = comment;
this.mName = name;
this.mUID = uid;
this.mColorRed=color[0];
this.mColorGreen=color[1];
this.mColorBlue=color[2];
}
public Date getTime(){
return mCommentTime;
}
public void setTime(Date time){
mCommentTime =time;
}
public String getComment(){
return mComment;
}
public void setComment(String comment){
mComment =comment;
}
public String getName(){
return mName;
}
public void setName(String name){
mName=name;
}
public String getUID(){
return mUID;
}
public void setUID(String uid){
mUID=uid;
}
public int getColorRed(){
return mColorRed;
}
public int getColorGreen(){
return mColorGreen;
}
public int getColorBlue(){
return mColorBlue;
}
public void setColor(int red,int green, int blue)
{
mColorRed=red;
mColorGreen=green;
mColorBlue=blue;
}
#Exclude
public Map<String, Object> toMap(){
HashMap<String, Object> hashmap = new HashMap<>();
hashmap.put("time", mCommentTime);
hashmap.put("UID", mUID);
hashmap.put("name", mName);
hashmap.put("comment", mComment);
hashmap.put("colorRed", mColorRed);
hashmap.put("colorBlue", mColorBlue);
hashmap.put("colorGreen", mColorGreen);
return hashmap;
}
}
And here is my DB information.
I could get only
mCommentTime;
mComment;
mName;
But I can't get
mUID;
mColorRed;
mColorGreen;
mColorBlue;
Is there something wrong with my code?
Actually datasnapshot has data but it didn't copy to mComment
Hi! Thank you, friends, gave me feedback here is all code.
public class CommentsActivity extends AppCompatActivity {
private DatabaseReference myRef;
private DatabaseReference mTopicRef;
private RecyclerView mRecyclerView;
private RecyclerArticleAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private List<ArticleComment> myDataset = new ArrayList<ArticleComment>();
private ArticleComment mComment;
private Topic mTopic;
private EditText mTitleEditText;
private String mUserName;
private String mUid;
private int mRedColor=100;
private int mBlueColor=100;
private int mGreenolor=100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comments);
//Add action button
Intent intent =getIntent();
String id = intent.getStringExtra("ID");
String date = intent.getStringExtra("Date");
String title = intent.getStringExtra("Title");
String topic = intent.getStringExtra("Topic");
mUserName = intent.getStringExtra("UserName");
mUid = intent.getStringExtra("UID");
SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(this);
mRedColor= pref.getInt("ColorRed",255);
mGreenolor=pref.getInt("ColorGreen",255);
mBlueColor=pref.getInt("ColorBlue",255);
mRecyclerView = findViewById(R.id.recyclerView_article);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
//Reference DB
FirebaseDatabase database = FirebaseDatabase.getInstance();
myRef = database.getReference("Main").child("Comments").child(id);
mTopicRef = database.getReference("Main").child("Topics").child(id);
List<String> topicinfo=new ArrayList<String >();
topicinfo.add(date);
topicinfo.add(title);
topicinfo.add(topic);
// Set TestAdapter as the adapter for RecyclerView.
mRecyclerView.setAdapter(mAdapter);
mAdapter = new RecyclerArticleAdapter(myDataset,topicinfo){
/* #Override
protected void onCheckedChangedRecycle(CompoundButton comButton, final boolean isChecked){
mTopicRef.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
Topic t = mutableData.getValue(Topic.class);
String id = mutableData.child("topicid").getValue(String.class);
t.setTopicID(id);
if (t == null) {
return Transaction.success(mutableData);
}
if (isChecked==true) {
// Unstar the post and remove self from stars
t.setRate(t.getRate()+1);
} else {
// Star the post and add self to stars
t.setRate(t.getRate()-1);
}
// Set value and report transaction success
mutableData.setValue(t);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
// Transaction completed
}
});
} */
};
mRecyclerView.setAdapter(mAdapter);
findViewById(R.id.button2).setOnClickListener(button1ClickListener);
mTitleEditText = findViewById(R.id.editText2);
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
mComment = new ArticleComment();
mComment = dataSnapshot.getValue(ArticleComment.class);
Logger.log("onChildAdded:addItem" + previousChildName);
mAdapter.addItem(mAdapter.getItemCount()-1, mComment);
Logger.log("onChildAdded:scrollToPosition" + previousChildName);
mAdapter.updateItem(mAdapter.getItemCount()-1,mComment);
mLayoutManager.scrollToPosition(mAdapter.getItemCount()-1);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
myRef.addChildEventListener(childEventListener);
}
View.OnClickListener button1ClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// finish();
Logger.log("onClick");
if(mTitleEditText.getText().toString().equals("")){
return;
}
//setting color
int color[]=new int[3];
color[0]= mRedColor;
color[1]=mGreenolor;
color[2]=mBlueColor;
mComment = new ArticleComment(new Date(),mTitleEditText.getText().toString(),mUserName,mUid,color);
sendTopic(mComment,myRef);
//Delete all text
mTitleEditText.setText("");
}
};
// Sending topic to DB
public void sendTopic(ArticleComment test,DatabaseReference ref) {
String key = ref.push().getKey();
Map<String, Object> map = new HashMap<>();
map.put(key, test.toMap());
ref.updateChildren(map);
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
finish();
return true;
}
return true;
}
Is it enough information?
Firebase follows JavaBean naming conventions to determine the name of the JSON property from the Java code. And in that convention getUID and setUID map to a property uID with a lowercase u.
To make the Firebase client adopt your naming convention, annotate the getter and setter with a #PropertyName:
#PropertyName("UID")
public String getUID(){
return mUID;
}
#PropertyName("UID")
public void setUID(String uid){
mUID=uid;
}
I'm not immediately sure why the other properties don't work. When this happens, I find it most useful to write an object of the type of Firebase, to see what it generates.
**
If you want to store values in a model .Then your variable name should
be same as Firebase node or else you need to typeConvert it .
**
private Date mCommentTime;
private String mComment;
private String mUID;
private String mName;
private int mColorRed;
private int mColorGreen;
private int mColorBlue;
Replace above with
private int time;
private String comment;
private String UID;
private String name;
private int colorRed;
private int colorBlue;
private int colorGreen;
now make getters,setters,constructor etc. using above nodes. (Now you will be able to get all the values ) .
Hope its gonna help you :)
I am unable to change the text of multiple TextView to the values retrieved from Firebase Realtime Database.
My database looks like: Database
My current code is:
public class SearchResult extends AppCompatActivity {
TextView searchResultHSPName,searchResultHSPStatus, searchResultHSPType,searchResultHSPRating;
Button messageButton;
private static final String TAG = "SearchResult";
DatabaseReference rootReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result);
searchResultHSPName = (TextView) findViewById(R.id.hspNameSearchResultTextView);
searchResultHSPType = (TextView) findViewById(R.id.hspTypeSearchResultTextView);
searchResultHSPRating = (TextView) findViewById(R.id.hspRatingSearchResultTextView);
searchResultHSPStatus = (TextView) findViewById(R.id.hspStatusSearchResultTextView);
//take the searched name from searchFunction and query db for the user details
Intent intent = getIntent();
final String searchedHSPName = intent.getExtras().getString("SearchFunctionMessage");
rootReference = FirebaseDatabase.getInstance().getReference();
DatabaseReference userReference = rootReference.child("HSPUsers");
userReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
HSPUsers user = snapshot.getValue(HSPUsers.class);
String userName = user.HSPName;
if(userName == searchedHSPName){
searchResultHSPName.setText(userName);
searchResultHSPStatus.setText(user.HSPStatus);
searchResultHSPRating.setText(user.HSPRating);
searchResultHSPType.setText(user.HSPType);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
And my HSPUsers class is:
public class HSPUsers {
//HSP user contains 4 fields of data UserName, Status,Type,Rating
public String HSPName,HSPStatus, HSPType,HSPRating;
//constructor for datasnapshot
public HSPUsers(){
}
public HSPUsers(String username, String status, String type, String rating){
this.HSPName=username;
this.HSPStatus=status;
this.HSPType=type;
this.HSPRating=rating;
}
//get and set methods
public String getHSPUserName() {
return HSPName;
}
public void setHSPUserName(String HSPUserName) {
this.HSPName = HSPUserName;
}
public String getHSPUserStatus() {
return HSPStatus;
}
public void setHSPUserStatus(String HSPUserStatus) {
this.HSPStatus = HSPUserStatus;
}
public String getHSPUserType() {
return HSPType;
}
public void setHSPUserType(String HSPUserType) {
this.HSPType = HSPUserType;
}
public String getHSPUserRating() {
return HSPRating;
}
}
public String getHSPUserRating() {
return HSPRating;
}
}
Ideally, i would like to change the textViews to the user's Name/Status/Rating/Type. However, there has been no change to the textviews and i am left with UnchangedTextViews
Would appreciate any advice on how to change the TextViews to the HSPName/rating/Status/type?
Thank you in advance for any advice.