How to save retrieved data from firebase to string variable in android?

3909 views java
1

Hy Developers, I am new to android development so that's why facing an issue in saving and viewing data to my android app.

I know that data can only be retrieved while you are connected to internet.

But the thing is it is retrieving data and also showing to android log.

But when i try to save it to a string variable or to arraylist to show it on main activity using that list or variable, its not working.

I am declaring a private string variable to store value from firebase database before onCreate method.

Sorry for my nob question. But this is the issue i am facing.

Following is the code that i am using and some screenshots to make the question understandable.

private String quest;

  @Override
    protected void onCreate(Bundle savedInstanceState{ 

   question = (TextView) findViewById(R.id.question);

FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.getReference("mcqs");

    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            Map <String, String> map = (Map)dataSnapshot.getValue();
            quest = map.get("question");

            Log.v("E_Value","Question is" + quest);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

  question.setText(quest);
}

enter image description here

In above pic you can see that question is retrieved successfully from firebase and visible in log.

enter image description here

But here when i try to display question on main screen after assigning, its showing blank.

answered question

pass quest value to text view

I am doing that, you can see this in the code i provided above..

check answer @Ehsan and let me know one thing are you getting value in logs.?

Yes as you could see in the black picture above, i am getting the question in log "What is your name"

1 Answer

8

Pass quest value to Textview..

ArrayList<String> questionArrrayList =new Arraylist<>();
questionArrrayList .clear();

   myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            Map <String, String> map = (Map)dataSnapshot.getValue();
            quest = map.get("question");
             question.setText(quest);


                questionArrrayList .add(quest);
                Log.v("E_Value","Question is" + quest);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

posted this

Have an answer?

JD

Please login first before posting an answer.