storing data into firestore in android - android

I have 2 arrays like
phonenumber[]={12345,67890,43215,34567,56789}
amount[]={10,20,30}
I want to store data in a document like
field1:phonenumber1 as 12345
field2:amount1 as 10
and again the same process to happen in the same document in firestore.
Is it possible to store like this in firestore
My code
final int phonenumber[] = {12345,67890,43215,67894,32453};
final int length = list.length;
final int amount[] = {20,30,40,50,60};
final int length1 = amount.length;
Map<String, Object> docData1 = new HashMap<>();
for(int i =0 ; i<length;i++)
{
for(int j =i;j<=i;j++){
docData1.put("phonenumber", list[i]);
docData1.put("amount", amount[i]);
}
}
docData1.put("invitee",docData1);
db.collection("Split").document("lahari")
.set(docData1)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully written!");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error writing document",e);
}
});
error I had occured is

Related

Can't get the total value of 2 children in Firebase database - Android

I have a method that will upload an app order. You can get the price from database (harga) and amount from the user, but I can't get the total from that. It always gets value as 0.
So here's my code:
public void uploadImg() {
if (FilePathUri != null) {
progressDialog.setTitle("Process...");
progressDialog.show();
StorageReference storageReference2 = storageReference.child(System.currentTimeMillis() + "." + GetFileExtension(FilePathUri));
storageReference2.putFile(FilePathUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
final String ukuran = UkuranPasFoto.getSelectedItem().toString().trim();
final int jumlah = Integer.parseInt(JumlahPasFoto.getText().toString().trim());
final String catatan = inputCatatan.getText().toString().trim();
final int status = 0;
databaseHarga.child("harga").child("pasFoto").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
int harga = dataSnapshot.child(ukuran).getValue(Integer.class);
int total = harga*jumlah;
progressDialog.dismiss();
Toast.makeText(getApplicationContext(),"Sucess !",Toast.LENGTH_LONG).show();
PesanPasFoto ImageUploadInfo = new PesanPasFoto(uid, ukuran, jumlah, catatan, total, status, taskSnapshot.getUploadSessionUri().toString());
String ImageUploadId = database.push().getKey();
database.child(ImageUploadId).setValue(ImageUploadInfo);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
} else {
Toast.makeText(PasFotoActivity.this,"Please Select Image or Fill the blank",Toast.LENGTH_LONG).show();
}
}
here's my database
As you can see that "total" value is always 0
and there's nothing wrong in logcat

Android Firestore db returns value exact every seccond time

i have a real strange problem. I have two methods where i parse data depending on user selected values. In my seccond method i parse those data. The seccond method returns always the right values but in my first method gets this values only every seccond time. I cannot find the issue. The list which i get from previous method is also right, so i get also all values.
Here is my Code:
mBuilder.setPositiveButton("Suche", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
ArrayList<String> selectedCategories = new ArrayList<>();
for (int i = 0; i < mUserItems.size(); i++) {
selectedCategories.add(listItems[mUserItems.get(i)]);
}
// selectedCategories.add("asdf");
getStores(selectedCategories);
}
});
private void getStores(ArrayList<String> checkedItems) {
for (int i =0; i<checkedItems.size(); i++){
String checkedItem = checkedItems.get(i);
getStore(checkedItem);
}
getDistanceToUser(sellers2);
}
private void getStore(String checkedItem) {
db.collection("Seller")
.whereEqualTo("typ", checkedItem)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
SellerObject so = document.toObject(SellerObject.class);
so.setId(document.getId());
sellers2.add(so);
Log.i(TAG, "onComplete: toa"+sellers.size());
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
}

One one image uploading with different postkeys but i want to store all images under one postkey in Firebase Database

One one image uploading with different postkeys but i want to store all images under one postkey
This is the code where im uploading all the images to firebase storage and databse with post key but one one images are storing with different post key and i want to store all the uploaded images into one post key under blog in firebase databse. Please help me _This is th issue im facing from past few days and i want to retrieve all the uploaded images under one postkey
upload.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
UploadTask uploadTask;
if( selectedImageGridView.getChildCount()!= 0)
{
for ( int i = 0; i < selectedImages.size(); i++) {
blogimages = new ArrayList<>();
Uri uri = Uri.parse("file://"+selectedImages.get(i));
final String CurrentUser = firebaseAuth.getCurrentUser().getUid();
StorageReference reference = mstorageReference.child("Blog_pics/users").child(uri.getLastPathSegment());
uploadTask = reference.putFile(uri);
uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
final Uri downloaduri = taskSnapshot.getDownloadUrl();
Log.v("DOWNLOAD URI", String.valueOf(downloaduri));
blogimages.add(downloaduri.toString());
Log.v("BLOGGIMAGES", String.valueOf(blogimages));
final String key = mdatabaseReference.push().getKey();
final String posttitle = desc.getText().toString();
final String CurrentUser = firebaseAuth.getCurrentUser().getUid();
int l = 0;
while (l < blogimages.size()){
Log.v("BLOGIMAGESSIZE", String.valueOf(blogimages.size()));
Map n = new HashMap();
int countingImage = 0;
n.put(String.valueOf("img" + countingImage), blogimages.get(l).toString());
Log.v("MapCount", String.valueOf(n));
mdatabaseReference.child(key).child("images").updateChildren(n).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
Toast.makeText(PhotoUploadActivity.this, "got download url", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(PhotoUploadActivity.this, "Failed to put in db", Toast.LENGTH_SHORT).show();
}
}
});
l++;
countingImage++;
}
}
}) .addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
});
}
}
}
});
you have to change this line
StorageReference reference = mstorageReference.child("Blog_pics/users").child(uri.getLastPathSegment());
to this lines: you have to put those lines befor the for loop
String userId = firebaseAuth.getCurrentUser().getUid();
StorageReference reference = mstorageReference.child("Blog_pics/users").child(userId);
then inside the loop
refrence.child(uri.getLastPathSegment());
uploadTask = reference.putFile(uri);
...

Firebase Storage OnSuccessListeners not successful in time

After thorough debugging, I have concluded that the reason my GridView is not displaying any of my Images is because both of my OnSuccessListeners in getData() and getImage() from when I get the thumbnail and title from Firebase Storage are not successful yet.
I do all of this in my getData() method, which I call after the user selects their Google Place in onActivityResult. The method should instantiate a new ImageItem(Bitmap, String) but is returning a null ImageItem due to the onSucessListeners not being successful yet. Any ideas?
private void getData() {
imageItems = new ArrayList<>();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child((String) p.getName()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator<DataSnapshot> iter = dataSnapshot.getChildren().iterator();
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference httpsReference = storage.getReferenceFromUrl(myUrl);
while (iter.hasNext()) {
hasImage = false;
hasTitle = false;
HashMap<String, String> m = (HashMap<String, String>) iter.next().getValue();
String v = m.get("url");
Log.d("url", v);
String bu = m.get("bucket");
Log.d("bucket", bu);
b = getImage(bu, v);
StorageReference iR = httpsReference.child(bu).child("thumb");
httpsReference.child(bu).getMetadata().addOnSuccessListener(new OnSuccessListener<StorageMetadata>() {
#Override
public void onSuccess(StorageMetadata storageMetadata) {
// Metadata now contains the metadata for 'images/forest.jpg'
t = storageMetadata.getCustomMetadata("title");
hasTitle = true;
Log.d("title", t);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.d("error", "ERROr");
// Uh-oh, an error occurred!
}
});
gridAdapter.data.add(new ImageItem(b, t, bu, v));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public Bitmap getImage(String bx, String vu) {
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference httpsReference = storage.getReferenceFromUrl(myUrl);
String v = vu;
Log.d("url", v);
String bu = bx;
Log.d("bucket", bu);
StorageReference iR = httpsReference.child(bu).child("thumb");
final long ONE_MEGABYTE = 1024 * 1024;
iR.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
#Override
public void onSuccess(byte[] bytes) {
// Data for "images/island.jpg" is returns, use this as needed
b = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
hasImage = true;
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
return b;
}
}
****************UPDATE 1/7/2017*********************
private void getData() {
imageItems = new ArrayList<>();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child((String) p.getName()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator<DataSnapshot> iter = dataSnapshot.getChildren().iterator();
FirebaseStorage storage = FirebaseStorage.getInstance();
final StorageReference httpsReference = storage.getReferenceFromUrl("gs://socialnetwork-4b0c9.appspot.com");
while (iter.hasNext()) {
hasImage = false;
hasTitle = false;
HashMap<String, String> m = (HashMap<String, String>) iter.next().getValue();
final String v = m.get("url");
Log.d("url", v);
final String bu = m.get("bucket");
Log.d("bucket", bu);
StorageReference iR = httpsReference.child(bu).child("thumb");
final long ONE_MEGABYTE = 1024 * 1024;
iR.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
#Override
public void onSuccess(byte[] bytes) {
// Data for "images/island.jpg" is returns, use this as needed
b = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
httpsReference.child(bu).getMetadata().addOnSuccessListener(new OnSuccessListener<StorageMetadata>() {
#Override
public void onSuccess(StorageMetadata storageMetadata) {
// Metadata now contains the metadata for 'images/forest.jpg'
t = storageMetadata.getCustomMetadata("title");
hasTitle = true;
gridAdapter.data.add(new ImageItem(b, t, bu, v));
Log.d("title", t);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.d("error", "ERROr");
// Uh-oh, an error occurred!
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
************************METHOD PERTAINING TO GRIDVIEW AND GRIDADAPTER*********
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(this, data);
p = place;
gridView = (GridView) findViewById(R.id.grid_View);
gridAdapter = new GridViewAdapter(this, R.layout.grid_item_layout);
getData();
gridView.setAdapter(gridAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
ImageItem item = (ImageItem) parent.getItemAtPosition(position);
//Create intent
Intent intent = new Intent(PlaceActivity.this, VideoActivity.class);
intent.putExtra("bucket", item.getBucket());
intent.putExtra("dUrl", item.getdUrl());
//Start details activity
startActivity(intent);
}
});
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(this, data);
// TODO: Handle the error.
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
}
}
This is a classic asynchronous programming issue:
var a = 1;
incrementAsync(function() {
a = 2;
});
console.log(a); // prints 1 because the function hasn't returned yet
You need to instead perform the action in the async function:
var a = 1;
incrementAsync(function() {
a = 2;
console.log(a); // prints 2 now
});
So I'd re-write your function as:
FirebaseDatabase mDatabase = FirebaseDatabase.getInstance();
FirebaseStorage mStorage = FirebaseStorage.getInstance();
mDatabase.getReference("...").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
ModelObject modelObject = storage.getValue(ModelObject.class);
// Or just download the object here...
mStorage.getReferenceFromUrl(modelObject.getUrl()).getMetadata().addOnSuccessListener(new OnSuccessListener<StorageMetadata>() {
#Override
public void onSuccess(StorageMetadata storageMetadata) {
String title = storageMetadata.getCustomMetadata("title");
gridAdapter.data.add(...);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Uh-oh, an error occurred!
}
});
}
...
});

Firebase - Sometimes value is not saving

Take a look at this GIF I recorded:
This is the database of a counter app I'm making. When a user increments, count gets added along with the count under
users:{
UID:{
count: x
}
}
However, if you can notice in the GIF, sometimes, the upper count gets incremented but the one under users doesn't. Here's the code I'm saving it with:
database = database.child("users").child(auth.getCurrentUser().getUid()).child("count");
final DatabaseReference finalDatabase = database;
database.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Get the latest int
final int[] i = {Integer.parseInt(button.getText().toString())};
//add to the user's count with an onFailureListener
finalDatabase.setValue(i[0]++).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e(TAG,"Adding user's count failed: " + e.getMessage());
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
//Now add to the original
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
database.child("Campaigns").child(key).child("count").setValue(i[0]++).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e(TAG, "Error: " + e.getMessage());
}
});
}
});
None of the onFailure methods get called. So why is this happening?
You can instead listen to the users node to count the total count. Here's an example
private Map<String, Long> userCount = new HashMap<>();
private Long totalCount = 0L;
private void addTotalCountListener() {
FirebaseDatabase.getInstance().getReference().child("users").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
User user = dataSnapshot.getValue(User.class);
userCount.put(dataSnapshot.getKey(), user.getCount);
totalCount += user.getCount();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
// subtract the total count with the previous count
totalCount -= userCount.get(dataSnapshot.getKey());
// then add the new count
User user = dataSnapshot.getValue(User.class);
userCount.put(dataSnapshot.getKey(), user.getCount);
totalCount += user.getCount();
}
});
}

Categories

Resources