[英]How can I automatically remove an entire post in my firebase database when a time selected by a time picker has been reached?
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下面是我的数据库的快照以及用于将数据库中的数据检索到我的主页活动和单个帖子活动中的代码
@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);
}
});
}
To convert String
to Date
将String
转换为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更新 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);
}
@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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.