Java – retrofitting with firebase
Ask anyone for help This is my API method
@POST("/user/new.json") Call createUser(@Body User user);
This is my phone in mainactivity
Retrofit retrofit=new Retrofit.Builder().baseUrl("https://XXXXXX.firebaseio.com").addConverterFactory(GsonConverterFactory.create()).build(); Api api=retrofit.create(Api.class); User user=new User(1,"Sam"); Call<User> call=api.createUser(user); call.enqueue(new Callback<User>() { @Override public void onResponse(Call<User> call,Response<User> response) { Log.d("sam","run"); } @Override public void onFailure(Call<User> call,Throwable t) { Log.d("sam","error"); } });
This is user java
public class User { int id; String name; public User(int id,String name) { this.id = id; this.name = name; } }
The output is like this: –
"user" : {"new" : {"-KBgcQTomo8xGpnv5raM" : {"id" : 1,"name" : "Sam"}}}
But I want to output: –
"user" : {"new" : {"id" : 1,"name" : "Sam"}}
This is a tutorial for retrofit + firebase
Please help
Solution
In firebase, when you post try to push the list of data stored under the URL of post Therefore, it is not possible to / user / new JSON performs post operation and does not store data under the key generated by the new firebase, such as "- kbgcqtomo8xgpnv5ram" under / user / new
If you want complete control over where you place data, you must use put However, it makes no sense to treat your new entry directly as / user / new Where will the subsequent entries be?
If you do not accept server - side key distribution, the normal solution will be to use part of the entry you will enforce uniqueness For example, a name or numeric ID may be the key of a new user so that multiple users can be added
Based on the modified API and using the name as the unique key, this is:
@POST("/user/new.json") Call createUser(@Body User user);
Will become:
@PUT("/user/new/{name}.json") Call createUser(@Path("name") String name,@Body User user);
And:
Call<User> call=api.createUser(user);
That would be:
Call<User> call=api.createUser(user.name,user);
The current layout is:
"user" : {"new" : {"Sam": {"id" : 1,"name" : "Sam"}}}
So future users can be added as long as they are not named Sam