The application I'm developing is really similar to Instagram.
On Instagram, users can change their usernames anytime. And if you change your username, your posts also show the updated username.
How can I implement this on a firebase database environment?
For example, I have VO below.
#IgnoreExtraProperties
public class Post {
String uid;
String username;
String content;
int likesCount = 0;
Map<String, Boolean> likes = new HashMap<>();
Map<String, Boolean> hashtags = new HashMap<>();
public Post() {
// Default constructor required for calls to DataSnapshot.getValue(Post.class)
}
public Post(String uid, String username, String content) {
this.uid = uid;
this.username = username;
this.content = content;
}
#Exclude
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("uid", uid);
result.put("username", username);
result.put("content", content);
result.put("likesCount", likesCount);
result.put("likes", likes);
result.put("hashtags", hashtags);
return result;
}
}
If I include "username" in the Post Object, I can show each post with the usernames synchronously, but it will be difficult to show the latest updated "username" all the time.
If one user's Posts are over 1000, should I update all the posts at the same time when the username is changed?
If I exclude "username" in Post object I can load updated "username" asynchronously each time after any Post is loaded.
Or at the first time just show old username, and check if it is changed everytime when the Post is loaded, and update it asynchronously.
Which is the most efficient and proper way to implement for it?
Related
I am using this method to store data in my firebase database:
First i store all the data in a Model Class, called SubjectDataModel,
then i get the push key from the firebase database.
and then i set value to that particular key.
Here is my code :
SubjectDataModel:
public class SubjectDataModel {
public String id;
public String dbName;
public String subName;
public String tagline;
public int preference;
public SubjectDataModel()
{
}
public SubjectDataModel(String id, String dbName, String subName, String tagline, int preference) {
this.id = id;
this.dbName = dbName;
this.subName = subName;
this.tagline = tagline;
this.preference = preference;
}
}
Then i use the following code to push it to the database and then i also store the key id locally.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Data");
String id = ref.push().getKey();
SubjectDataModel newSub = new SubjectDataModel(id, txt_dbName, txt_subName, txt_tagline, txt_preference);
ref.child(id).setValue(newSub);
Now imagine, later in time, i want to update this data,
so i have the key id stored, so i can access it, i also have edited all the other data locally, so now if i make a SubjectDataModel Object with that data and again do ref.child(id).setValue(newSub); with the stored id, will the data be updated ? Or is there any other method to do so ?
updateChildren() is the method you are looking for, refer this documentation Firebase Read and Write Data on Android
Here's an example from documentation...
private void writeNewPost(String userId, String username, String title, String body) {
// Create new post at /user-posts/$userid/$postid and at
// /posts/$postid simultaneously
String key = mDatabase.child("posts").push().getKey();
Post post = new Post(userId, username, title, body);
Map<String, Object> postValues = post.toMap();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/posts/" + key, postValues);
childUpdates.put("/user-posts/" + userId + "/" + key, postValues);
mDatabase.updateChildren(childUpdates);
}
Okay, so i tried this and it works perfectly, like i expected it to. No need for me to use maps or anything. Simplest way to update data.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Data");
SubjectDataModel newSub = new SubjectDataModel(idForUpdate, txt_dbName, txt_subName, txt_tagline, txt_preference);
ref.child(idForUpdate).setValue(newSub);
So here basically, i created the object with the required data, and pushed it back to the same id with which i created a node in the firebase database, so it updates that same node with the new values.
This is my code and I am uploading a student name and batch name to firebase database. This method is excecuted after user created the account successfully.
User is created in Authentication but data is not uploaded to database and the only error in logcat is:
E/SpellCheckerSession: ignoring processOrEnqueueTask due to unexpected mState=TASK_CLOSE scp.mWhat=TASK_CLOSE
private void uploadUserDetails(){
String name = studentName.getText().toString();
String batch = "BCA";
database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference(firebaseAuth.getUid());
Student student = new Student(name,batch);
ref.child("Student Details").setValue(student);
}
public class Student {
public String name;
public String batch;
Student(){
this.name= "Hello";
this.batch="Unspecified";
}
Student(String name,String batch){
this.name=name;
this.batch=batch;
}
}
The following snippet uses a map for storing the student name and his batch, in this map key is string and value is of object type. and putting a value of key "l".
Map<String, Object> updates = new HashMap<>();
updates.put("l", Arrays.asList(student.batch,student.name));
ref.child("Student Details").setValue(updates);
I have been trying to send raw json using retrofit 2 but not working, i have tried JsonObject , map but it's not working at all. I don't understand what the problem is. Works fine on Postman.
I am trying to send this request:
{
"incomes":[{"amount":"5566","incomeId":"345"}]
}
my android code is:
#Headers({"Accept: application/json"})
#POST("/api/v1/addIncome")
Call<ResponseBody> addIncome(#Body Map<String, String> params);
Map<String, String> params = new HashMap<>();
Call<ResponseBody> req = null;
Income[] incomes = new Income[1];
incomes[0] = income;
params.put(URLParam.INCOMES, new Gson().toJson(incomes));
req = CustomUtil.getCuumiAPIObject(this, URLConstant.BASE_URL).addIncome(params);
I know added the relavent part, rest works fine with other services, problem is of parameter.In response server gives a null value exception meaning, the parameter their is not picking up the value. Would really appreciate some help.
While sending String Map, You need to send it with #FieldMap instead of String Map as #Body.
Use #FiledMap as below in your code:
#FieldMap Map<String, String> params
Edit
If you want to send your json with #Body, you need to send with pojo class as #Body by setting your value in pojo class.
Pojo class:
public class Incomes {
#SerializedName("incomes")
#Expose
private List<Income> incomes = null;
public List<Income> getIncomes() {
return incomes;
}
public void setIncomes(List<Income> incomes) {
this.incomes = incomes;
}
public class Income {
#SerializedName("amount")
#Expose
private String amount;
#SerializedName("incomeId")
#Expose
private String incomeId;
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getIncomeId() {
return incomeId;
}
public void setIncomeId(String incomeId) {
this.incomeId = incomeId;
}
}
}
Then you need to create object of Incomes class and need to set every income in created object of Incomes class.
Incomes incomes=new Incomes();
Incomes.Income mIncome=new Incomes().new Income();
mIncome=income;
incomes.setIncomes(mIncome);
Then send Incomes class object as #Body in you API request.
req = CustomUtil.getCuumiAPIObject(this, URLConstant.BASE_URL).addIncome(incomes);
You also need to change your addIncome method as below:
Call<ResponseBody> addIncome(#Body Incomes incomes);
Hope this helps you.
Hello i'm a newbie on firebase, i'm creating a simple app to store text data on my firebase database. My goal is just to store the text but it seems that i cannot store the text.
I have this code for my send button which gets the value from the textbox and send it to the database. I can't figure out what's wrong.
public void onSendButtonClick(View v) {
String message = mMessageEdit.getText().toString();
Map<String, String> values = new HashMap<>();
values.put("name", "puf");
values.put("message", message.toString());
mFirebaseRef.push().setValue(values);
mMessageEdit.setText("");
}
Hope you could help me with this simple newbie problem.
Thanks. :)
I usually make a long variable to save date in millisecond.
long currentTimeInMillis = System.currentTimeInMillis();
Map<String, String> values = new HashMap<>();
values.put("date", currentTimeInMillis);
mFirebaseRef.push().setValue(values);
And then to convert it back I use DateFormat class (from android.text.format)
public static String getDate(String dateFormat, long currentTimeInMillis) {
return DateFormat.format(dateFormat, currentTimeInMillis); }
// Example usage
getDate("dd/MM/yyyy hh:mm:ss", "38232213325");
Try using a Map of type Map<String, Object> to write your values:
public void onSendButtonClick(View v) {
String message = mMessageEdit.getText().toString();
Map<String, Object> values = new HashMap<>();
values.put("name", "puf");
values.put("message", message);
mFirebaseRef.push().setValue(values);
mMessageEdit.setText("");
}
I am new to Kumulos development.
I want to get selected data from table of kumulos.
Like If user enter username and password i check from table that data exits or not.
But the issue is while checking data inserted in table and not giving me correct output.
While testing api in browser it works fine.
My code for select from table is below.
public void CallApiLogin(){
final String Uname=editUname.getText().toString();
final String pass=editPass.getText().toString();
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", Uname);
params.put("password",pass);
Kumulos.call("user_register", params, new ResponseHandler() {
#Override
public void didCompleteWithResult(Object result) {
// Do updates to UI/data models based on result
ArrayList<LinkedHashMap<String, Object>> objects = (ArrayList<LinkedHashMap<String,Object>>) result;
for (LinkedHashMap<String, Object> item : objects) {
String name = (String) item.get("name");
String password = (String) item.get("password");
if(name.equalsIgnoreCase(Uname) && password.equalsIgnoreCase(pass)){
Intent i=new Intent(Login.this,Home.class);
startActivity(i);
}else{
Toast.makeText(getApplicationContext(),"Please enter valid username and password.",Toast.LENGTH_SHORT).show();
}
}
}
});
}
Please suggest where i am going wrong as requested data inserted in table.
But i want that request data exist or not????
After spending hours, I got solution.
Issue is creating api. In Kumulos you have to create different api.
I was using api "user_register", Now i have create other api call "Select_user".
This api works fine what the result i want.
I hope this question may help some other.