I have uploaded 1 Hashmap to firestore.And when i try to upload one more Hashmap to the same document it replaces my previous Hashmap.Why is it so?
I change the String title everytime and still it replaces the previous Hashmap.
String poll1 = Poll1.getText().toString().trim();
String poll2 = Poll2.getText().toString().trim();
String poll3 = Poll3.getText().toString().trim();
String title = Title.getText().toString().trim();
DocumentReference documentReference = firestore.collection("Polls").document("abc1");
Map<String, Object> nestedData = new HashMap<>();
nestedData.put(poll1 , 0 );
nestedData.put(poll2 , 0);
nestedData.put(poll3 , 0);
Map<String, Object> upload = new HashMap<>();
upload.put(title, nestedData);
documentReference.set(upload).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(polls.this, "UPLOADED", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(polls.this, "FAILED", Toast.LENGTH_LONG).show();
}
});
your document needs to mention that this has to be merged instead replace.
.set(data, SetOptions.merge())
Try this if it works.
documentReference.set(upload, SetOptions.merge()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(polls.this, "UPLOADED", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(polls.this, "FAILED", Toast.LENGTH_LONG).show();
}
});
Related
i want to accsess my firebase collection but somehow it didnt work on this java file, in otherwise i had another java file on my android project thats containts the same syntax and its actually work.. i dont have any idea to solve this line
on Signupn.java (worked)
fAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(SignUp.this, "User Created", Toast.LENGTH_SHORT).show();
userId = fAuth.getCurrentUser().getUid();
DocumentReference documentReference =fStore.collection("users").document(userId);
Map<String,Object> user =new HashMap<>();
user.put("fName",fullName);
user.put("email",email);
user.put("phone",phone);
documentReference.set(user).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Log.d(TAG,"onSuccess: user Profile is created for "+ userId);
}
});
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}else{
Toast.makeText(SignUp.this, "Error!"+task.getException().getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
});
on EditProfile.java (error)
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (editFullName.getText().toString().isEmpty() || editEmail.getText().toString().isEmpty()
|| editPhone.getText().toString().isEmpty()) {
Toast.makeText(EditProfile.this, "All Fields Are Required.", Toast.LENGTH_SHORT).show();
return;
}
String email = editEmail.getText().toString();
user.updateEmail(email).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
DocumentReference docRef = fStore.collection("users").document(user.getUid());
Map<String, Object> edited = new HashMap<>();
edited.put("email", email);
edited.put("fName", editFullName.getText().toString());
edited.put("phone", editPhone.getText().toString());
docRef.update(edited);
Toast.makeText(EditProfile.this, "Email Changed Successfully.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(EditProfile.this, "Error!", Toast.LENGTH_SHORT).show();
}
});
}
});
here is where the error line
DocumentReference docRef = fStore.collection("users").document(user.getUid());
in collection sentence.
this picture from editProfile.java
this picture from signup.java
thank you for your value answers, any answer i really apriciate it.
Please verify your dataStype for fstore object in both classes or post full code wherever you are declaring the fstore and intializing it
I'm trying to get pictures from firebase storage and save it into the firestore.
I upload the picture once, and then I tried to open this app but it keeps stop.
java.lang.IllegalArgumentException: uri cannot be null
It shows this error.
Here is my code, and this is the part occurring error.
private void postButtonClicked(){
//immutable read-only variable
final String title = ((EditText)findViewById(R.id.titleEditText)).getText().toString();
final String contents = ((EditText)findViewById(R.id.contentsEditText)).getText().toString();
if(!title.trim().isEmpty() || !contents.trim().isEmpty()){
final StorageReference postRef = storageReference.child("post_images").child(FieldValue.serverTimestamp().toString()+".jpg");
postRef.putFile(postImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
postRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
HashMap<String, Object> writeinfoMap = new HashMap<>();
writeinfoMap.put("image", uri.toString());
writeinfoMap.put("title", title);
writeinfoMap.put("contents", contents);
writeinfoMap.put("time", FieldValue.serverTimestamp());
// postMap.put("user", user);
firestore.collection("post").add(writeinfoMap).addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
#Override
public void onComplete(#NonNull Task<DocumentReference> task) {
if(task.isSuccessful()){
startActivity(new Intent(WritePostActivity.this, MainActivity.class));
Toast.makeText(WritePostActivity.this, "posted!", Toast.LENGTH_SHORT).show();
finish();
}else{
String error = task.getException().getMessage();
Toast.makeText(WritePostActivity.this,"Error: "+error,Toast.LENGTH_SHORT).show();
}
}
});
}
});
}else{
String error = task.getException().getMessage();
Toast.makeText(WritePostActivity.this,"Error: "+error,Toast.LENGTH_SHORT).show();
}
}
});
}else{
Toast.makeText(this,"please enter the title.", Toast.LENGTH_SHORT).show();
}
}
please help me to find out the error and fix it. Thanks
I recently added a feature to send images too along with the option to send text messages. Everything was working fine before that - messages popped as expected queried by descending time. But after I added this image sending feature whenever I scroll up or down the chat the messages get all jumbled up and I don't know why.
When I send only text:
Before Scrolling https://i.stack.imgur.com/2NMVHl.jpg
After Scrolling https://i.stack.imgur.com/2Nxpc.jpg (same)
When I send Image with text
Before Scrolling https://i.stack.imgur.com/rS6Mx.jpg
After Scrolling https://i.stack.imgur.com/OP5DK.jpg
In my code there are two places from where message(image or text) can be uploaded.
For sending Image message:
Briefings - Here I upload the image to the Storage and then retrieve its URL. Then I store the URL to firestore in form of string (which I later use to download the image using Picasso) along with other message details.
final Long currentTime = System.currentTimeMillis();
final String time = currentTime + "";
final StorageReference fileref = storageReference.child("Image Messages")
.child(uid + time);
StorageTask uploadTask = fileref.putFile(uri);
uploadTask.continueWithTask(new Continuation() {
#Override
public Object then(#NonNull Task task) throws Exception {
if(!task.isSuccessful()){
throw task.getException();
}
return fileref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if(task.isSuccessful()){
Uri downloadUrl = task.getResult();
String myUrl = downloadUrl.toString();
Map<String, Object> chat = new HashMap<>();
chat.put("message", myUrl);
chat.put("time", currentTime);
chat.put("sender", mUser.getUid());
chat.put("groupId",Gid);
chat.put("type","image");
chat.put("username",preferences.getData("username"));
chat.put("name",preferences.getData("usernameAdded"));
firestore.collection("aGroups").document(Gid).collection("Chat")
.add(chat).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
showChatMessages();
dialog.dismiss();
Toast.makeText(getApplicationContext(),"Message Sent", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(),"Error", Toast.LENGTH_SHORT).show();
}
});
}
}
});
For sending text message
Briefings - Here I upload the message and it's details
Map<String, Object> chat = new HashMap<>();
chat.put("message", message.getText().toString());
chat.put("time", System.currentTimeMillis());
chat.put("sender", mUser.getUid());
chat.put("groupId",Gid);
chat.put("type","text");
chat.put("username",preferences.getData("username"));
chat.put("name",preferences.getData("usernameAdded"));
firestore.collection("aGroups").document(Gid).collection("Chat")
.add(chat).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(ChatInterface.this, "Message Sent", Toast.LENGTH_SHORT).show();
showChatMessages();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(),"Error", Toast.LENGTH_SHORT).show();
}
});
This is where I add callbacks
private void showChatMessages() {
firestore.collection("aGroups").document(Gid).collection("Chat")
.orderBy("time", Query.Direction.DESCENDING)
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
if(error != null){
Log.d("Check", "listen failed: " + error.getMessage());
}
else{
Log.d("Check", "Snapshot worked");
List<ChatModel> list = new ArrayList<>();
list.clear();
for(QueryDocumentSnapshot query : value){
list.add(new ChatModel(
query.getString("groupId")
, query.getId()
, query.getString("message")
, query.getString("sender")
, query.getLong("time")
, query.getString("name")
, query.getString("username")
, query.getString("type")
));
}
recycler_interface.setAdapter(new RealChatRecyclerInterface(mUser.getUid(),list));
}}
});
}
I am adding my whole RealChatRecyclerInterface in this pastebin link.
Use holder.setIsRecyclable(false); in your RealChatRecyclerInterface
I created an app and I want to store some images in a Firebase Storage, this is working fine, those images are uploaded, but I want to save their path in the database and those values are not inserted.
Let me show you what I did:
I'm not showing you the entire function. Only the code that points to my problem.
List<String> picturesUrls = new ArrayList<String>(); //This is declared globaly
buttonSigningUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadFile(mProfilePic,"profilePicture");
uploadFile(mIdPhoto,"idPicture");
uploadFile(mCriminalRecord,"criminalRecordPicture");
final List<String> pictureUrls = picturesUrls;
mFirebaseAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
final CarrierUser carrierUser;
carrierUser = new CarrierUser(
pictureUrls
);
FirebaseDatabase.getInstance().getReference("User")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(carrierUser).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()) {
Toast.makeText(SignupCarrier.this,"Your request has been sent for approval", Toast.LENGTH_LONG).show();
sendEmail(email, fullname);
openLogin();
}
}
});
}
}
});
}
});
Upload File Function :
private void uploadFile(Uri path,String forWho) {
if(path != null) {
StorageReference fileReference = mStorageRef.child(editemail.getText().toString()+"-"+forWho+"-"+System.currentTimeMillis()+"."+getFileExtension(path));
mUploadTask = fileReference.putFile(path)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
picturesUrls.add(taskSnapshot.getUploadSessionUri().toString());
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(SignupCarrier.this, e.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
}
And the Object:
import java.util.List;
public class CarrierUser {
public List<String> picturesUrls;
public CarrierUser() {
}
public CarrierUser(List<String> picturesUrls) {
this.picturesUrls = picturesUrls;
}
}
I do have another values and fields, but they are inserted, only this list with paths is not. Maybe I did something wrong when I add a path to that list, but I can't figure out what exactly is wrong. Can you please help me out? Thank you very much.
What i am wanting to do: When a user creates a post have an iterator iterate through a document to see if the users has too many posts. If user has a null field post is allowed
The issue i am facing is that when the user creates a post it iterates through the list and posts on every null value, not just one.
To solve this issue I added break;. This solved my issue but now for some reason when the break; statement is used the iterator will only check to see if the 5th item in the document is null not all of the documents.
Code:
currentDocument.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Map<String, Object> map = document.getData();
for (Map.Entry<String, Object> entry : map.entrySet()) {
Log.d(TAG, map.entrySet().toString());
Log.d(TAG, entry.toString());
if (entry.getValue() == null) {
Log.d("tag", entry.toString() + " is equal to null");
posted....
break;
To solve this issue i found this stack post and they said to add a boolean flag (removed break:)
public static boolean criteriaMet=false;
currentDocument.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Map<String, Object> map = document.getData();
while (criteriaMet == false) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
Log.d(TAG, map.entrySet().toString());
Log.d(TAG, entry.toString());
if (entry.getValue() == null) {
criteriaMet = true;
Log.d("tag", entry.toString() + " is equal to null");
posted....
when I use this method the user goes to post it is posted four times and (skips the first null value the itterator identifies and posts on the remaining 4), if the user attempts to post again nothing, happens I don't think the variable is resetting but not sure
full code with the second method commented out i have a few other documents that i am also creating/writing to they are unrelated:
newPostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
currentDocument.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Map<String, Object> map = document.getData();
// while (criteriaMet == false) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
Log.d(TAG, map.entrySet().toString());
Log.d(TAG, entry.toString());
if (entry.getValue() == null) {
criteriaMet = true;
Log.d("tag", entry.toString() + " is equal to null");
postProgress.setTitle("Posting");
postProgress.setMessage("This Should Only Take A Second");
postProgress.setCanceledOnTouchOutside(false);
postProgress.show();
final String desc = newPostDesc.getText().toString();
if (!TextUtils.isEmpty(desc)) {
final String randomName = UUID.randomUUID().toString();
final StorageReference filePath = storageReference.child("post_images").child(randomName + ".jpeg");
filePath.putFile(postImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull final Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
File newImageFile = new File(Objects.requireNonNull(postImageUri.getPath()));
try {
compressedImageFile = new Compressor(NewPost.this)
.setMaxHeight(200)
.setMaxWidth(200)
.setQuality(10)
.compressToBitmap(newImageFile);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
compressedImageFile.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] thumbData = baos.toByteArray();
final UploadTask uploadTask = storageReference.child("post_images/thumbs").child(randomName + ".jpeg").putBytes(thumbData);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final String downloadUrl = uri.toString();
Log.d("tag", downloadUrl);
FirebaseUser current_user = FirebaseAuth.getInstance().getCurrentUser();
String uid = Objects.requireNonNull(current_user).getUid();
final Map<String, Object> postMap = new HashMap<>();
// No thumb ?????
postMap.put("image_url", downloadUrl);
postMap.put("desc", desc);
postMap.put("user_id", current_user_id);
postMap.put("message_doc", uid + postCategory);
postMap.put("timestamp", FieldValue.serverTimestamp());
firebaseFirestore.collection(postCategory).add(postMap).addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
#Override
public void onComplete(#NonNull Task<DocumentReference> task) {
if (task.isSuccessful()) {
firebaseFirestore.collection("Posts").add(postMap).addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
#Override
public void onComplete(#NonNull final Task<DocumentReference> task) {
FirebaseUser current_user = FirebaseAuth.getInstance().getCurrentUser();
String uid = Objects.requireNonNull(current_user).getUid();
final Map<String, String> chatMap = new HashMap<>();
postMap.put("timestamp", FieldValue.serverTimestamp());
postMap.put("name", current_user_id);
postMap.put("message", "");
firebaseFirestore.collection("Messages")
.document(uid + postCategory)
.set(chatMap)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
final String BlogPostID = Objects.requireNonNull(task.getResult()).getId();
String document_Id = current_user_id + postCategory;
final Map<String, String> usermap = new HashMap<>();
usermap.put("Owner", current_user_id);
usermap.put("debater", null);
firebaseFirestore.collection("Messages").document(document_Id)
.set(usermap)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
//write to active posts document
postProgress.dismiss();
Intent startIntent = new Intent(NewPost.this, MainActivity.class);
startActivity(startIntent);
}
});
}
});
}
});
}
}
});
}
});
}
}
});
}
} else {
Log.w(TAG, "the value is not null");
Toast.makeText(getApplicationContext(), "Too many active debates", Toast.LENGTH_LONG).show();
}
break;
}
// } //attached to while crit loop
}
}
}
});
}
});}
I have been working on this for a few days and I am stumped if any more info is required let me know.