Как я могу автоматически удалить всю запись в моей базе данных Firebase, когда достигнуто время, выбранное средством выбора времени? - PullRequest
2 голосов
/ 03 мая 2020

Проблема, с которой я сталкиваюсь сейчас, заключается в том, что единственный способ удалить сообщение - это когда я нажимаю на сообщение точно в момент истечения срока его действия. Когда истечет время, когда я не нажму на сообщение, сообщение не будет удалено. Я хочу, чтобы публикация автоматически удалялась из базы данных по истечении времени истечения независимо от того, какой деятельностью будет заниматься пользователь. Есть ли способ, которым я могу обойти это? Ниже приведен снимок моей базы данных и кодов, используемых для извлечения данных из моей базы данных в активность на моей домашней странице и в отдельном сообщении

База данных

Действия на домашней странице

@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);
    }

Активность одного сообщения

@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);
            }
        });
    }

Ответы [ 2 ]

1 голос
/ 04 мая 2020
@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);
    }
1 голос
/ 03 мая 2020

Для преобразования String в Date

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 = 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) {

            }
        });

Обновление 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);
    }

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...