I'm trying to download data for my chat from Firebase database(structure of data is bellow and It is recommended structure from official Firebase web).
"chats": {
"one": {
"lastMessage": "ghopper: Relay malfunction found. Cause: moth.",
"timestamp": 1459361875666
},
"two": { ... }
},
"members": {
"one": {
"member1": "cxgF3EddyMWiYybXdMsYwu5YQsn1",
"member2": "jdxBDm5MXBdX4zfGoEp9hgHqscn2"
};
"two": {
"member1": "cxgF3EddyMWiYybXdMsYwu5YQsn1",
"member2": "yGpTEPDfChVmUeEkzvCCY6IjQnA2"
};
},
"messages": {
"one": {
"m1": {
"name": "cxgF3EddyMWiYybXdMsYwu5YQsn1",
"message": "The relay seems to be malfunctioning.",
"timestamp": 1459361875337
},
"m2": {
"name": "jdxBDm5MXBdX4zfGoEp9hgHqscn2",
"message": "Yes.",
"timestamp": 1459361875689
},
},
"two": { ... }
}
Now I'm trying just to check if I(as logged user) am involved in the conversation and download just the last message under chats/and particular chat number. Also I have to download a profile picture of another user that is involved in this chat and then add last message and this picture to PrefenceScreen.
Here is code:
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("members");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final ArrayList<String> arrayList = new ArrayList<>();
for (final DataSnapshot snapshot : dataSnapshot.getChildren()) {
GenericTypeIndicator<Map<String, Object>> m = new GenericTypeIndicator<Map<String, Object>>() {
};
Map<String, Object> map = snapshot.getValue(m);
if (map.get("member1").equals(myUID)) {
arrayList.add(snapshot.getKey());
arrayList.add(map.get("member2").toString());
} else if (map.get("member2").equals(myUID)) {
arrayList.add(snapshot.getKey());
arrayList.add(map.get("member1").toString());
}
}
mStorage = FirebaseStorage.getInstance().getReference();
for (int i=0, y=1; y<arrayList.size(); i+=2, y+=2) {
Log.i("Chat", arrayList.get(i));
StorageReference storageReference = mStorage.child("photos").child(arrayList.get(y));
try {
final File localFile = File.createTempFile("images", "jpg");
final int finalI = i;
StorageTask<FileDownloadTask.TaskSnapshot> taskSnapshotStorageTask = storageReference.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Bitmap bitmap = BitmapFactory.decodeFile(localFile.getAbsolutePath());
Resources res = getResources();
final RoundedBitmapDrawable dr =
RoundedBitmapDrawableFactory.create(res, Bitmap.createScaledBitmap(bitmap, 150, 150, false));
dr.setCornerRadius(500);
DatabaseReference myRef2 = database.getReference("chats").child(arrayList.get(finalI)).child("lastMessage");
myRef2.addValueEventListener(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String message = dataSnapshot.getValue(String.class);
Log.d("TAG", "Value is: " + message);
PreferenceScreen screen = getPreferenceManager().createPreferenceScreen(getActivity());
Preference preference = new Preference(getActivity());
preference.setTitle(message);
preference.setKey("Hej celkom v pohode");
preference.setIcon(dr);
preference.setSelectable(true);
preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Intent intent = new Intent(getActivity(), ScrollingActivity.class);
startActivity(intent);
return false;
}
});
screen.addPreference(preference);
setPreferenceScreen(screen);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("TAG", "Failed to read value.", error.toException());
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
});
} catch (IOException e ) {
}
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("TAG", "Failed to read value.", error.toException());
}
});
The code is almost doing what It should. The problem is that it all the time adds just one Prefence because the screen.addPreference(preference); and setPreferenceScreen(screen); methods are inside onDataChange. Is there a way how to use methods after files are downloaded?
And also I think this code is messy and there must by simplier way to download all the data. You would be very thankful if you can help me with this. Thanks.
Related
Here is my data structure.
"Posts" : {
"-MpVVpVIqmn0Iu78hDRp" : {
"description" : "",
"picture" : "",
"postKey" : "",
"reports" : 0,
"timeStamp" : 1638001760487,
"title" : "",
"userId" : "",
"userPhoto" : ""
},
"-MpVcioadtvRBRaa0n96" : {
"description" : "",
"picture" : "",
"postKey" : "",
"reports" : 0,
"timeStamp" : 1638003830234,
"title" : "",
"userId" : "",
"userPhoto" : ""
},
I want to access the "reports" part. So I use
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.child("Posts").child("reports").setValue(1);
But It creates reports value 1 right below Posts not below "-MpVVpVIqmn0Iu78hDRp" this.
I want to increment the report. But I don't know how can I approach to reports node.
Here is my full code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_detail);
imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
et = (EditText)findViewById(R.id.post_detail_comment);
// let's set the statue bar to transparent
// ini Views
RvComment = findViewById(R.id.rv_comment);
imgPost =findViewById(R.id.post_detail_img);
imgUserPost = findViewById(R.id.post_detail_user_img);
imgCurrentUser = findViewById(R.id.post_detail_currentuser_img);
txtPostTitle = findViewById(R.id.post_detail_title);
txtPostDesc = findViewById(R.id.post_detail_desc);
txtPostDateName = findViewById(R.id.post_detail_date_name);
editTextComment = findViewById(R.id.post_detail_comment);
btnAddComment = findViewById(R.id.post_detail_add_comment_btn);
btnDeletePost = findViewById(R.id.button_delete);
btnnoti = findViewById(R.id.button_noti);
btncommentnoti = findViewById(R.id.comment_noti);
firebaseAuth = FirebaseAuth.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
// add post delete button
mDatabase= FirebaseDatabase.getInstance().getReference();
myUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
//게시글 신고기능
btnnoti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.child("Posts").child("reports").setValue(1);
}
});
btnDeletePost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//여기 수정 주의 UId.equals(myUid)
if (true){
Toast.makeText(PostDetailActivity.this,"삭제중...",Toast.LENGTH_SHORT).show();
beginDelete();
onBackPressed();
}
}
});
// add Comment button click listener
btnAddComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btnAddComment.setVisibility(View.INVISIBLE);
DatabaseReference commentReference = firebaseDatabase.getReference(COMMENT_KEY).child(PostKey).push();
String comment_content = editTextComment.getText().toString();
String uid = firebaseUser.getUid();
String uname = firebaseUser.getDisplayName();
if (firebaseUser.getPhotoUrl()!=null){
String uimg = firebaseUser.getPhotoUrl().toString();
Comment comment = new Comment(comment_content,uid,uimg,uname);
commentReference.setValue(comment).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
showMessage("댓글이 등록되었습니다.");
editTextComment.setText("");
btnAddComment.setVisibility(View.VISIBLE);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
showMessage("fail to add comment : "+e.getMessage());
}
});
}
else{
String usphoto =Integer.toString(R.drawable.userphoto);
Comment comment = new Comment(comment_content,uid,usphoto,uname);
commentReference.setValue(comment).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
showMessage("comment added");
editTextComment.setText("");
btnAddComment.setVisibility(View.VISIBLE);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
showMessage("fail to add comment : "+e.getMessage());
}
});
}
}
});
// now we need to bind all data into those views
// first we need to get post data
// we need to send post detail data to this activity first ...
// now we can get post data
// 게시글 사진 백지 케이스
postImage = getIntent().getExtras().getString("postImage") ;
if(postImage!=null){
Glide.with(this).load(postImage).into(imgPost);
}
else{
Glide.with(this).load(R.drawable.whitepaper).into(imgPost);
}
String postTitle = getIntent().getExtras().getString("title");
txtPostTitle.setText(postTitle);
String userpostImage = getIntent().getExtras().getString("userPhoto");
if (userpostImage!=null){
Glide.with(this).load(userpostImage).into(imgUserPost);
}
else {
Glide.with(this).load(R.drawable.userphoto).into(imgUserPost);
}
String postDescription = getIntent().getExtras().getString("description");
txtPostDesc.setText(postDescription);
// set comment user image
if (firebaseUser.getPhotoUrl()!=null){
Glide.with(this).load(firebaseUser.getPhotoUrl()).into(imgCurrentUser);
}
else{
Glide.with(this).load(R.drawable.userphoto).into(imgCurrentUser);
}
// get post key
PostKey = getIntent().getExtras().getString("postKey");
String date = timestampToString(getIntent().getExtras().getLong("postDate"));
txtPostDateName.setText(date);
// get post uid
UId = getIntent().getExtras().getString("userId");
// ini Recyclerview Comment
iniRvComment();
}
private void beginDelete() {
//서버 관리용 개발자 옵션
if (myUid.equals("k1kn0JF5idhrMzuw46GarEIBgPw2")) {
long tlong = System.currentTimeMillis(); long ttime;
ttime = tlong - 3*24*60*60*1000;
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
Query queryByTimestamp = db.child("Posts").orderByChild("timeStamp").endAt(ttime);
queryByTimestamp.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
ds.getRef().removeValue();
Toast.makeText(PostDetailActivity.this,"게시글이 삭제되었습니다.",Toast.LENGTH_SHORT).show();
}
} else {
Log.d("TAG", task.getException().getMessage());
Toast.makeText(PostDetailActivity.this,"게시글이 삭제되지않았습니다.",Toast.LENGTH_SHORT).show();
}
}
});
}
else if (UId.equals(myUid)) {
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
Query queryByTimestamp = db.child("Posts").orderByChild("postKey").equalTo(PostKey);
queryByTimestamp.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
ds.getRef().removeValue();
Toast.makeText(PostDetailActivity.this, "게시글이 삭제되었습니다.", Toast.LENGTH_SHORT).show();
}
} else {
Log.d("TAG", task.getException().getMessage());
Toast.makeText(PostDetailActivity.this, "게시글이 삭제되지않았습니다.", Toast.LENGTH_SHORT).show();
}
}
});
}
else{
Toast.makeText(PostDetailActivity.this,"다른 사용자의 게시글입니다.",Toast.LENGTH_SHORT).show();
}
}
public void linearOnClick(View v) {
imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
}
private void iniRvComment() {
RvComment.setLayoutManager(new LinearLayoutManager(this));
DatabaseReference commentRef = firebaseDatabase.getReference(COMMENT_KEY).child(PostKey);
commentRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
listComment = new ArrayList<>();
for (DataSnapshot snap:dataSnapshot.getChildren()) {
Comment comment = snap.getValue(Comment.class);
listComment.add(comment) ;
}
commentAdapter = new CommentAdapter(getApplicationContext(),listComment);
RvComment.setAdapter(commentAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void showMessage(String message) {
Toast.makeText(this,message,Toast.LENGTH_LONG).show();
}
private String timestampToString(long time) {
Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
calendar.setTimeInMillis(time);
String date = DateFormat.format("yyyy-MM-dd",calendar).toString();
return date;
}
}
This is the part of my question
btnnoti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.child("Posts").child("reports").setValue(1);
}
});
I also tried orderbychild but I think it is not the right code.
This code:
rootRef.child("Posts").child("reports").setValue(1);
You're telling the database to set the value of /Posts/reports to 1, which is precisely what it then does.
If you want increment the current value of a node, you can use the atomic increment operation:
rootRef.child("Posts").child("reports").setValue(ServerValue.increment(1));
If you want to increment the reports property of a specific node under Posts, you will need to know the key of that node. For example:
rootRef.child("Posts/-MpVVpVIqmn0Iu78hDRp/reports").setValue(ServerValue.increment(1));
If you don't know the key of the node to increment, but do know some other value that uniquely (enough) identifies the node(s) to update, you can use a query to find the keys.
For example, to update all nodes with a specific postKey:
Query query = rootRef.child("Posts").orderByChild("postKey").equalTo("thePostKeyValue");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
postSnapshot.getReference().child("reports").setValue(ServerValue.increment(1));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
I am working on an app where I have uploaded images to Firebase, then I use a query to look for an image based on its name, I display it in an imageview, then I try to upload this image to a different table in the same firebase database.
My problem is that when I try to upload the image to the other table, I get a No content provider error, and in front of it is a fully working link to my image (I click on it and my image is displayed in the browser).
Here is the code that I have tried :
private void addToMenu(){
final Query query = mDatabaseRef.orderByChild("name").equalTo(EditTextName.getText().toString());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot NamedImage : dataSnapshot.getChildren()) {
SliderUtils sliderUtils = NamedImage.getValue(SliderUtils.class);
Uri uriFile = Uri.parse(sliderUtils.getImageUrl());
StorageReference Ref= menuStorageRef.child(System.currentTimeMillis()+"."+getPath(uriFile));
mStorageTask = Ref.putFile(uriFile)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setProgress(0);
}
}, 500);
Toast.makeText(MainActivity.this, "Image uploaded successfully.",
Toast.LENGTH_LONG).show();
SliderUtils sliderUtils = new SliderUtils(EditTextName.getText().toString().trim(),
taskSnapshot.getDownloadUrl().toString());
String uploadId = menuDatabaseRef.push().getKey();
menuDatabaseRef.child(uploadId).setValue(sliderUtils);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(MainActivity.this,"Image upload failed.",Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
progressBar.setProgress((int) progress);
}
});
}
}
}
the getPath() function is the following:
private String getPath(Uri uri){
ContentResolver cr = getContentResolver();
MimeTypeMap mimeTypeMap= MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(cr.getType(uri));
}
The error I get is :
/StorageException: StorageException has occurred.
An unknown error occurred, please check the HTTP result code and inner exception for server response.
Code: -13000 HttpResult: 0
E/StorageException: No content provider: https://firebase...
Do you have any idea where the problem is please?
for anyone in the same situation and looking for a solution:
A big mistake that I had is that I was trying to turn an URL into a URI which is simply impossible
So I decided to change the way that I was uploading my image altogether. Here is the code:
private void addToMenu(){
final Query query =
mDatabaseRef.orderByChild("name").equalTo(EditTextName.getText().toString());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot NamedImage : dataSnapshot.getChildren()) {
SliderUtils sliderUtils = NamedImage.getValue(SliderUtils.class);
StorageReference Ref= menuStorageRef.child("filename" + new Date().getTime());
image.setDrawingCacheEnabled(true);
image.buildDrawingCache();
Bitmap bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = Ref.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(MainActivity.this,"Image upload failed.",Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Image uploaded successfully.", Toast.LENGTH_LONG).show();
SliderUtils sliderUtils = new SliderUtils(EditTextName.getText().toString().trim(),
taskSnapshot.getDownloadUrl().toString());
String uploadId = menuDatabaseRef.push().getKey();
menuDatabaseRef.child(uploadId).setValue(sliderUtils);
}
});
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
When send user data to firestore and login again the system not read this code , he join already to (if) after add data but return failed because I think firestore accept write only is there any solution?
if (snapshot.exists()) {
return snapshot.getString("ID");
}
Code
FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
DocumentReference documentReference = firebaseFirestore.collection("Players").document(saveSystem.LoadStringData("LoginType").equals("Facebook") ? "F" + saveSystem.LoadStringData("ID") : "G" + saveSystem.LoadStringData("ID"));
firebaseFirestore.runTransaction(new Transaction.Function<Object>() {
#Override
public Object apply(Transaction transaction) throws FirebaseFirestoreException {
DocumentSnapshot snapshot = transaction.get(documentReference);
if (snapshot.exists()) {
return snapshot.getString("ID");
} else {
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("ID", saveSystem.LoadStringData("ID"));
return hashMap;
}
}
}).addOnSuccessListener(new OnSuccessListener<Object>() {
#Override
public void onSuccess(Object aObject) {
Toast.makeText(Test.this, "" + aObject, Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
Sorry for simple English language.
According to the documentation, we should avoid nesting data when it comes to database relationships. So I structured my data as follow:
{
"rides": {
"ride1": {
"price": "500",
"bids": {
// the value here doesn't matter, just that the key exists
"bid1": true,
"bid2": true
}
},
...
},
"bids": {
"bid1": {
"price": "550",
"ride": "ride1"
},
...
}
}
In one page of my app, the user should be able to see all "bids" that are linked to the selected "ride" in a ListView. My attempt was: Getting the keys of the bids in an arrayList and then fetching the bids by key on by one. My problem is the fact that I have to display all the bids in a listview at once.
bidsListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ArrayList<String> bidskeysOfActiveRideArrayList = new ArrayList<>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Boolean IsbidLinkedToThisRid = snapshot.getValue(Boolean.class);
if (IsbidLinkedToThisRid) {
String bidObjectId = dataSnapshot.getKey();
bidskeysOfActiveRideArrayList.add(bidObjectId);
}
}
fetchMultipleBidsByKeys(bidskeysOfActiveRideArrayList);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
databaseReference.child("rides").child(ride.getID()).child("bids").addValueEventListener(bidsListener);
The two functions are here:
private void fetchMultipleBidsByKeys(ArrayList<String> bidskeysOfActiveRideArrayList) {
ArrayList<Bid> bidsArrayList = new ArrayList<>();
for (String bid_id:bidskeysOfActiveRideArrayList){
bidsArrayList.add(getBidByKey(bid_id));
}
displayBidList(bidsArrayList);
}
private Bid getBidByKey(String bidObjectId) {
final Bid[] bidFetched = {null};
ValueEventListener bidsSingleFetcher = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
bidFetched[0] = snapshot.getValue(Bid.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
databaseReference.child("bids").child(bidObjectId).addListenerForSingleValueEvent(bidsSingleFetcher);
return bidFetched[0];
}
However, firebase data fetch is asyncronuous. So what is the correct way of fetching elements by a list of IDs then displaying them on a listview?
I am trying to verify if a username already exists in the Firebase DB and created a method to verify it.
The method should return true if the username is available and return false if the username is already taken.
public boolean isUsernameValid(final String newUsername, String oldUsername){
if(newUsername.equals(oldUsername)){
//if username is not changed
return true;
}else {
userValid = true;
databaseReference.orderByChild("Username").equalTo(newUsername).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long userCount = dataSnapshot.getChildrenCount();
if(userCount!=0){
userValid = false;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return userValid; //username is valid if this returns true
}
}
this method is returning UserValid boolean first and then it is querying the database. Please let me know if I missed something.
This is returning true first, and then searching the DB for username and hence, it is always Overwriting the username in the DB.
This method is called from here:
if(!TextUtils.isEmpty(str_firstName)
&& !TextUtils.isEmpty(str_lastName)
&& !TextUtils.isEmpty(str_username)
&& verify.isEmailValid(str_email)
&& verify.isMobileNoValid(str_mobile)
//here
&& verify.isUserNameValid(str_username, globalSharedPrefs.getUserDetail("username").toString())){
progressDialog.setMessage("Saving Profile ...");
progressDialog.show();
//saving the photo
if(isImageClicked) {
filepath = storageReference.child("profile_photos").child(globalSharedPrefs.getUserDetail("uid").toString());
filepath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//TODO: add picture remote/edit button in the XML
isImageClicked = false;
downloadUri = taskSnapshot.getDownloadUrl();
databaseReference.child("Profile Picture").setValue(downloadUri.toString());
uploadUserInfo();
Toast.makeText(UserProfileActivity.this, "Profile Saved.!", Toast.LENGTH_LONG)
.show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
updateProfileUI();
clickEditProfileButton(false);
Toast.makeText(UserProfileActivity.this, "Update Failed.!", Toast.LENGTH_LONG)
.show();
}
});
}
Database Structure
{
"userinfo" : {
"J6Y4Dtxe7Nh45B653U5AVXHFrSJ2" : {
"AccountId" : "",
"DOB" : "21 Jun, 2017",
"First Name" : "Krishna",
"Last Name" : "kk",
"Mobile" : "",
"Username" : "kittuov",
"uid" : "J6Y4Dtxe7Nh45B653U5AVXHFrSJ2"
},
"ck8x94FeHtUbC9DgHCkxmQt93Ar1" : {
"AccountId" : "",
"DOB" : "7 Dec, 1992",
"First Name" : "Seshagiri Rao",
"Last Name" : "Kornepati",
"Mobile" : "",
"Username" : "seshu1",
"uid" : "ck8x94FeHtUbC9DgHCkxmQt93Ar1"
},
"iDBn0lYIZFSgll9KyVje0T6JFIy2" : {
"AccountId" : "",
"DOB" : "",
"First Name" : "Ramesh",
"Last Name" : "Devarapu",
"Mobile" : "",
"Username" : "rameshb",
"uid" : "iDBn0lYIZFSgll9KyVje0T6JFIy2"
}
}
Try this
if(str_username.equals(globalSharedPrefs.getUserDetail("username").toString()))){
sumbit();
}else {
databaseReference.orderByChild("Username").equalTo(newUsername).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long userCount = dataSnapshot.getChildrenCount();
if(userCount==0){
sumbit();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
private void sumbit(){
if(!TextUtils.isEmpty(str_firstName)
&& !TextUtils.isEmpty(str_lastName)
&& !TextUtils.isEmpty(str_username)
&& verify.isEmailValid(str_email)
&& verify.isMobileNoValid(str_mobile)
){
progressDialog.setMessage("Saving Profile ...");
progressDialog.show();
//saving the photo
if(isImageClicked) {
filepath = storageReference.child("profile_photos").child(globalSharedPrefs.getUserDetail("uid").toString());
filepath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//TODO: add picture remote/edit button in the XML
isImageClicked = false;
downloadUri = taskSnapshot.getDownloadUrl();
databaseReference.child("Profile Picture").setValue(downloadUri.toString());
uploadUserInfo();
Toast.makeText(UserProfileActivity.this, "Profile Saved.!", Toast.LENGTH_LONG)
.show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
updateProfileUI();
clickEditProfileButton(false);
Toast.makeText(UserProfileActivity.this, "Update Failed.!", Toast.LENGTH_LONG)
.show();
}
});
}
}