Как добавить лимит времени на само удаление базы данных RealTime - PullRequest
0 голосов
/ 26 февраля 2020

Я хочу удалить свои firebaseRealtimeData через 20 минут, так как мне это сделать. Я создаю приложение запроса пищи, где пользователь запрашивает и добавляет подробности о еде, и все остальные люди видят их детали, но я хочу, чтобы данные, которые добавляются пользователем, удалялись через 20 минут, так почему я должен делать, и где я должен делать в этом коде помогите мне.

package com.example.mynewapp;

import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;


public class MainActivity extends AppCompatActivity {

    DatabaseReference myRef ;
    modelClass mClass;
    CoordinatorLayout coordinatorLayout;
    RecyclerView recyclerView;
    FirebaseRecyclerOptions<modelClass>options;
    FirebaseRecyclerAdapter<modelClass,MyVIewHolder> adapter;
    private String post_key;
    Query query;

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


        //for net Connectivity
        checkNetworkConnectionIsAvailable ();

        //cordinatorLayout
        coordinatorLayout=findViewById ( R.id.myCoordinator );

        //toolbar
        Toolbar toolbar = findViewById ( R.id.toolbar );
        setSupportActionBar ( toolbar );
        getSupportActionBar ().setTitle ( "YouR Food Corner" );

        //modelClass and firebase
        modelClass mClass=new modelClass (  );

        //for insert the data into firebase database and also use for the retrive the data from database.
        myRef= FirebaseDatabase.getInstance ().getReference ().child ( "All Data" );
        myRef.keepSynced ( true );//for syncronize the firebase data

        //recyclerView
       recyclerView=findViewById ( R.id.myRecyclerView );
       LinearLayoutManager linearLayoutManager= new LinearLayoutManager ( getApplicationContext () );
       linearLayoutManager.setReverseLayout ( true );
       linearLayoutManager.setStackFromEnd ( true );
       recyclerView.setHasFixedSize ( true );
       recyclerView.setLayoutManager ( linearLayoutManager );

        //FloatingActionButton
        FloatingActionButton floatingActionButton = findViewById ( R.id.fab );
        floatingActionButton.setOnClickListener ( new View.OnClickListener () {
            @Override
            public void onClick(View view) {
                 FloatingActionButtonData ();
            }
        } );

    }

    //for only press FloatingActionbutton
private void FloatingActionButtonData()
{
    AlertDialog.Builder myDig= new AlertDialog.Builder ( this );
    LayoutInflater layoutInflater=LayoutInflater.from ( this );
    View v=layoutInflater.inflate ( R.layout.inputlayout ,null);
    myDig.setView ( v );
    final AlertDialog dialog=myDig.create ();
    dialog.setCancelable ( true );
    dialog.show ();

     final EditText fname=(EditText)v.findViewById ( R.id.name );
    final EditText fcontact=(EditText)v.findViewById ( R.id.contact );
    final EditText fcollege=(EditText)v.findViewById ( R.id.college );
    final EditText ffood=(EditText)v.findViewById ( R.id.food );


    Button submit =(Button)v.findViewById ( R.id.submitButton );
    submit.setOnClickListener ( new View.OnClickListener () {
        @Override
        public void onClick(View view) {
            String f_name = fname.getText ().toString ().trim ();
            String f_college = fcollege.getText ().toString ().trim ();
            String f_food = ffood.getText ().toString ().trim ();
           String f_contact = fcontact.getText ().toString ().trim ();


            if (f_name.equals ( "" )) {

                fname.setError ( "Required Field.." );
            }
            else if (f_contact.equals ( "" )) {
                fcontact.setError ( "Required Field.." );
            }

            else if (f_college.equals ( "" )) {
                fcollege.setError ( "Required Field.." );
            } else if (f_food.equals ( "" )) {
               ffood.setError ( "Required Field.." );

            }

            else {
              /*
               we also add like this

               mClass.setName ( f_name );
                mClass.setCollege ( f_college );
                mClass.setContact ( f_contact );
                mClass.setFood ( f_food );
                */

              //for date
              Calendar calendar=Calendar.getInstance ();
                DateFormat dateFormat = new SimpleDateFormat ( "MM-dd-yyyy HH:mm:ss" );
                String date = dateFormat.format ( calendar.getTime () );

              mClass=new modelClass ( f_name,f_college,f_food,f_contact,date );

               myRef.push ().setValue ( mClass );//for insert into database
                dialog.dismiss ();
                Snackbar snackbar = Snackbar
                        .make ( coordinatorLayout , "Done" , Snackbar.LENGTH_LONG );
                snackbar.show ();

            }
        }
    } );
}
//for retrive the data use onStart
    @Override
    protected void onStart() {
        super.onStart ();
        AddData ("");
    }
    public void AddData(String data)
    {
        query=  myRef.orderByChild ( "college" ).startAt ( data ).endAt ( data + "\uf8ff" );//for search
   // options=new FirebaseRecyclerOptions.Builder<modelClass> ().setQuery ( myRef,modelClass.class ).build ();//for retrive
        options=new FirebaseRecyclerOptions.Builder<modelClass> ().setQuery ( query,modelClass.class ).build ();//for search and retrive
    adapter=new FirebaseRecyclerAdapter < modelClass, MyVIewHolder > (options)
    {

        @Override
        protected void onBindViewHolder(@NonNull MyVIewHolder holder , final  int position , @NonNull modelClass model)  //for binding the View of recycler_view_item_layout
        {

            holder.college.setText ( model.getCollege () );
            holder.contact.setText ( model.getContact ()  );
            holder.time.setText ( model.getDateTime ());
            holder.food.setText ( model.getFood () );
            holder.name.setText ( model.getName () );


         //  holder.setFoodPost ( model );

            //for post_key we simply fetch that data postion which we want to delete
            post_key=getRef ( position ).getKey ();

            //for Delete the particular data when press long click
            holder.itemView.setOnLongClickListener ( new View.OnLongClickListener () {
                @Override
                public boolean onLongClick(View view) {
                    openDeleteWindow ();
                    Toast.makeText ( MainActivity.this , "Press" , Toast.LENGTH_SHORT ).show ();
                    return true;
                }
            } );

        }
        @NonNull
        @Override
        public MyVIewHolder onCreateViewHolder(@NonNull ViewGroup parent , int viewType)
        {
          View v=  LayoutInflater.from ( parent.getContext () ).inflate ( R.layout.recycler_view_item_layout,parent,false );
            return new MyVIewHolder ( v );

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

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

        if (adapter!= null) {
            adapter.stopListening ();
        }
    }
//for openDeleteWindow Window When LongPress on retrive Items and delete that items
public void openDeleteWindow()
{
    AlertDialog myQuittingDialogBox = new AlertDialog.Builder(this)
            // set message, title, and icon
            .setTitle("Delete")
            .setMessage("Do you want to Delete")
            .setIcon(android.R.drawable.ic_delete)

            .setPositiveButton("Delete", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int whichButton) {
                    //your deleting code
                    myRef.child ( post_key ).removeValue ();


                }

            })
            .setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                    dialog.dismiss();

                }
            })
            .show ();
}

//for Showing AlertBOx of internetconnection
    public  void internetConnectionDialogboX()
    {
        AlertDialog internetDialog = new AlertDialog.Builder(this)
                // set message, title, and icon
                .setTitle("Connect to a Network")
                .setMessage("To use Application,turn on mobile data of connect to Wi-fi.")
                .setNegativeButton("ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                        finish(); //for exit with the application

                    }
                })
                .show ();
    }

//now check the internet conection
    public void checkNetworkConnectionIsAvailable()
    {
        ConnectivityManager connectivityManager=(ConnectivityManager)getSystemService ( Context.CONNECTIVITY_SERVICE );
        NetworkInfo activNetwork = connectivityManager.getActiveNetworkInfo ();
        boolean isConnected = activNetwork != null && activNetwork.isConnected ();

        if(isConnected)
        {
        // onStart ();
        }
        else
        {
            internetConnectionDialogboX ();
        }

    }

    //menu
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater ().inflate ( R.menu.menu_main , menu );

        //for Search
        MenuItem menuItem=menu.findItem (  R.id.search );
        SearchView searchView=(SearchView )menuItem.getActionView ();
        searchView.setQueryHint ( "Enter College Name" );
        searchView.setOnQueryTextListener ( new SearchView.OnQueryTextListener () {
            @Override
            public boolean onQueryTextSubmit(String query) {
                Toast.makeText ( MainActivity.this , "Text Submit" , Toast.LENGTH_SHORT ).show ();
             // Query query1= myRef.orderByChild ( "name" ).startAt ( query ).endAt ( query + "\uf8ff" );
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {

               AddData ( newText);
                return true;
            }
        } );

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId ();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
       /* else if(id==R.id.search)
        {
            Toast.makeText ( this , "hello Search" , Toast.LENGTH_SHORT ).show ();
            return true;
        }*/

        return super.onOptionsItemSelected ( item );
    }
}

1 Ответ

0 голосов
/ 26 февраля 2020

Вы можете управлять отдельным слушателем, который будет делать только это:

  1. прослушивать новые элементы
  2. для каждого элемента, установить таймер (20 минут минус возраст элемента)
  3. при срабатывании таймера удалите элемент.

Для этого потребуется подключить хотя бы одно устройство, или элементы останутся в базе данных, пока какое-либо устройство не будет подключено снова.

Если вам нужно удалить элементы, даже если никто не находится в сети, вы можете написать запланированную функцию , которая будет запускаться каждые несколько минут и удалять старые элементы.

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