How to get user data Firebase - java

I'm new to Android development. I need to put and get information through Firebase. I managed to make the assignment of information, but I can not make getting information from the database.
test_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String user_id = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id);
String testData = edit_data_FB.getText().toString();
Map newPost = new HashMap();
newPost.put("testData",testData);
current_user_db.setValue(newPost);
}
});
test_get.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String user_id = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id).child("testData").val;
//Map newPost = new HashMap();
//String data = newPost.get();
//text_get.setText();
}
});
Mission database has the following form
Firebase Database I need to get the testData value

To retrieve testData try the following:
String user_id = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id);
current_user_db.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String testData = dataSnapshot.child("testData").getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Attach a listener to your reference and then you will be able to retrieve testData

Related

How to add data in pre-existing document by searching for specific node in Firebase? (Android)

There is one document which is student profile with student data like course, username, status etc.
I want to add another node named uid in pre-existing document by searching for emailid
For example, In document containing emailid: "abc#gmail.com" I want to add uid:"111032" in that document containing emailid.
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
final DatabaseReference studentRef = rootRef.child("STUDENT");
lg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
username = un.getText().toString().trim();
String password= pw.getText().toString().trim();
lg.setText("Logging in...");
firebaseAuth.signInWithEmailAndPassword(username, password)
.addOnCompleteListener(Welcome.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
firebaseAuth = FirebaseAuth.getInstance();
final String current_user_id = firebaseAuth.getCurrentUser().getUid();
//Save UID to database
Query emailAddressQuery = studentRef.orderByChild("emailid").equalTo(username).limitToFirst(1);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Map<String, Object> uidUpdate = new HashMap<String, Object>();
uidUpdate.put("uid", current_user_id);
ds.getRef().updateChildren(uidUpdate);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
emailAddressQuery.addListenerForSingleValueEvent(valueEventListener);
Intent i=new Intent(Welcome.this,Home.class);
// i.putExtra("useremail", username);
startActivity(i);
lg.setText("Log In");
} else {
Toast.makeText(getApplicationContext(), "Log In Failed", Toast.LENGTH_SHORT).show();
lg.setText("Log in");
}
// ...
}
});
}
});
The above code is actually is in sign in button which sign in the user get the uid and save it to that specific profile's info.this is the image with more detailed information.
As shown in this image, I want to search by emailid (Shown in yellow) and add node called uid in that specific document.
OLD CODE :
username = un.getText().toString().trim();
firebaseAuth = FirebaseAuth.getInstance();
String current_user_id = firebaseAuth.getCurrentUser().getUid();
ref= FirebaseDatabase.getInstance().getReference().child("STUDENT").child(username);
Map<String, Object> updates = new HashMap<String, Object>();
updates.put("uid", current_user_id);
ref.updateChildren(updates);
This code works but we have to pass the name of document while I want to pass data by child node in the document.
To solve this problem, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference studentRef = rootRef.child("STUDENT");
Query emailAddressQuery = studentRef.orderByChild("emailid").equalTo("abc#gmail.com").limitToFirst(1);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Map<String, Object> uidUpdate = new HashMap<String, Object>();
uidUpdate.put("uid", uid);
ds.getRef().updateChildren(uidUpdate).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d("TAG", "task is successful!");
} else {
Log.d("TAG", task.getException().getMessage());
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
emailAddressQuery.addListenerForSingleValueEvent(valueEventListener);
The result of this operation will be the update of the uid in the user object.

Edit specific values in Firebase database using Android Studio

I want to create an "edit user profile" page on Android Studio. The user(which is logged in obviously) can go in and edit user info such as weight and age. Here is how my firebase database is set up:
The database
In this case, a user who is logged in as "Raxor2k", wants to change he`s info such as Age and Weight.
I have made a function that queries the database, and it manages to reach the "AdditionalUserInfo" table which is good. But the next task is to reach those specific values that belong to the logged-in user.
here is the code:
public class UserSettingsActivity extends AppCompatActivity {
private Button mEditInfoButton;
private TextView usernameField;
private EditText ageField, weightField;
private DatabaseReference dbUsernames;
DatabaseReference the_additional_userInfo_table = FirebaseDatabase.getInstance().getReference("AdditionalUserInfo");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_settings);
ageField = (EditText) findViewById(R.id.ageID);
weightField = (EditText) findViewById(R.id.weightID);
mEditInfoButton = (Button) findViewById(R.id.editButton);
usernameField = (TextView) findViewById(R.id.usernameTextViewID);
mEditInfoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
QueryUserInfo();
}
});
}
public void QueryUserInfo(){
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference the_additional_userInfo_table = database.getReference("AdditionalUserInfo");
//Query query =the_additional_userInfo_table.child("username");
the_additional_userInfo_table.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Toast.makeText(UserSettingsActivity.this, "User exists!", Toast.LENGTH_SHORT).show();
// dataSnapshot is the "issue" node with all children with id 0
for (DataSnapshot issue : dataSnapshot.getChildren()) {
// do something with the individual "issues"
}
if(!dataSnapshot.exists()){
Toast.makeText(UserSettingsActivity.this, "nooooo user!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
To get the data under AdditionalUserInfo that corresponds to a specific user, you need to use a query that looks like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference additionalUserInfoRef = rootRef.child("AdditionalUserInfo");
Query userQuery = additionalUserInfoRef.orderByChild("username").equalTo("Raxor2k");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Map<String, Object> map = new HashMap<>();
map.put("user-age", "30");
map.put("user-weight", "30");
ds.getRef().updateChildren(map);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
userQuery.addListenerForSingleValueEvent(valueEventListener);
The result in your database will be the change of both properties from 25 to 30. Since you didn't add the database as a text, file I have used in the query he user name but a more elegant way of querying the database would be to use the uid.
Query userQuery = additionalUserInfoRef.orderByChild("user-id").equalTo("IXL ... Eoj");

Firebase - Unable to read data on application interface - Android Studio

I am developing a task management application on Android Studio with Firebase. I have created a class to add data to the database but I have tried multiple approaches to integrate and read the data on the application with no progress.
Main Activity.java
database = FirebaseDatabase.getInstance();
ref = database.getReference().child("Task List");
final ArrayList<String> mTaskName = new ArrayList<>();
taskListView = (ListView) findViewById(R.id.taskListView);
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.task_info, mTaskName);
taskListView.setAdapter(arrayAdapter);
ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
String value = dataSnapshot.getValue(String.class);
mTaskName.add(value);
arrayAdapter.notifyDataSetChanged();
}
add_task.java
mDatabase = FirebaseDatabase.getInstance().getReference().child("Task List"); // Reference database
addTaskbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String taskName = newTask.getText().toString().trim();
String date = dateField.getText().toString().trim();
String assignee = spinnerAssign.getSelectedItem().toString();
String descrip = description.getText().toString();
if (!TextUtils.isEmpty(taskName) && !TextUtils.isEmpty(date)) {
HashMap<String, String> taskData = new HashMap<>();
taskData.put("Name", taskName);
taskData.put("Date", date);
taskData.put("Assigned to", assignee);
taskData.put("Description", descrip);
mDatabase.push().setValue(taskData).addOnCompleteListener(new OnCompleteListener<Void>() {
The database is structured like this:
task-list-for-managers
-Task List
-PushID
-Assigned to: "Name"
-Date: "Date"
-Description: "Description"
-Name: "Task Name"
ValueEventListener eventListener = new ValueEventListener() {
//Searching the database and adding each to list
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
//adding the key to an arraylist to be referenced when deleting records or passing intents from specific button
mTaskName.add(ds.getKey());
String name = ds.child("Name").getValue(String.class);
String date = ds.child("Date").getValue(String.class);
id.add(name + "\n" + date);
Log.d("TAG", name);
}
taskListView.setAdapter(arrayAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
database.addListenerForSingleValueEvent(eventListener);

Get specific value from Firebase

I have this firebase database:
That has been created with this code:
private DatabaseReference mDatabase;
private EditText tbfirstname;
private EditText tblastname;
private EditText tbemail;
private Button btnSubmit;
private String str_firstname;
private String str_lastname;
private String str_email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
//GUI DECLARATIONS
tbfirstname = (EditText) findViewById(R.id.tb_firstname);
tblastname = (EditText) findViewById(R.id.tb_lastname);
tbemail = (EditText) findViewById(R.id.tb_email);
btnSubmit = (Button) findViewById(R.id.btn_register);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//HANDLES VALUES FROM TB TO STR
str_firstname = tbfirstname.getText().toString().trim();
str_lastname = tblastname.getText().toString().trim();
str_email = tbemail.getText().toString().trim();
HashMap<String, String> dataMap = new HashMap<String, String>();
dataMap.put("Firstname", str_firstname);
dataMap.put("Lastname", str_lastname);
dataMap.put("Email", str_email);
mDatabase.push().setValue(dataMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(MainActivity.this,"Registered Successfully!",Toast.LENGTH_LONG).show();
tbfirstname.setText("");
tblastname.setText("");
tbemail.setText("");
} else {
Toast.makeText(MainActivity.this, "There was an Error. Try Again!", Toast.LENGTH_LONG).show();
}
}
});
}
});
}
It's actually a simple app that let users register some data. What I wanna do is I want to create a search textboxthat will locate specific data in the database based on what the user has entered in that textbox and returns a value.
For example I'll search steve#sample.com, if there is an email in the database that has the same value, I want it to return its root value namely L4JyRA77YKldmMWM-C7. If somehow there is no said record, I want it to return with false or something.
Requirements:I'm really a beginner in Android and Firebase so if you could make the code newbie-friendly, that'll really be a great help. Thanks!
first of all you need to fetch all records from firebase database List<User>
create copy of list List<User> temp = new ArrayList();
you can add particular searchable user detail in temp - temp.add(users.get(i));
Now you can get useremail like this email = temp.get(i).getEmailId();
FirebaseDatabase.getInstance().getReference().child("Your table name").orderByChild("email").equalTo(your searchable emailid ).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator<DataSnapshot> dataSnapshots = dataSnapshot.getChildren().iterator();
List<User> users = new ArrayList<>();
while (dataSnapshots.hasNext()) {
DataSnapshot dataSnapshotChild = dataSnapshots.next();
User user = dataSnapshotChild.getValue(User.class);
users.add(user);
}
String userids = "";
List<User> temp = new ArrayList();
try {
for (int i = 0; i < users.size(); i++) {
if (users.get(i).getEmailid().equals("your searchable email")) {
temp.add(users.get(i));
//Here you can find your searchable user
Log.e("temp", "+" + temp.get(i).getFirebaseId());
email = temp.get(i).getEmailId();
}
}
} catch (Exception e) {
e.printStackTrace();
Log.e("Logs", e.toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("Users").orderByChild("Email").equalTo("editext.getText()");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// dataSnapshot is the "issue" node with all children with id 0
for (DataSnapshot issue : dataSnapshot.getChildren()) {
// do something with the individual "issues"
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Some general things to remember is never name nodes with Capital letters

How to update firebase database values

I have tried too many times but not works this code .How to update specific fields in Firebase database which is mentioned in structure
Here is my structure:
Blog
-LOkCTZQtuMIPT_c9ESK
desc: "wow"
id: "-LOkCTZQtuMIPT_c9ESK"
image:"firebase image"
title:"gh"
uid:"6757576gfgHh6"
So how i can update the desc,image,title these particular fields only with the help of id
Here is my code:
mCurrentUser = mAuth.getCurrentUser();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
mDatabaseUser = FirebaseDatabase.getInstance().getReference().child("users").child(mCurrentUser.getUid());
private void startPosting() {
mProgress.setMessage("Posting...");
final String title_val = mPostTitle.getText().toString().trim();
final String desc_val = mNameFieldUpdate.getText().toString().trim();
if (!TextUtils.isEmpty(title_val) && !TextUtils.isEmpty(desc_val) && mImageUri != null) {
mProgress.show();
final StorageReference filepath = mStorage.child("Blog_Images").child(mImageUri.getLastPathSegment());
filepath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
#SuppressWarnings("VisibleForTests")
final Uri downloadUri = taskSnapshot.getDownloadUrl();
final String id = mDatabase.getKey();
mDatabaseUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mDatabase.child(id).child("title").setValue(title_val);
mDatabase.child(id).child("desc").setValue(desc_val);
mDatabase.child(id).child("image").setValue(downloadUri.toString());
mProgress.dismiss();
Intent mainIntent = new Intent(Update_Post.this, Main2Activity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mainIntent);
finish();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Do this:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Blog");
ref.addListenerForSingleValueEvent(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot){
for(DataSnapshot data: dataSnapshot.getChildren()){
String uid=data.child("uid").getValue().toString();
if(uid.equals((mCurrentUser.getUid()){
String keyid=data.getKey();
ref.child(keyid).child("title").setValue(newtitle);
ref.child(keyid).child("image").setValue(newurl);
ref.child(keyid).child("desc").setValue(newdesc);
}
}
}
Have the location of the listener at child("Blog") and then iterate inside of it and get the key which is keyid. Then to update the values simple point it to the right location and update each one.
You're using getKey() on your base blog DB reference (/Blog). You need to create a new node within that reference with push(), and then getKey() on your newly created child.
final String id = mDatabase.push().getKey();

Categories

Resources