1

el código de mi clase AddMedicineModified donde aparece el ListView en el que quiero mostrar los datos guardados en Firebase (que se guardan en la misma actividad) es el siguiente:

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.List;

public class AddMedicineModified extends AppCompatActivity {

private static final String TAG = "AddNewMedicine";



private Button buttonModifiedMedicine;

private EditText newMedicineModified;

private ListView listViewMedicine;

//Mensaje Adapter


//añadimos cosas de Firebase
private FirebaseDatabase bd;
private DatabaseReference myRef;
private ArrayAdapter<String> adapter;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;



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

    //recuperamos el nombre de usuario
    //Inicializamos vistas
    buttonModifiedMedicine = (Button) findViewById(R.id.btnAñadirMedicinaModified);//revisar
    newMedicineModified = (EditText) findViewById(R.id.add_new_medicine_modified);
    listViewMedicine=(ListView) findViewById(R.id.listMedicines);


    //Se declara el objeto database reference
    //Se necesita estar logueado
    mAuth = FirebaseAuth.getInstance();
    bd = FirebaseDatabase.getInstance();
    myRef = bd.getReference();

    //Para mostrar las medicinas
    List<String> medicinas= new ArrayList<>();
    adapter= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,medicinas);
    listViewMedicine.setAdapter(adapter);





    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
                toastMessage("Successfully signed in with: " + user.getEmail());
            } else {
                // User is signed out
                Log.d(TAG, "onAuthStateChanged:signed_out");
                toastMessage("Successfully signed out.");
            }

        }
    };

    //leer desde la base de datos. Esto está sacado del tutorial de firebase
    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            //this method is called once with the initial value and again
            //whenever data on this location is updated
            Object value = dataSnapshot.getValue();
            Log.d(TAG, "Value is" + value);
            //SIN LO DE ABAJO FUNCIONA BIEN, VAMOS A VER SI FUNCIONA CON LO DE ABAJO
            //Si le añado lo de abajo peta y se quita la pantalla de esta actividad
            String mensaje=dataSnapshot.getValue(String.class);
            adapter.add(mensaje);

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            //Failed to read value
            Log.w(TAG, "Failed to read value.", databaseError.toException());

        }
    });

    buttonModifiedMedicine.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Log.d(TAG, "onClick:Attempting to add object to database.");
            String newMedicine = newMedicineModified.getText().toString();
            if (!newMedicine.equals("")) {
                FirebaseUser user = mAuth.getCurrentUser();
                String userID = user.getUid();
                myRef.child(userID).child("Medication").child("Medicines").child(newMedicine).setValue("true");
                toastMessage("Adding " + newMedicine + " to database...");
                //reset the text
                newMedicineModified.setText("");
            }
        }
    });
}


public void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(mAuthListener);
}

public void onStop() {
    super.onStop();
    if (mAuthListener != null) {
        mAuth.removeAuthStateListener(mAuthListener);
    }
}

public void toastMessage(String message) {
    Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
 }

Y se produce el siguiente error: introducir la descripción de la imagen aquí

He estado buscando cómo solucionarlo en otras preguntas de Stack en inglés, etc, pero en este caso en concreto no entiendo el problema que se está produciendo. Sin las líneas de código:

String mensaje=dataSnapshot.getValue(String.class);
        adapter.add(mensaje);

Lo demás funciona perfectamente. ¿Hay algún enlace de documentación Firebase que me pueda ayudar a solucionar este problema? Gracias de antemano

1 respuesta 1

0

Estas obteniendo el mensaje de error:

com.google.firebase.database.DatabaseException: Failed to convert value of type java.util.HashMap to String

El valor que recibes en onDataChange() es un HashMap y no un String,

myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

             Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();

             Log.d(TAG, "Value is" + value);

        }

        ...
        ...

    });

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.