Parse powered by Bitnami for Android (friends list) - java

So I have written an on click method that takes in text from a user (a friend's name) then checks to see if that user exists on the database and if you are already friends with that user. If the user exists and isn't already your friend, I want it to add them to your friends list, which is an array on the Parse backend. The checks seem to be working, and "frank" is added to the list on the device however the list isn't being updated or saved on the server and I can't work out why, I've checked variable and database names for error and I cant find any. I'm testing logged in as "bill". Please find method and screenshot of database below. Any help would be greatly appreciated.
Parse bitnami database here
public void addFriend(View view){
final EditText mText = (EditText)findViewById(R.id.editText);
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("username", mText.getText().toString());
query.countInBackground(new CountCallback() {
#Override
public void done(int count, ParseException e) {
if (e == null) {
if(count==0){
Toast.makeText(getApplicationContext(), "User Doesn't Exist", Toast.LENGTH_LONG).show();
}
else if (ParseUser.getCurrentUser().getList("friendsList").contains(mText.getText().toString()))
{Toast.makeText(getApplicationContext(), "User is already a friend", Toast.LENGTH_LONG).show();}
else
{
ParseUser.getCurrentUser().getList("friendsList").add(mText.getText().toString());
ParseUser.getCurrentUser().saveInBackground();
}
}
}
});
}

I haven't used Parse much myself, but from the API documents here: http://docs.parseplatform.org/android/guide/#arrays
It looks like what is happening is you are using the .add() method from List<>, but it seems you need to use the Parse's specific .add() method on the ParseObject.
Try changing this line:
ParseUser.getCurrentUser().getList("friendsList").add(mText.getText().toString());
to
ParseUser.getCurrentUser().add("friendsList", mText.getText().toString());

Related

How do i create a key with FirebaseDatabase

How can I program a key in my FirebaseDatabase that is created by the userName. wText should then be the text: "" Value.
I try to create a key but when i run my app it removes all values in my database
The Code:
`
// getting text from our edittext fields.
String nameValue = userName.getText().toString();
String textValue = wText.getText().toString();
// below line is for checking whether the
// edittext fields are empty or not.
if (nameValue.isEmpty() && textValue.isEmpty()) {
// if the text fields are empty
// then show the below message.
Toast.makeText(AddTextActivity.this, "Please add some data.", Toast.LENGTH_SHORT).show();
return;
} else {
// else call the method to add
// data to our database.
addDatatoFirebase(nameValue, textValue);
finish();
}
}
});
}
private void addDatatoFirebase(String name, String wText) {
// below 3 lines of code is used to set
// data in our object class.
Messages.setuserName(name);
Messages.setText(wText);
// we are use add value event listener method
// which is called with database reference.
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
// inside the method of on Data change we are setting
// our object class to our database reference.
// data base reference will sends data to firebase.
myRef.setValue(text);
// after adding this data we are showing toast message.
Toast.makeText(AddTextActivity.this, "data added", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
// if the data is not added or it is cancelled then
// we are displaying a failure toast message.
Toast.makeText(AddTextActivity.this, "Fail to add data" + error, Toast.LENGTH_SHORT).show();
}
}); `
It seems you might be using set() function to update data in firebase.
( in your case setValue(), I'm not sure if it is Firebase function or user defined function , Firebase uses set() method in almost in every SDK, not sure about Java SDK for Firebase )
Please note that set() will replace the existing value, or create a new key if there isn't any.
Use update() function instead of set()
Ways to Save Data
set - Write or replace data to a defined path, like messages/users/
update - Update some of the keys for a defined path without replacing all of the data
push - Add to a list of data in the database. Every time you push a new node onto a list, your database generates a unique key, like
messages/users//
transaction - Use transactions when working with complex data that could be corrupted by concurrent updates
refer the docs here

How can I perform OR query while searching in firebase?

Here are the various attributes of a person.
I want to implement a search where the results come if any of the fields: specializationField, hospitalName or fullName have the same letters.
For example if I search 'sh', this person should appear in the field, because of the similar hospital name.
This is the code I am using to search only for fullName:
FirebaseRecyclerOptions<DoctorHelperClass> options =
new FirebaseRecyclerOptions.Builder<DoctorHelperClass>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("Doctor").orderByChild("fullName").startAt(s.toUpperCase()).endAt(s.toLowerCase()+"\uf8ff"), DoctorHelperClass.class)
.build();
adapter = new DoctorsAdapters(options, FindDoctorActivity.this);
adapter.startListening();
binding.rvListDoctors.setAdapter(adapter);
Please help me out
As #Puf said, you can't achieve it at Firebase Realtime Database but you can do it at client side which mean at the Android part.
First, you cannot use FirebaseUI which is you are currently using, instead you need to use https://firebase.google.com/docs/database/android/read-and-write#read_data
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// You have to make for each loop
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
DoctorHelperClass doc = snapshot.getValue(DoctorHelperClass.class);
//List them in an array
docList.add(doc);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
}
};
mPostReference.addValueEventListener(postListener);
Once you have added all the list of doctors. You can compare them using the arrayList.
You can do something like this.
private void searchDoc(final String inputDoc){
boolean isFound = false;
for (DoctorHelperClass doc in docList){
if (doc.getFullName() == inputDoc && doc.getHospitalName() == inputDoc){
isFound = true;
//Do something if found
}
}
}
I hope you get the concept of it.
There is no support for OR conditions in Firebase Realtime Database. You will either have to perform multiple queries and merge the results client-side, or create a specialized field for performing this search.
But given your question, you may be looking for text search capabilities that are well beyond what Firebase Realtime Database handles. Instead of trying to shoehorn those requirements onto Firebase, I recommend using an additional (or even other) database for meeting your text search requirements.
Also see:
Use firebase realtime database create search function
How to search anywhere in string in Firebase Database - Android
Searching in Firebase without server side code
Firebase and indexing/search

How to query an array list in a Firebase document?

I'm trying to query my database for an android application, if a username is in the 'fave' array field of my database and if so then change the background of an image. My database is set up like this...
I don't know if i'm doing it right but currently i think i may be checking the whole collection rather than a specific document and it's not even returning anything. Any suggestions would be appreciated!
You wanted this?
FirebaseFirestore.getInstance().collection("Trainers").document("Air Force 1 Low").get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
List<String> list = (List<String>)documentSnapshot.get("fave");
for (String name : list){
if (name.equals("Admin")){
//do if user is admin
return;
}
}
//do if user is not admin
}
});

Firebase upvote adding id which doesn't exist [duplicate]

This question already has answers here:
How to save users score in firebase and retrieve it in real-time in Android studio
(3 answers)
Closed 4 years ago.
I'm having a problem when I try to star a movie which id doesn't exist in my likes firebase node. Here's my code:
private void onStarClicked(long releaseId, final String uid) {
final DatabaseReference postRef = ((GamePageActivity)getActivity()).mDatabaseRef.child("likes").child(mRegion).child(String.valueOf(releaseId));
postRef.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
_Post p = mutableData.getValue(_Post.class);
if (p == null) {
Log.d(TAG, "Transaction success");
return Transaction.success(mutableData);
}
if (p.stars.containsKey(uid)) {
// Unstar the post and remove self from stars
p.starCount = p.starCount - 1;
p.stars.remove(uid);
} else {
// Star the post and add self to stars
p.starCount = p.starCount + 1;
p.stars.put(uid, true);
}
// Set value and report transaction success
mutableData.setValue(p);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
// Transaction completed
Log.d(TAG, "postTransaction:onComplete:" + databaseError);
}
});
}
The problem is if my id "releaseId" doesn't exist in the database, the star won't get added in, I thought my code was supposed to first add the "releaseId" if it doesn't exist?
It seems a bit complicated to try to add a movie inside your likes path during a ‘like’ transaction. Ideally, it would already be there. So it will be easier to separate adding the movie to the likes path, and after that use a Cloud Function onCreate or onUpdate.
I assume you have your movie data somewhere else in your database. Let’s call it the ‘movies’ path for now. One idea to try is to have a Cloud Function that watches your ‘movies’ path, and when a movie is added, the function will add that movie data to your ‘likes’ path. That way, once a user tries to like a movie, its information is already in the correct spot in the database. Fixing the problem of the non-existent 'releaseId'.
Firebase Realtime Database Triggers
If you don’t want to use a Cloud Function, you can consider writing to both the ‘movies’ path and ‘likes’ path directly from the client when the movie is added, to accomplish the same thing.

Get Related ParseUser From a ParseRelation for Android

I have 2 classes
User
StockProduct
StockProduct has a relation column sold_by for User.
I am trying to retrieve sold_by for the corresponding StockProduct but, it's returning 0 objects for the following code.
/**
* GET SELLER FOR CURRENT PRODUCT
* current_stock_object: ParseObject for StockProduct
*/
ParseRelation getSellerRelation = current_stock_object.getRelation("sold_by");
ParseQuery getSeller = getSellerRelation.getQuery();
getSeller.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> users, ParseException e) {
if (e!=null){
e.printStackTrace();
}
Log.d("SIZE", Integer.toString(users.size()));
}
});
Output:
I successfully retrieve the relation via Parse DataBrowser.
SIDE NOTE
/**
* GET PRICE FOR CURRENT PRODUCT
*/
ParseRelation<ParseObject> getPriceRelation = current_stock_object.getRelation("prices");
ParseQuery getPrice = getPriceRelation.getQuery();
getPrice.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject>prices, ParseException e) {
Log.d("PRICE SIZE", Integer.toString(prices.size()));
System.out.println(prices.get(0).get("costPrice"));
}
});
Works perfectly fine, leaving me with the thought that, getting ParseUser requires a different approach.
Any help would be appreciated.
I would try:
ParseRelation<ParseUser> getSellerRelation = current_stock_object.getRelation("sold_by");
getSellerRelation.getQuery().findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> users, ParseException e) {
if (e!=null){
e.printStackTrace();
}
Log.d("SIZE", Integer.toString(users.size()));
}
});
All I added was an explicit type to the ParseRelation (in this case ParseUser). The documentation uses exactly this syntax, so I'm not sure why this wouldn't work for fetching the Relation.. maybe your "current_stock_object" needs to be fetched, or the "current_stock_object" is not the one you are looking at in the Parse console. Use the debugger and check the fields of your "current_stock_object" and ensure the objectId matches the one you are looking at in the console. Again, the object could be stale may need a fetch
Side note: (unrelated possibly)
Be sure to only use ParseRelation for a many-to-many relationship, otherwise just store the ParseObjects directly as a field. In this case, you have a StockProduct with a relation to _User table. If it makes sense in your application that a StockProduct can have multiple sellers, stick with the ParseRelation. If it was actually intended that a StockProduct may only have one unique seller, switch to not using a ParseRelation

Categories