I'm trying to insert some data into my firebase but encountered the following error, the 2nd data is missing. Here are the code:
Firebase.setAndroidContext(this);
Button btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
//Creating firebase object
Firebase ref = new Firebase(Config.FIREBASE_URL);
//Getting values to store
String name = mName.getText().toString().trim();
String address = mAddress.getText().toString().trim();
String latlng = mLatLng.getText().toString().trim();
//Creating Person object
FM_Spots spots = new FM_Spots();
//Adding values
spots.setName(name);
spots.setAddress(address);
spots.setLatLng(latlng);
//Storing values to firebase
//ref.child("FM_Spots").setValue(spots);
Firebase newRef = ref.child("FM_Spots").push();
newRef.setValue(spots);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
I only have 2 fields which are name and the address is having data from the last field (latlng). Please advise, thank you.
-sea-
When you said "2nd data" you meant that the second field of the writable object is missing, right?
If so, you can use updateChildren(Map map) method instead of setValue() to specify fields you want to write directly:
newRef.updateChildren(convertFMSpotsToMap(spots));
where convertFMSpotsToMap() is something like this:
private static Map<String, Object> convertFMSpotsToMap(#NonNull FM_Spots spots) {
HashMap<String, Object> map = new HashMap<>();
map.put("name", spots.getName());
map.put("address", spots.getAddress());
return map;
}
Related
Okay, say I've got the following FireBase database structure.
{
"2143" :
{
"Henk" : 6,
"message" : 1
}
}
With data being added as follows:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("2143/message");//Testing code, would later be replaced with a session variable and a username variable.
myRef.setValue(1);//Again, mere testing code which sets the 'message' key to have value 1. The actual code is currently lacking as the program isn't entirely functional yet.
I now want to put the players and their respective scores into a leaderboard on an android app in android studio. When I'm trying to put them into a hashmap using the following code:
String code = "2143"; //This is would be the SessionID, it's currently static for testing purposes.
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference(code);
HashMap<String, String> leaderboardMap = new HashMap<>();
...
myRef.orderByValue().addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
leaderboardMap.put(dataSnapshot.getKey(), dataSnapshot.getValue().toString());
}
}
I get the following hashmap
key: 2143, value:{Henk=6, message=1}
However I expected the following:
key: Henk, value: 6
key: message, value: 1
Where's the error in my code, and how can I fix it?
You can convert the json string to HashMap and then use those values to display in leaderborad. Here is a function to convert json sring to map.
public static HashMap<String,String> jsonToMap(String t) throws JSONException {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jObject = new JSONObject(t);
Iterator<?> keys = jObject.keys();
while( keys.hasNext() ){
String key = (String)keys.next();
String value = jObject.getString(key);
map.put(key, value);
}
return map;
}
I'm trying to extract the auto-generated Id under a document so I can use it elsewhere.
Here is the full code:
mStartChatButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final HashMap<String, Object> myChatFields = new HashMap<>();
myChatFields.put("dateJoined", ServerValue.TIMESTAMP );
myChatFields.put("status", "");
myChatFields.put("snoozeUntil", "");
myChatFields.put("myCharacter", "");
myChatFields.put("requestedCustomChatCode", "");
myChatFields.put("groupChatName", "");
myChatFields.put("toInviteMembers", "");
myChatFields.put("lastMessage", "");
myChatFields.put("lastMessageTimeStamp", ServerValue.TIMESTAMP);
mWhammyUsersCollection.document(mCurrentUserId).collection("my-chats")
.document().set(myChatFields)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
String chatId = mWhammyUsersCollection.document(mCurrentUserId)
.collection("my-chats").document().getId();
Log.v("CHATS", chatId);
myChatFields.put("chatCardId", chatId);
Intent goToChatActivity = new Intent(UserProfileActivity.this,
ChatActivity.class);
startActivity(goToChatActivity);
}
});
As you can see I'm using the code shown below to generated a Collection called "my-chats" and the .document() is creating the auto-generated document id.
mWhammyUsersCollection.document(mCurrentUserId).collection("my-chats")
.document().set(myChatFields)
.addOnSuccessListener(new OnSuccessListener<Void>() {
Then I'm using the line of code shown below to try get the id from that document.
String chatId = mWhammyUsersCollection.document(mCurrentUserId)
.collection("my-chats").document().getId();
Finally using the line of code below, I'm trying to put it into the HashMap I have created.
myChatFields.put("chatCardId", chatId);
There are two main problems I am having:
1) The line of code I'm using to extract the document Id is not working and is extracting some other new auto-generated id (I'm guessing it is because I'm using the .document() method before the .getId() method).
2) Also the information for some reason does not get added to the HashMap with the last line of code I put.
How can I solve these two issues?
To explain it a bit more graphically:
Picture of database
I'm trying to retrieve "1" and add it in the area of "2".
1) The line of code I'm using to extract the document Id is not working and is extracting some other new auto-generated id (I'm guessing it is because I'm using the .document() method before the .getId() method).
No, this is happening because you are calling CollectionReference's document() method twice:
Returns a DocumentReference pointing to a new document with an auto-generated ID within this collection.
So every time you are calling document() method, a fresh new id is generated. To solve this, please change the following lines of code:
mWhammyUsersCollection.document(mCurrentUserId).collection("my-chats")
.document().set(myChatFields)
.addOnSuccessListener(/* ... */);
to
String id = mWhammyUsersCollection.document(mCurrentUserId).collection("my-chats")
.document().getId();
mWhammyUsersCollection.document(mCurrentUserId).collection("my-chats")
.document(id).set(myChatFields)
.addOnSuccessListener(/* ... */);
See, I have used the id that was generated first time inside the refernce. Now inside the onSuccess() method, you should use the same id that was generated above:
myChatFields.put("chatCardId", id);
And not a newer one, as you do in your actual code.
2) Also the information for some reason does not get added to the HashMap with the last line of code I put.
This is happening becase you are using a wrong reference. Using a reference that contains the correct id will solve your problem.
For part one, you'll want to get the document reference in the onSuccess function vs. void. So that would look something like this -
mWhammyUsersCollection.document(mCurrentUserId).collection("my-chats").add(myChatFields)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
String chatId = documentReference.getId();
Log.v("CHATS", chatId);
myChatFields.put("chatCardId", chatId);
Intent goToChatActivity = new Intent(UserProfileActivity.this,
ChatActivity.class);
startActivity(goToChatActivity);
}
});
In Documentation writed that
However, sometimes there is no meaningful ID for this document and it's easier to let Cloud Firestore automatically generate an ID for you. You can do this by calling add().
So you can follow #R. Wright answer.
You can get your id from collection data as QuerySnapshot.Just store the position/id
mFirebaseStore.collection("allorder").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
try {
if (!queryDocumentSnapshots.isEmpty()) {
id = queryDocumentSnapshots.getDocuments().get(position).getId();
mArrayList.clear();
List<OrderDetails> data = queryDocumentSnapshots.toObjects(OrderDetails.class);
mArrayList.addAll(data);
mCustomerName.setText(mArrayList.get(position).getCustomerName());
mCustomerContact.setText(mArrayList.get(position).getContactNumber());
mCustomerLocation.setText(mArrayList.get(position).getArea().equals("") ? "No Location Found" : mArrayList.get(position).getArea());
mCustomerInstruction.setText(mArrayList.get(position).getSpecialInstruction().equals("") ? "Type Something" : mArrayList.get(position).getSpecialInstruction());
mTotalPrice.setText(mArrayList.get(position).getTotalPrice().equals("") ? "0" : mArrayList.get(position).getTotalPrice().toString());
String orderStatus = mArrayList.get(position).getOrderStatus();
if (orderStatus.equals("pending") || orderStatus.equals("rejected")) {
mLayout.setVisibility(View.VISIBLE);
} else if (orderStatus.equals("accepted")) {
mLayout.setVisibility(View.GONE);
}
JSONArray json = new JSONArray(mArrayList.get(position).getItemList());
List<AdminOrderDetailsModel> mList = new ArrayList<>();
for (int i = 0; i < json.length(); i++) {
JSONObject jsonObject = json.getJSONObject(i);
AdminOrderDetailsModel model = new AdminOrderDetailsModel();
model.setPackageName(jsonObject.getString("packageName"));
model.setPackageType(jsonObject.getString("packageType"));
model.setPrice(jsonObject.getString("price"));
model.setDuration(jsonObject.getString("duration"));
model.setQuantity(jsonObject.getInt("quantity"));
mList.add(model);
}
AdminOrderDetailsAdapter adapter = new AdminOrderDetailsAdapter(getApplicationContext(), mList);
setRecyclerLayoutManager(getApplicationContext(), mOrderListView, LinearLayoutManager.VERTICAL);
mOrderListView.setAdapter(adapter);
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
});
I am inserting some data in Firebase database From json Response in an array with below code
JSONArray arr = new JSONArray(result);
String[] stocks = new String[arr.length()];
for(int i=0;i<arr.length();i++){
JSONObject obj = arr.getJSONObject(i);
mDatabase= FirebaseDatabase.getInstance().getReference().child("books");
atabaseReference newBid=mDatabase.push();
newBid.child("usr_id").setValue(obj.getString("user_id"));
newBid.child("usr_fullNme").setValue(obj.getString("first_name")+" "+obj.getString("last_name"));
newBid.child("usr_mobile").setValue(obj.getString("user_mobile"));
newBid.child("usr_avatr").setValue(obj.getString("src"));
}
How can i check if above operation is successful or not
You can use a Hashmap and do the following:
Map<String, Object> userValues = new HashMap<>();
userValues.put("usr_id", obj.getString("user_id"));
userValues.put("usr_fullNme",obj.getString("first_name")+" "+obj.getString("last_name"));
userValues.put("usr_mobile", obj.getString("user_mobile"));
userValues.put("usr_avatr", obj.getString("src"));
Then use setValue():
mDatabase= FirebaseDatabase.getInstance().getReference().child("books");
String newBid = mDatabase.push().getKey();
mDatabase.child(newBid).setValue(userValues, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
System.out.println(databaseError);
}
});
From the docs:
public void setValue (Object value, DatabaseReference.CompletionListener listener)
Set the data at this location to the given value. Passing null to setValue() will delete the data at the specified location. The native types accepted by this method for the value correspond to the JSON types:
Boolean
Long
Double
String
Map
List
I'm trying to extract the auto-generated Id under a document so I can use it elsewhere.
Here is the full code:
mStartChatButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final HashMap<String, Object> myChatFields = new HashMap<>();
myChatFields.put("dateJoined", ServerValue.TIMESTAMP );
myChatFields.put("status", "");
myChatFields.put("snoozeUntil", "");
myChatFields.put("myCharacter", "");
myChatFields.put("requestedCustomChatCode", "");
myChatFields.put("groupChatName", "");
myChatFields.put("toInviteMembers", "");
myChatFields.put("lastMessage", "");
myChatFields.put("lastMessageTimeStamp", ServerValue.TIMESTAMP);
mWhammyUsersCollection.document(mCurrentUserId).collection("my-chats")
.document().set(myChatFields)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
String chatId = mWhammyUsersCollection.document(mCurrentUserId)
.collection("my-chats").document().getId();
Log.v("CHATS", chatId);
myChatFields.put("chatCardId", chatId);
Intent goToChatActivity = new Intent(UserProfileActivity.this,
ChatActivity.class);
startActivity(goToChatActivity);
}
});
As you can see I'm using the code shown below to generated a Collection called "my-chats" and the .document() is creating the auto-generated document id.
mWhammyUsersCollection.document(mCurrentUserId).collection("my-chats")
.document().set(myChatFields)
.addOnSuccessListener(new OnSuccessListener<Void>() {
Then I'm using the line of code shown below to try get the id from that document.
String chatId = mWhammyUsersCollection.document(mCurrentUserId)
.collection("my-chats").document().getId();
Finally using the line of code below, I'm trying to put it into the HashMap I have created.
myChatFields.put("chatCardId", chatId);
There are two main problems I am having:
1) The line of code I'm using to extract the document Id is not working and is extracting some other new auto-generated id (I'm guessing it is because I'm using the .document() method before the .getId() method).
2) Also the information for some reason does not get added to the HashMap with the last line of code I put.
How can I solve these two issues?
To explain it a bit more graphically:
Picture of database
I'm trying to retrieve "1" and add it in the area of "2".
1) The line of code I'm using to extract the document Id is not working and is extracting some other new auto-generated id (I'm guessing it is because I'm using the .document() method before the .getId() method).
No, this is happening because you are calling CollectionReference's document() method twice:
Returns a DocumentReference pointing to a new document with an auto-generated ID within this collection.
So every time you are calling document() method, a fresh new id is generated. To solve this, please change the following lines of code:
mWhammyUsersCollection.document(mCurrentUserId).collection("my-chats")
.document().set(myChatFields)
.addOnSuccessListener(/* ... */);
to
String id = mWhammyUsersCollection.document(mCurrentUserId).collection("my-chats")
.document().getId();
mWhammyUsersCollection.document(mCurrentUserId).collection("my-chats")
.document(id).set(myChatFields)
.addOnSuccessListener(/* ... */);
See, I have used the id that was generated first time inside the refernce. Now inside the onSuccess() method, you should use the same id that was generated above:
myChatFields.put("chatCardId", id);
And not a newer one, as you do in your actual code.
2) Also the information for some reason does not get added to the HashMap with the last line of code I put.
This is happening becase you are using a wrong reference. Using a reference that contains the correct id will solve your problem.
For part one, you'll want to get the document reference in the onSuccess function vs. void. So that would look something like this -
mWhammyUsersCollection.document(mCurrentUserId).collection("my-chats").add(myChatFields)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
String chatId = documentReference.getId();
Log.v("CHATS", chatId);
myChatFields.put("chatCardId", chatId);
Intent goToChatActivity = new Intent(UserProfileActivity.this,
ChatActivity.class);
startActivity(goToChatActivity);
}
});
In Documentation writed that
However, sometimes there is no meaningful ID for this document and it's easier to let Cloud Firestore automatically generate an ID for you. You can do this by calling add().
So you can follow #R. Wright answer.
You can get your id from collection data as QuerySnapshot.Just store the position/id
mFirebaseStore.collection("allorder").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
try {
if (!queryDocumentSnapshots.isEmpty()) {
id = queryDocumentSnapshots.getDocuments().get(position).getId();
mArrayList.clear();
List<OrderDetails> data = queryDocumentSnapshots.toObjects(OrderDetails.class);
mArrayList.addAll(data);
mCustomerName.setText(mArrayList.get(position).getCustomerName());
mCustomerContact.setText(mArrayList.get(position).getContactNumber());
mCustomerLocation.setText(mArrayList.get(position).getArea().equals("") ? "No Location Found" : mArrayList.get(position).getArea());
mCustomerInstruction.setText(mArrayList.get(position).getSpecialInstruction().equals("") ? "Type Something" : mArrayList.get(position).getSpecialInstruction());
mTotalPrice.setText(mArrayList.get(position).getTotalPrice().equals("") ? "0" : mArrayList.get(position).getTotalPrice().toString());
String orderStatus = mArrayList.get(position).getOrderStatus();
if (orderStatus.equals("pending") || orderStatus.equals("rejected")) {
mLayout.setVisibility(View.VISIBLE);
} else if (orderStatus.equals("accepted")) {
mLayout.setVisibility(View.GONE);
}
JSONArray json = new JSONArray(mArrayList.get(position).getItemList());
List<AdminOrderDetailsModel> mList = new ArrayList<>();
for (int i = 0; i < json.length(); i++) {
JSONObject jsonObject = json.getJSONObject(i);
AdminOrderDetailsModel model = new AdminOrderDetailsModel();
model.setPackageName(jsonObject.getString("packageName"));
model.setPackageType(jsonObject.getString("packageType"));
model.setPrice(jsonObject.getString("price"));
model.setDuration(jsonObject.getString("duration"));
model.setQuantity(jsonObject.getInt("quantity"));
mList.add(model);
}
AdminOrderDetailsAdapter adapter = new AdminOrderDetailsAdapter(getApplicationContext(), mList);
setRecyclerLayoutManager(getApplicationContext(), mOrderListView, LinearLayoutManager.VERTICAL);
mOrderListView.setAdapter(adapter);
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
});
i have a request to build slider image from jsonArray using volley, i don't know how to put value of jsonArray to hashmap<string, string> .. it keep saying null object
error message
Attempt to invoke virtual method 'java.lang.Object
java.util.HashMap.put(java.lang.Object, java.lang.Object)' on a null object reference
JSON array value
[
{"cPID":"62001002280293829",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/rsch.jpg"},
{"cPID":"62001002020254584",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/penang.jpg"},
{"cPID":"62001002050264258",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/guardian.jpg"}
]
and then i wanna put that value like this into hashmap<string, string> inside onCreate()
HashMap<String,String> url_maps = new HashMap<>();
url_maps.put("Hannibal", "http://static2.hypable.com/wp-content/uploads/2013/12/hannibal-season-2-release-date.jpg");
url_maps.put("Big Bang Theory", "http://tvfiles.alphacoders.com/100/hdclearart-10.png");
url_maps.put("House of Cards", "http://cdn3.nflximg.net/images/3093/2043093.jpg");
url_maps.put("Game of Thrones", "http://images.boomsbeat.com/data/images/full/19640/game-of-thrones-season-4-jpg.jpg");
it gonna use for adding picture to my slider(slideshow) inside onCreate()
for(String name : url_maps.keySet()){
DefaultSliderView DefaultSliderView = new DefaultSliderView(getContext());
// initialize a SliderLayout
DefaultSliderView
.image(url_maps.get(name))
.setScaleType(BaseSliderView.ScaleType.Fit)
.setOnSliderClickListener(this);
//add your extra information
DefaultSliderView.bundle(new Bundle());
DefaultSliderView.getBundle()
.putString("extra",name);
mDemoSlider.addSlider(DefaultSliderView);
}
and i don't know how to put values from volley JsonArray, and this is my request but error saying null.
private void getSlider(){
String tag_string_req = "sliderList";
// Showing progress dialog before making http request
JsonArrayRequest mostReq = new JsonArrayRequest(AppConfig.URL_Slider, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
for (int i = 0; i < 5; i++) {
JSONObject jObj = response.getJSONObject(i);
url_maps.put(jObj.getString("cPID"), jObj.getString("image"));
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + "Error Data Occured!!" + error.getMessage());
Toast.makeText(getContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) ;
AppController.getInstance().addToRequestQueue(mostReq, tag_string_req);
}
the values request was accepted on volley, it show on Logcat .. but null on hashmap .. tell me if i got mistake in my code, sorry just newbie and still study
You are iterating thru just the keys... You need to iterate through the keys and values...
for (url_maps.Entry<String, String> url_map : url_maps.entrySet()) {
String key = url_map.getKey();
String value = url_map.getValue();
// ...
}
ANOTHER WAY TO ATTEMPT THIS IS...
to deserialize your Json into a java object...
ObjectMapper mapper = new ObjectMapper();
string StringJson = "[
{"cPID":"62001002280293829",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/rsch.jpg"},
{"cPID":"62001002020254584",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/penang.jpg"},
{"cPID":"62001002050264258",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/guardian.jpg"}
]";
// For the following line to work you will need to make a URLMaps Class to hold the objects
URLMaps urlMaps = mapper.readValue(StringJson , URLMaps.class);
The URLMaps Class might look like this.
public class URLMaps{
public string name = "";
public string image = "";
//constructor
public URLMaps(string a, string b) {
name = a;
image = b;
}
public string getName() {
return name;
}
public string getImage() {
return image;
}
}
Then to utilize the class you can go with:
urlMaps.getName(), or urlMaps.getValue() in your DefaultSliderView.image()
Also to note, since this is a class you can store an array of them or a list of them, so you can re-purpose your for loop...
For (URLMap urlmap : UrlMaps[]) // where URLMaps is your object that holds multiple instances of URLMaps.
Lastly, it has been a long time since I have coded in Java, so this code is untested, but should help you come to a solution.