相关活动未关闭

时间:2018-10-07 13:18:48

标签: android android-activity activity-finish

我有一些奇怪的情况:

我有3个活动-MainFeed,可以在其中发布一些带有说明的图片,然后对其进行评论, PostActivity,从这里我实际上传图像并写一些单词,然后在MainFeed中自动更新 CommentActivity,从这里我只在相关帖子中写评论。

问题是-当我仅滚动查看帖子并单击以写评论并写一个时-一切都已被更新,但是一旦我上传了新的POST,然后在单击“更新评论”按钮时对任何帖子发表了评论我刚刚移到Postactivity ...我需要单击android后退按钮,然后才能看到我的所有评论。

据我了解,后期活动不会使用finish()方法关闭。

任何帮助,请!!

package com.example.android.bluesky.Posts;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.android.bluesky.Login.LoginActivity;
import com.example.android.bluesky.Login.RegisterActivity;
import com.example.android.bluesky.R;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;

import de.hdodenhof.circleimageview.CircleImageView;

import static java.nio.file.Paths.get;

public class CommentsActivity  extends AppCompatActivity
{
    private ImageView PostCommentButton,BackButton;
    private EditText CommentInputText;
    private RecyclerView CommentsList;

    private String Post_Key, current_user_id;
    private long countPosts;

    private DatabaseReference UsersRef,PostsRef;
    private FirebaseAuth mAuth;
    private String currentUserID, CommentRandomKey,post_user_uid_for_comment;
    private int PostIntKeyFromMain;


    private String comment_user_uid;



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comments);





        Post_Key=getIntent().getExtras().get("Post_Key").toString();
        PostIntKeyFromMain =getIntent().getIntExtra("PostIntKey",5);
        post_user_uid_for_comment=getIntent().getExtras().get("post_user_uid_for_comment").toString(); //Coming from mainfeed - commentPostButton
        Toast.makeText(this, "received: "+post_user_uid_for_comment, Toast.LENGTH_SHORT).show();


        UsersRef= FirebaseDatabase.getInstance().getReference().child("users");
        mAuth=FirebaseAuth.getInstance();
        current_user_id=mAuth.getCurrentUser().getUid();
        currentUserID = mAuth.getCurrentUser().getUid();
        PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts").child(Post_Key).child("comments");

        BackButton=(ImageView) findViewById(R.id.backArrow) ;

        CommentsList = (RecyclerView) findViewById(R.id.comment_list);
        CommentsList.setHasFixedSize(true);
        LinearLayoutManager linearLayoutManager= new LinearLayoutManager(this);
        linearLayoutManager.setReverseLayout(true);
        linearLayoutManager.setStackFromEnd(true);
        CommentsList.setLayoutManager(linearLayoutManager);


        CommentInputText=(EditText) findViewById(R.id.comment_input);
        PostCommentButton=(ImageView) findViewById(R.id.post_comment_button1);

        BackButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(CommentsActivity.this,MainFeedActivity.class);
                intent.putExtra("PostIntKeyFromComment", PostIntKeyFromMain);
                startActivity(intent);
                finish();
            }
        });

        PostCommentButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view)
            {
                UsersRef.child(current_user_id).addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        if(dataSnapshot.exists())
                        {
                            String userFullname=dataSnapshot.child("name").getValue().toString().toLowerCase()+"."+dataSnapshot.child("lastname").getValue().toString();

                           String userProfileimage=dataSnapshot.child("profileimage").getValue().toString();




                            ValidateComment(userFullname,userProfileimage);

                            CommentsList.smoothScrollToPosition(0);


                            CommentInputText.setText("");


                        }
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });

            }
        });
    }



    @Override
    protected void onStart()
    {
        super.onStart();

        PostsRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()) {
                    countPosts = dataSnapshot.getChildrenCount();
                    countPosts=100000-countPosts;
                } else {
                    countPosts = 100000;
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });




        Query SortCommentsInDecendingOrder = PostsRef.orderByChild("counterC");

        FirebaseRecyclerAdapter<Comments,CommentsViewHolder> firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<Comments, CommentsViewHolder>
                (
                        Comments.class,
                        R.layout.all_comments_layout,
                        CommentsViewHolder.class,
                        SortCommentsInDecendingOrder
                ) {
            @Override
            protected void populateViewHolder(CommentsViewHolder viewHolder, Comments model, int position)
            {

                final String CommentKey = getRef(position).getKey();


                //viewHolder.setUsername(model.getUsername());
                viewHolder.setComment(model.getComment());
                viewHolder.setDate(model.getDate());
                viewHolder.setTime(model.getTime());
                viewHolder.setLastname(model.getLastname());
                viewHolder.setProfileimage(model.getProfileimage());






            }
        };


        CommentsList.setAdapter(firebaseRecyclerAdapter);
    }

    public static class CommentsViewHolder extends RecyclerView.ViewHolder
    {

        View mView;


        String currentUserID;






        public CommentsViewHolder(View itemView) {
            super(itemView);

            mView=itemView;

            currentUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
        }



        public void setLastname(String lastname)
        {
            TextView myUserName=(TextView) mView.findViewById(R.id.comment_username1);
            myUserName.setText("@ " + lastname);
        }

        public void setComment(String comment)
        {
            TextView myComment=(TextView) mView.findViewById(R.id.comment_text);
            myComment.setText(comment);
        }

        public void setDate(String date)
        {
            TextView myDate=(TextView) mView.findViewById(R.id.comment_date);
            myDate.setText(date);
        }

        public void setTime(String time)
        {

            TextView myTime=(TextView) mView.findViewById(R.id.comment_time);
            myTime.setText(time);
        }

        public void setProfileimage(String profileimage) {
            CircleImageView myProfileImage = (CircleImageView) mView.findViewById(R.id.comment_profile_image);
            Picasso.get().load(profileimage).into(myProfileImage);
       }



    }



    private void ValidateComment(String userFullname, String userProfileimage, String userCountryimage,String userPartyimage )
    {
        String commentText=CommentInputText.getText().toString();
        if(TextUtils.isEmpty(commentText))
        {
            Toast.makeText(this, "Please write text", Toast.LENGTH_SHORT).show();
        }
        else
        {
            Calendar calForDate = Calendar.getInstance();
            SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
            final String saveCurrentDate = currentDate.format(calForDate.getTime());

            Calendar calForTimeSS = Calendar.getInstance();
            SimpleDateFormat currentTimeSS = new SimpleDateFormat("HH:mm:ss");
            final String saveCurrentTimeSS = currentTimeSS.format(calForDate.getTime());

            Calendar calForTime = Calendar.getInstance();
            SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm");
            final String saveCurrentTime = currentTime.format(calForDate.getTime());


            final String RandomKey =current_user_id+ saveCurrentDate + saveCurrentTimeSS;

            CommentRandomKey=RandomKey;

            HashMap commentsMap = new HashMap();
            commentsMap.put("uid",current_user_id);
            commentsMap.put("comment",commentText);
            commentsMap.put("date",saveCurrentDate);
            commentsMap.put("time",saveCurrentTime);
            commentsMap.put("lastname",userFullname);
            commentsMap.put("counterC", countPosts);
            commentsMap.put("profileimage", userProfileimage);




            PostsRef.child(RandomKey).updateChildren(commentsMap).addOnCompleteListener(new OnCompleteListener()
            {
                @Override
                public void onComplete(@NonNull Task task) {
                    if(task.isSuccessful())
                    {
                        Toast.makeText(CommentsActivity.this, "You have commented successfully", Toast.LENGTH_SHORT).show();
                    }
                    else
                    {
                        Toast.makeText(CommentsActivity.this, "Error occured, try again...", Toast.LENGTH_SHORT).show();
                    }
                }
            });




            CommentsList.smoothScrollToPosition(0);
           // Toast.makeText(CommentsActivity.this, ""+CurrentCommentKey, Toast.LENGTH_SHORT).show();


        }
    }
}






package com.example.android.bluesky.Posts;
import java.lang.Math;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.android.bluesky.R;
import com.example.android.bluesky.Utils.SquareImageView;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;

import de.hdodenhof.circleimageview.CircleImageView;


public class PostActivity extends AppCompatActivity {

    private Toolbar mToolbar;
    private ProgressDialog loadingBar;

    //private ImageButton SelectPostImage;
    private SquareImageView SelectPostImage;
    private FloatingActionButton DonePostButton;
    private FloatingActionButton UpdatePostButton;
    private EditText PostDescription;
    private long countPosts;
    ImageView PartyImage;

    private static final int Gallery_Pick = 1;
    private Uri ImageUri;
    private String Description;

    //referense to store in firebase storage
    private StorageReference PostsImagesReference;
    private DatabaseReference UsersRef, PostsRef;
    private FirebaseAuth mAuth;

    private String saveCurrentDate, saveCurrentTime,saveCurrentTimeS, postRandomName, downloadUrl, current_user_id;


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post);

        //This two lines is to get current user from database
        mAuth = FirebaseAuth.getInstance();
        current_user_id = mAuth.getCurrentUser().getUid();


        PostsImagesReference = FirebaseStorage.getInstance().getReference();
        UsersRef = FirebaseDatabase.getInstance().getReference().child("users");
        PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");
        UserPhotosRef=FirebaseDatabase.getInstance().getReference().child("user_photos");
        PhotosRef=FirebaseDatabase.getInstance().getReference().child("photos");


        DonePostButton = (FloatingActionButton) findViewById(R.id.done_post_button);
        SelectPostImage = (SquareImageView) findViewById(R.id.select_post_image);
        UpdatePostButton = (FloatingActionButton) findViewById(R.id.update_post_button);
        PostDescription = (EditText) findViewById(R.id.post_description);

        PartyImage=(ImageView) findViewById(R.id.user_party_flag);

        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");



                UpdatePostButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onSelectImageClick(SelectPostImage);
                //  OpenGallery();
            }
        });

        //UpdatePostButton.setOnClickListener(new View.OnClickListener() {
        DonePostButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ValidatePostInfo();
            }
        });


    }


    public void onSelectImageClick(View view) {
        CropImage.activity()
                .setGuidelines(CropImageView.Guidelines.ON)
                .setActivityTitle("My Crop")
                //.setCropShape(CropImageView.CropShape.RECTANGLE)
                .setCropMenuCropButtonTitle("Done")
                //.setMaxCropResultSize(1000, 1000)
                .setMinCropWindowSize(2000, 2000)
                .setMinCropResultSize(2000, 2000)
                .setRequestedSize(800, 800)
                .setAspectRatio(1,1)
                .setCropMenuCropButtonIcon(R.drawable.ic_checkmark)
                .start(this);

        //.startActivityForResult(galleryIntent,Gallery_Pick);
        // / .start(getContext(),this);
    }

    private void ValidatePostInfo() {
        //This Description var is using only in this method, there is another one for global use
        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("Add new post");
            loadingBar.setMessage("Please wait, while we are updating your new post...");
            loadingBar.show();
            loadingBar.setCanceledOnTouchOutside(true);
            //Code for storing image in firebase storage and database
            StoringImageToFirebaseStorage();
        }
    }

    private void StoringImageToFirebaseStorage() {
        //assigning random uid for image based on date and time
        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");
        saveCurrentTime = currentTime.format(calForDate.getTime());

        Calendar calForTimeS = Calendar.getInstance();
        SimpleDateFormat currentTimeS = new SimpleDateFormat("HH:mm:ss");
        saveCurrentTimeS = currentTime.format(calForDate.getTime());

        postRandomName = saveCurrentDate + saveCurrentTimeS;

        StorageReference filepath = PostsImagesReference.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");
        //Now let's store the image to firebase storage
        filepath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                if (task.isSuccessful()) {
                    downloadUrl = task.getResult().getDownloadUrl().toString();
                    Toast.makeText(PostActivity.this, "Image uploaded successfully to Storage", Toast.LENGTH_SHORT).show();

                    SavingPostInformationToDatabase();
                } else {
                    String message = task.getException().getMessage();
                    Toast.makeText(PostActivity.this, "Error occured: " + message, Toast.LENGTH_SHORT).show();
                }


            }

        });


    }

    private void SavingPostInformationToDatabase()
    {
        PostsRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()) {
                    countPosts = dataSnapshot.getChildrenCount();
                  //  countForPhotos="photo_"+countPosts;
                } else {
                    countPosts = 0;
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });




        UsersRef.child(current_user_id).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()) {
                    //Two lines of code to retreive and assign to var the users fullname and uid of it profile image
                    String userFullName = "@" + dataSnapshot.child("name").getValue().toString().toLowerCase() + "." + dataSnapshot.child("lastname").getValue().toString();
                    String userProfileImage = dataSnapshot.child("profileimage").getValue().toString();


                    //Creating database for storing user posts data including users data
                    HashMap postsMap = new HashMap();
                    postsMap.put("uid", current_user_id);
                    postsMap.put("description", Description);
                    postsMap.put("postimage", downloadUrl);
                    postsMap.put("profileimage", userProfileImage);
                    postsMap.put("fullname", userFullName);
                    postsMap.put("counter", countPosts);




                    //Updating database of users post photo only
                    UserPhotosRef.child(current_user_id).child(current_user_id + postRandomName).updateChildren(postsMap_users_photo);




                    PostsRef.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, "The post is updated successfully!", Toast.LENGTH_SHORT).show();
                                        loadingBar.dismiss();
                                        finish();
                                    } else {
                                        Toast.makeText(PostActivity.this, "Error occurred while updating your post!", Toast.LENGTH_SHORT).show();
                                        loadingBar.dismiss();
                                    }
                                }
                            });

                } else {

                    String userFullName = dataSnapshot.child("lastname").getValue().toString();
                    Toast.makeText(PostActivity.this, "You have a problem!!!  " + userFullName, Toast.LENGTH_SHORT).show();

                }




}

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == RESULT_OK)
            {
                SelectPostImage.setImageURI(result.getUri());
                Toast.makeText(this, "Cropping successful, Sample: " + result.getSampleSize(), Toast.LENGTH_LONG)
                        .show();
                Uri resultUri = result.getUri();
                ImageUri = resultUri;
            }
            else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                Toast.makeText(this, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show();
            }
        }
    }


    private void SendUserToMainActivity() {
        Intent intent = new Intent(PostActivity.this, MainFeedActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
    }


}

1 个答案:

答案 0 :(得分:0)

问题出在Firebase初始化中的sendActivity ...