Return string value with firebase

Asked

Viewed 630 times

0

In Android Studio I have the following code in Mainactivity

package br.alan.com.firebaseapp;

import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.ButtonBarLayout;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

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;

public class MainActivity extends AppCompatActivity {
    //Referencia a banco de dados do site do firebase
    private DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
    //Referencia o nome do banco de dados
    public DatabaseReference usuarioReferencia = databaseReference;
    private TextView texto;
    private Button botaoValor;
    private EditText valor;


    @Override
    public View findViewById(@IdRes int id) {
        return super.findViewById(id);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        texto = (TextView) findViewById(R.id.textView2);
        botaoValor = (Button) findViewById(R.id.botaoId);
        valor = (EditText) findViewById(R.id.valorId);



        botaoValor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String valorDigitado = valor.getText().toString();

                usuarioReferencia.child(valorDigitado).addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        if(dataSnapshot.exists()) {
                            texto.setText(dataSnapshot.getValue().toString());
                        }else{
                            texto.setText("Não existe!");
                        }
                    }
                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                        texto.setText("Dados não encontrado!");
                    }
                });
            }
        });

    }
}

No firabase I have the values

inserir a descrição da imagem aqui

When I run Androidstudio emulator I have the following data:

inserir a descrição da imagem aqui

As I do to format this string, take out that { } that looks like it is returning a json. When I put texto.setText(dataSnapshot.getValue().toString()); in the code is returning this data. I would like to know how to return without {} and know how to manipulate this data.

  • may be half beast the question, but you can access the object: dataSnapshot.pais.getValue(). toString()?

  • If the object comes entirely in string you can use this google Mavem which converts JSON string into Object: https://mvnrepository.com/artifact/com.google.code.gson/gson

  • blz, I’ll check, I can only return in string when I pick up a data after Alan. For example using this code userReference.Child("Alan"). Child("parents"), there it returns in string. But I wanted to take a data set. But if it doesn’t work I’ll use the parse or Heroku.

1 answer

3

I believe that the most appropriate way for a future adaptation of the code would be to create a class that instantiates this data, in this case a class called User:

public class User {

    public String name;
    public String email;

    public User() {
    
    }

    public User(String name, String email) {
        this.name= name;
        this.email = email;
    }

    public String getName(){
        return this.name;
    }

}

Here the code returns the class you want:

ValueEventListener postListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        User user = dataSnapshot.getValue(User.class);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
    
    }
};

Here you already have user instance with the data available, so just work with this data:

user.getName(); //Retorna o nome

Browser other questions tagged

You are not signed in. Login or sign up in order to post.