Load activity with a data from the Firebase database

0

I am doing the final project of DAM and in the app that I am creating I would like to know how I can load an activity through a code that exists in the database. I'm working with Firebase and this is the method I'm using.

   public void joinEvent(View view) {

    codigo=Codigo.getText().toString();

    DatabaseReference root = FirebaseDatabase.getInstance().getReference();
    DatabaseReference events = root.child("Events");
    events.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            if (snapshot.child(codigo).exists()) {
                // run some code
            }else {

                Toast.makeText( context, "Código Invalido", Toast.LENGTH_SHORT ).show();

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    Intent intent = new Intent(this, EventActivity.class);
   // intent.putExtra("code",mCode.getText().toString());
    startActivity(intent);

}

    
asked by lujan 13.04.2018 в 18:36
source

1 answer

0

A serious way by using SharedPreferences , in which you can save information locally as if you were creating a SQL database but in a simpler way.

Example

Suppose that in MiActivity you need to take the information that is received from FireBase , to save said data you do the following:

My Activity:

public void joinEvent(View view) {

codigo=Codigo.getText().toString();

DatabaseReference root = FirebaseDatabase.getInstance().getReference();
DatabaseReference events = root.child("Events");
events.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
        if (snapshot.child(codigo).exists()) {
            Context context = getActivity();
            SharedPreferences sharedPreferences = getActivity().getSharedPreferences("Mis_preferences",context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("code", mCode);
            editor.apply();
        }else {

            Toast.makeText( context, "Código Invalido", Toast.LENGTH_SHORT ).show();

        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

Intent intent = new Intent(this, EventActivity.class);
// intent.putExtra("code",mCode.getText().toString());
startActivity(intent);

}

Then, in OtraActivity you can retrieve that information as follows:

Other Activity:

Context context = getActivity();
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("Mis_preferences",context.MODE_PRIVATE);
String mCode = sharedPreferences.getString("code","No hay dato");//"No hay dato" es el valor por defecto que mostrara si no se encuentra el dato guardado
    
answered by 13.04.2018 в 18:51