2

The problem I am having now is that the only way a post can be removed is when I click on the post at the exact time of expiry. When the expiry time has exceeded without me clicking on the post, the post will not be removed. What I want is for the post to be automatically removed from the database when the expiry time has reached regardless of whichever activity the user will be at. Is there a way I can get around it? Below is a snapshot of my database and the codes used to retrieve data from my database into my homepage activity and single post activity

Database

HomePage Activity

@Override
    protected void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
        final String key = "";

        Query query = FirebaseDatabase.getInstance().getReference("Posts").limitToLast(50);
        FirebaseRecyclerOptions<Post> options = new FirebaseRecyclerOptions.Builder<Post>().setQuery(query,Post.class).build();

        FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(options){
            @Override
            public PostViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_row,parent,false);
                return new PostViewHolder(view);
            }
            @Override
            protected void onBindViewHolder(PostViewHolder holder, int position, Post model){
                final String post_key = getRef(position).getKey();

                holder.setLocation("Location: " + model.getLocation());
                holder.set_foodAvailable("Food Available: " + model.getFood_Available());
                holder.setImage(model.getImage());
                holder.set_foodExpiry("Food Expires At: " + model.getFood_Expiry() + "hrs");
                holder.setCounter("Interested Parties: " + model.getCounter());
                holder.setUsername("Posted by: " + model.getUsername());

                holder.mView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //Toast.makeText(MainActivity.this,post_key, Toast.LENGTH_SHORT).show();
                        Intent singlePostIntent = new Intent(HomeActivity.this, SingleActivity.class);
                        singlePostIntent.putExtra("post_id", post_key);
                        startActivity(singlePostIntent);
                        ((SimpleItemAnimator) mPostList.getItemAnimator()).setSupportsChangeAnimations(false);
                    }
                });
                if(key == post_key){
                    mDatabaseTest = mDatabase.child(key);
                    mDatabaseTest.addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                            String expiry = (String) dataSnapshot.child("Food_Expiry").getValue();
                            SimpleDateFormat format = new SimpleDateFormat("HH:mm", Locale.ENGLISH);
                            try {
                                Date currentDate = format.parse(time);
                                Date expiryDate = format.parse(expiry);
                                assert currentDate != null;
                                if(!currentDate.before(expiryDate) || currentDate.after(expiryDate)){
                                    mDatabaseTest.removeValue();
                                }
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError databaseError) {

                        }
                    });
                }
            }
        };

        adapter.startListening();
        mPostList.setAdapter(adapter);
    }

Single Post Activity

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

        mSingleImage = findViewById(R.id.single_image);
        mSingleEventName = findViewById(R.id.single_eventName);
        mSingleLocation = findViewById(R.id.single_Location);
        mSingleMoreDetails = findViewById(R.id.single_moreDetails);
        mSingleFoodAvailable = findViewById(R.id.single_foodAvailable);
        mSingleDietaryOptions = findViewById(R.id.single_dietaryOptions);
        mSingleEstimatedPaxAvailability = findViewById(R.id.single_estimatedPaxAvailability);
        mSingleFoodExpiry = findViewById(R.id.single_foodExpiry);
        removeBtn = findViewById(R.id.removeButton);
        mSingleUsername = findViewById(R.id.single_username);

        mCounterView = findViewById(R.id.single_counter);
        counterBtn = findViewById(R.id.counterButton);

        mDatabaseTest = FirebaseDatabase.getInstance().getReference();
        mDatabase = FirebaseDatabase.getInstance().getReference().child("Posts");
        mAuth = FirebaseAuth.getInstance();

        mPost_key = getIntent().getExtras().getString("post_id");
        //Values that you want to retrieve
        mDatabase.child(mPost_key).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                String post_uid = (String) dataSnapshot.child("Uid").getValue();
                String post_image = (String) dataSnapshot.child("Image").getValue();
                String post_eventName = (String) dataSnapshot.child("Event_Name").getValue();
                String post_location = (String) dataSnapshot.child("Location").getValue();
                String post_moreDetails = (String) dataSnapshot.child("More_Details_On_Location").getValue();
                String post_foodAvailable = (String) dataSnapshot.child("Food_Available").getValue();
                String post_username = (String) dataSnapshot.child("Username").getValue();

                post_click = (String) dataSnapshot.child("Clicked").getValue();

                post_counter = (String) dataSnapshot.child("Counter").getValue();
                mCounterView.setText("Interested Parties: " + post_counter);

                ArrayList<String> names = new ArrayList<String>();
                StringBuffer sb = new StringBuffer();
                for(DataSnapshot s : dataSnapshot.child("Dietary_Options").getChildren()){
                    names.add(s.getValue().toString());
                }
                Log.d("tag","value" + names.size());
                for(String a : names) {
                    sb.append(a);
                    sb.append(", ");
                }
                String str = sb.toString();
                str = str.replaceAll(", $", "");
                mSingleDietaryOptions.setText("Dietary Options: " + str);

                String post_estimatedPaxAvailability = (String) dataSnapshot.child("Estimated_Pax_Availability").getValue();
                String post_foodExpiry = (String) dataSnapshot.child("Food_Expiry").getValue();

                mSingleEventName.setText("Event Name: " + post_eventName);
                mSingleLocation.setText("Location: " + post_location);
                mSingleMoreDetails.setText("More Details On Location: " + post_moreDetails);
                mSingleFoodAvailable.setText("Food Available: " + post_foodAvailable);
                mSingleEstimatedPaxAvailability.setText("Estimated Pax Available: " + post_estimatedPaxAvailability);
                mSingleFoodExpiry.setText("Food Expires At: " + post_foodExpiry + "hrs");
                mSingleUsername.setText("Posted By: " + post_username);

                Picasso.get().load(post_image).into(mSingleImage);

                if(mAuth.getCurrentUser().getUid().equals(post_uid)){
                    removeBtn.setVisibility(View.VISIBLE); //check that only user that post the location can remove the post
                }

                ArrayList<String> users = new ArrayList<String>();
                for(DataSnapshot a : dataSnapshot.child("Users_Interested").getChildren()){
                    users.add(a.getValue().toString());
                }

                Calendar calendar = Calendar.getInstance();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
                final String time = simpleDateFormat.format(calendar.getTime());
                if(time.equals(post_foodExpiry)){
                    mDatabase.child(mPost_key).removeValue();
                }
                //check to see if current user has already clicked the button
                if(mAuth.getCurrentUser().getUid().equals(post_click) || users.contains(mAuth.getCurrentUser().getUid())){
                    counterBtn.setEnabled(false);
                    counterBtn.setText("Confirmed!");
                    Log.i("testing",mPost_key);
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

        counterBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAlertDialog();
            }
        });

        removeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDatabase.child(mPost_key).removeValue();
                Intent mainIntent = new Intent(SingleActivity.this, HomeActivity.class);
                startActivity(mainIntent);
            }
        });
    }
Shaun .C
  • 31
  • 5
  • Take a look, how to ask a good question: https://stackoverflow.com/help/how-to-ask – Marsad May 03 '20 at 02:37
  • Post your code instead of images. – Marsad May 03 '20 at 02:37
  • I have posted my code – Shaun .C May 03 '20 at 04:28
  • ```if(time.equals(post_foodExpiry)){ mDatabase.child(mPost_key).removeValue(); }``` you are comparing time, what if the user is not using app at that time, check something like if time equals to expiry time or if exceeded than remove the entry – Marsad May 03 '20 at 05:16
  • How do I check if the time has exceeded? Because I have saved my expiry as a String so I'm not sure how I can go about comparing it. – Shaun .C May 03 '20 at 05:25

2 Answers2

1

To convert String to Date

SimpleDateFormat format = new SimpleDateFormat("HH:mm", Locale.ENGLISH);

Date currentDate = format.parse(time);
Date expiryDate = format.parse(post_foodExpiry);

To check

assert currentDate != null;
if (!currentDate.before(expiryDate) || currentDate.after(expiryDate)){
     //here to remove value
     mDatabase.child(mPost_key).removeValue();

}

Update

mDatabase = FirebaseDatabase.getInstance().getReference().child("Posts");

        mDatabase.child(mPost_key).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                String post_foodExpiry = (String) dataSnapshot.child("Food_Expiry").getValue();

                SimpleDateFormat format = new SimpleDateFormat("HH:mm", Locale.ENGLISH);

                Date currentDate = format.parse(time);
                Date expiryDate = format.parse(post_foodExpiry);


                assert currentDate != null;
                if (!currentDate.before(expiryDate) || currentDate.after(expiryDate)) {
                    //here to remove value
                    //mDatabase.child(mPost_key).removeValue();
                    mDatabase.child(mPost_key).getRef().removeValue();

                }

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

Update 2

@Override
    protected void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);

        Query query = FirebaseDatabase.getInstance().getReference("Posts").limitToLast(50);
        FirebaseRecyclerOptions<Post> options = new FirebaseRecyclerOptions.Builder<Post>().setQuery(query,Post.class).build();

        FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(options){
            @Override
            public PostViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_row,parent,false);
                return new PostViewHolder(view);
            }
            @Override
            protected void onBindViewHolder(PostViewHolder holder, int position, Post model){
                final String post_key = getRef(position).getKey();


                holder.setLocation("Location: " + model.getLocation());
                holder.set_foodAvailable("Food Available: " + model.getFood_Available());
                holder.setImage(model.getImage());
                holder.set_foodExpiry("Food Expires At: " + model.getFood_Expiry() + "hrs");
                holder.setCounter("Interested Parties: " + model.getCounter());
                holder.setUsername("Posted by: " + model.getUsername());

                holder.mView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //Toast.makeText(MainActivity.this,post_key, Toast.LENGTH_SHORT).show();
                        Intent singlePostIntent = new Intent(HomeActivity.this, SingleActivity.class);
                        singlePostIntent.putExtra("post_id", post_key);
                        startActivity(singlePostIntent);
                        ((SimpleItemAnimator) mPostList.getItemAnimator()).setSupportsChangeAnimations(false);
                    }
                });

                String test = mDatabase.child(post_key).getRef().toString();
                mDatabase.child(post_key).addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        String expiry = (String) dataSnapshot.child("Food_Expiry").getValue();

                        Calendar calendar = Calendar.getInstance();
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm", Locale.ENGLISH);
                        final String time = simpleDateFormat.format(calendar.getTime());
                        //Log.i("expiry",expiry);
                        SimpleDateFormat format = new SimpleDateFormat("HH:mm", Locale.ENGLISH);

                        try {
                            Date currentDate = format.parse(time);
                            assert expiry != null;
                            Date expiryDate = format.parse(expiry);
                            assert currentDate != null;
                            if (!currentDate.before(expiryDate) || currentDate.after(expiryDate)) {
                                mDatabase.child(post_key).getRef().removeValue();
                                Log.i("remove", "please");
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {

                    }
                });
                Log.i("test",test);
            }
        };

        adapter.startListening();
        mPostList.setAdapter(adapter);
    }

Marsad
  • 859
  • 1
  • 14
  • 35
  • But where should I insert it if I want to put it in my HomeActivity because currently if I were to insert this code into the SingleActivity class the posts gets remove only if the user goes into the activity. Is it possible for the posts to automatically be deleted in the HomeActivity class as well? – Shaun .C May 03 '20 at 07:37
  • yes, if you want to remove post in HomeActivity just query data, I mean check the time in HomeActivity. If post is expired so the post will deleted. – Marsad May 03 '20 at 09:28
  • I have updated my answer, add this in your ```HomeActivity``` – Marsad May 03 '20 at 09:38
  • I have edited my HomeActivity in my question with your code but my logcat is giving me 'Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference'. I don't have mPost_key in my HomeActivity as I am starting an Activity and retrieving the key in SinglePostActivity. Is there any way around it? – Shaun .C May 03 '20 at 10:08
  • To get post_key```String post_key = getRef(position).getKey();``` – Marsad May 03 '20 at 10:17
  • if you want to get ```post_key``` add a ```String key = ""```; in ```onStart``` below ```mAuth.addAuthS...```. and in ```query``` just compare ```key = post_key;``` this will give you the value and put ```key``` in ```mDatabase.child(key)...``` – Marsad May 03 '20 at 10:21
  • I tried but it does not seem to work. As I am using a push() id in my HomeActivity I can only use for(DataSnapshot ds : dataSnapshot.getChildren()) and after that using ds.getKey() to retrieve the keys. Just to check I am supposed to add your code into my onStart() method right? – Shaun .C May 03 '20 at 10:26
  • I have edited my code in my HomeActivity in my question, although I am not getting any crashes or error the post is still not getting deleted after the time has been met. Can you help me check to see where did I go wrong? – Shaun .C May 03 '20 at 11:17
  • ```mDatabase.child(mPost_key).getRef().removeValue();``` use this to delete – Marsad May 03 '20 at 12:59
  • Sorry if I'm asking too much cause I'm still really new to android studios. But I'm still not able to delete the post. My main problem now is getting the post key as my HomeActivity do not have the variable mPost_key. I tried adding String key="" but problem is if I were to compare key=post_key in the onBindViewHolder I will have to declare final String key="" in the onStart method. Really need some help here. – Shaun .C May 04 '20 at 02:34
  • I've uploaded my current code and problem lies with Date expiryDate = format.parse(expiry); my logcat is giving me 'java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference' and my app just crash but when I restart my app, the post gets remove. Any idea why this is happening? – Shaun .C May 04 '20 at 03:26
  • ``` 'int java.lang.String.length()' on a null object reference'``` this means you're getting null. I suggest you to fist check for null and then proceed. – Marsad May 05 '20 at 04:02
  • If you are still facing the issue, I just updated my answer. try this – Marsad May 05 '20 at 04:20
  • My app is still crashing and the main problem still lies with this line 'Date expiryDate = format.parse(expiry);' Is there a reason why? – Shaun .C May 05 '20 at 07:02
  • This is because you are getting null from server – Marsad May 05 '20 at 07:21
  • https://stackoverflow.com/questions/8573250/android-how-can-i-convert-string-to-date – Marsad May 05 '20 at 07:31
  • So the problem lies with the converting of the String to a Date? Is there a way I can solve cause they are using SimpleDateFormat as well and it wasn't working for me. Really need some help with this. – Shaun .C May 05 '20 at 09:01
  • Let's continue our discussion in chat room: https://chat.stackoverflow.com/rooms/213148/marsad – Marsad May 05 '20 at 10:00
  • Hi I'm really sorry but I can't chat in the chat room as I do not have 20 reputations. Can we chat on facebook or any other platforms? – Shaun .C May 05 '20 at 10:17
  • Now when the expiry has reached and if I transit to another activity and back to my homepage it seems like the app restarts by itself and the post gets removed, should it be this way that the app is restarting by itself? – Shaun .C May 05 '20 at 10:34
  • Let's continue our discussion [WA](https://wa.me/923100522239) or [here FB](https://www.facebook.com/marsad.ch.0408) – Marsad May 05 '20 at 12:04
  • If your app restart when the post deleted just rearrange last two lines ```mPostList.setAdapter(adapter); adapter.startListening(); ``` – Marsad May 05 '20 at 15:17
  • Hey Marsad, I've dmed you on FB – Shaun .C May 06 '20 at 02:29
1
@Override
    protected void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
        String key = "";

        Query query = FirebaseDatabase.getInstance().getReference("Posts").limitToLast(50);
        FirebaseRecyclerOptions<Post> options = new FirebaseRecyclerOptions.Builder<Post>().setQuery(query,Post.class).build();

        FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(options){
            @Override
            public PostViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_row,parent,false);
                return new PostViewHolder(view);
            }
            @Override
            protected void onBindViewHolder(PostViewHolder holder, int position, Post model){
                final String post_key = getRef(position).getKey();


                holder.setLocation("Location: " + model.getLocation());
                holder.set_foodAvailable("Food Available: " + model.getFood_Available());
                holder.setImage(model.getImage());
                holder.set_foodExpiry("Food Expires At: " + model.getFood_Expiry() + "hrs");
                holder.setCounter("Interested Parties: " + model.getCounter());
                holder.setUsername("Posted by: " + model.getUsername());

                holder.mView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //Toast.makeText(MainActivity.this,post_key, Toast.LENGTH_SHORT).show();
                        Intent singlePostIntent = new Intent(HomeActivity.this, SingleActivity.class);
                        singlePostIntent.putExtra("post_id", post_key);
                        startActivity(singlePostIntent);
                        ((SimpleItemAnimator) mPostList.getItemAnimator()).setSupportsChangeAnimations(false);
                    }
                });

                String test = mDatabase.child(post_key).getRef().toString();
                mDatabase.child(post_key).addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        String expiry = (String) dataSnapshot.child("Food_Expiry").getValue();
                        //Log.i("expiry",expiry);
                        SimpleDateFormat format = new SimpleDateFormat("HH:mm", Locale.ENGLISH);
                        try {
                            Date currentDate = format.parse(time);
                            Date expiryDate = format.parse(expiry);
                            assert currentDate!= null;
                            if(!currentDate.before(expiryDate) || currentDate.after(expiryDate)){
                                mDatabase.child(post_key).getRef().removeValue();
                                Log.i("remove","please");
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {

                    }
                });
                Log.i("test",test);
            }
        };

        adapter.startListening();
        mPostList.setAdapter(adapter);
    }
Shaun .C
  • 31
  • 5