
public class PostActivity extends AppCompatActivity {
private Toolbar mToolbar;
private ProgressDialog loadingBar;
private ImageButton selectPostImage;
private Button updatePostButton;
private EditText postDescription;
private static final int Gallery_Pick = 1;
private Uri imageUri;
private String description;
private String saveCurrentDate, saveCurrentTime, postRandomName, downloadUrl, current_user_id, specialKey;
private long countPosts = 0;
private StorageReference postsImageReference;
private DatabaseReference usersRef, postRef;
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
mAuth = FirebaseAuth.getInstance();
current_user_id = mAuth.getCurrentUser().getUid();
postsImageReference = FirebaseStorage.getInstance().getReference().child("Post Images");
usersRef = FirebaseDatabase.getInstance().getReference().child("Users");
postRef = FirebaseDatabase.getInstance().getReference().child("Posts");
selectPostImage = (ImageButton) findViewById(R.id.select_post_image);
updatePostButton = (Button) findViewById(R.id.update_post_button);
postDescription = (EditText) findViewById(R.id.post_description);
loadingBar = new ProgressDialog(this);
mToolbar = (Toolbar) findViewById(R.id.update_post_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Update Post");
selectPostImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
OpenGallery();
}
});
updatePostButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ValidatePostInfo();
}
});
}
private void ValidatePostInfo() {
description = postDescription.getText().toString();
if(imageUri==null){
Toast.makeText(this, "Please Select Post Image...", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(description)){
Toast.makeText(this, "Please Say Something About Your Image...", Toast.LENGTH_SHORT).show();
}
else {
loadingBar.setTitle("Adding New Post");
loadingBar.setMessage("Please Wait, While We Are Updating Your New Post...");
loadingBar.show();
loadingBar.setCanceledOnTouchOutside(true);
StoringImageToFirebaseStorage();
}
}
private void StoringImageToFirebaseStorage() {
Calendar calForDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
saveCurrentDate = currentDate.format(calForDate.getTime());
Calendar calForTime = Calendar.getInstance();
SimpleDateFormat currentTime = new SimpleDateFormat("hh:mm:ss");
saveCurrentTime = currentTime.format(calForDate.getTime());
postRandomName = saveCurrentDate + saveCurrentTime;
final StorageReference filePath = postsImageReference.child(imageUri.getLastPathSegment() + ".jpg");
filePath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
downloadUrl = uri.toString();
SavingPostInformationToDatabase();
}
});
}
});
}
private void SavingPostInformationToDatabase(){
usersRef.child(current_user_id).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
String userFullName = dataSnapshot.child("fullname").getValue().toString();
String userProfileImage = dataSnapshot.child("profileimage").getValue().toString();
HashMap postsMap = new HashMap();
postsMap.put("uid", current_user_id);
postsMap.put("date", saveCurrentDate);
postsMap.put("time", saveCurrentTime);
postsMap.put("description", description);
postsMap.put("postimage", downloadUrl);
postsMap.put("postprofileimage", userProfileImage);
postsMap.put("postfullname", userFullName);
postsMap.put("timestamp", getCurrentTimeStamp());
postRef.child(current_user_id + postRandomName).updateChildren(postsMap)
.addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if(task.isSuccessful()){
SendUserToMainActivity();
Toast.makeText(PostActivity.this, "New Post Updated Successfully.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else{
Toast.makeText(PostActivity.this, "ERROR Occurred While Updating Your Post.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
public class SettingsActivity extends AppCompatActivity {
private Toolbar mToolbar;
private EditText userName, userProfName, userStatus, userCountry, userGender, userRelation, userDOB;
private Button updateAccountSettingsButton;
private CircleImageView userProfImage;
private ProgressDialog loadingBar;
private DatabaseReference userRef, postRef;
private FirebaseAuth mAuth;
private StorageReference UserProfileImageRef;
private String downloadUrl;
private String currentUserId;
final static int Gallery_Pick = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mAuth = FirebaseAuth.getInstance();
currentUserId = mAuth.getCurrentUser().getUid();
userRef = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserId);
UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
postRef = FirebaseDatabase.getInstance().getReference().child("Posts").child(currentUserId);
loadingBar = new ProgressDialog(this);
mToolbar = (Toolbar) findViewById(R.id.settings_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Account Settings");// this is the back arrow bar
userName = (EditText) findViewById(R.id.settings_username);
userProfName = (EditText) findViewById(R.id.settings_profile_full_name);
userStatus = (EditText) findViewById(R.id.settings_status);
userCountry = (EditText) findViewById(R.id.settings_profile_country);
userGender = (EditText) findViewById(R.id.settings_gender);
userRelation = (EditText) findViewById(R.id.settings_relationship_status);
userDOB = (EditText) findViewById(R.id.settings_profile_dob);
userProfImage = (CircleImageView) findViewById(R.id.settings_profile_image);
updateAccountSettingsButton = (Button) findViewById(R.id.update_account_settings_button);
userRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
String myProfileImage = dataSnapshot.child("profileimage").getValue().toString();
String myUserName = dataSnapshot.child("username").getValue().toString();
String myProfileName = dataSnapshot.child("fullname").getValue().toString();
String myProfileStatus = dataSnapshot.child("status").getValue().toString();
String myDOB = dataSnapshot.child("dob").getValue().toString();
String myCountry = dataSnapshot.child("country").getValue().toString();
String myGender = dataSnapshot.child("gender").getValue().toString();
String myRelationStatus = dataSnapshot.child("relationshipstatus").getValue().toString();
Picasso.get().load(myProfileImage).placeholder(R.drawable.profile).into(userProfImage);
userName.setText(myUserName);
userProfName.setText(myProfileName);
userStatus.setText(myProfileStatus);
userDOB.setText(myDOB);
userCountry.setText(myCountry);
userGender.setText(myGender);
userRelation.setText(myRelationStatus);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
updateAccountSettingsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ValidateAccountInfo();
}
});
userProfImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, Gallery_Pick);
}
});
}
// In settings start this when a new pic is selected to replace the existing profile pic
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// some conditions for the picture
if(requestCode==Gallery_Pick && resultCode==RESULT_OK && data!=null)
{
Uri ImageUri = data.getData();
// crop the image
CropImage.activity(ImageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
}
// Get the cropped image
if(requestCode==CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{ // store the cropped image into result
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK)
{
loadingBar.setTitle("Profile Image");
loadingBar.setMessage("Please wait, while we updating your profile image...");
loadingBar.setCanceledOnTouchOutside(true);
loadingBar.show();
// Get the result of the image and store it in resultUri
Uri resultUri = result.getUri();
// Get a reference to the storage in Firebase. Its a filepath to the Firebase Storage
// Create a child and store to the user with a file type .jpg
final StorageReference filePath = UserProfileImageRef.child(currentUserId + ".jpg");
// Store the cropped image "resultUri" into the profile image's folder
filePath.putFile(resultUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
downloadUrl = uri.toString();
userRef.child("profileimage").setValue(downloadUrl).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
//Intent selfIntent = new Intent(SetupActivity.this, SetupActivity.class);
//startActivity(selfIntent);
Toast.makeText(SettingsActivity.this, "Image Stored", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else {
String message = task.getException().getMessage();
Toast.makeText(SettingsActivity.this, "Error:" + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
});
}
});
}
else
{
Toast.makeText(this, "Error Occured: Image can not be cropped. Try Again.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
У меня нет проблем с сохранением моих изображений и текста в Firebase, а затем обратно в мое приложение, когда я пишу сообщение. Однако, когда я решил создать класс настроек и позволить пользователю изменять изображение профиля, URL-адреса изображения, которые хранятся в каждом сообщении, не обновляются. Я не могу понять, как перейти к «Posts / uniqueID / postprofileimage». Я думал о том, чтобы избавиться от уникального идентификатора, а затем понял, что каждый новый пост будет перезаписывать старый пост. Мне нужно создать уникальный идентификатор, чтобы мои сообщения были уникальными, но я не могу понять, как обновить postprofileimage, когда я обновляю «Users / profileimage». Я попытался выяснить, как выполнять многозадачные обновления atomi c, но просто не могу понять это. Я новичок в Android Studio и Firebase. Я провел неделю в тупике и пришел сюда, прося чью-то помощь. Когда я обновляю изображение профиля в разделе «Пользователи», как мне обновить изображение для всех предыдущих сообщений, связанных с текущим пользователем? Кажется, моя проблема связана с уникальным идентификатором, который я создаю ("currentUserID" + дата + время). Я не могу понять, как добраться до .child (postprofileimage). Заранее спасибо. После устранения неполадок я понял, что при смене изображения новый URL-адрес не переносится на старые сообщения. Затем я понял, что мне нужно вручную обновить старые сообщения с новым URL-адресом изображения, но не могу понять, как это сделать. Все это ново для меня, и я не могу найти ни одного видео или поста, которые бы помогли мне это понять.