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.

public class MainActivity extends AppCompatActivity {

private static final String TAG = "Firelog" ;

Button ans1, ans2, ans3, ans4;

TextView uscore, question, timer;

private String mAnswer;

private ArrayList<String> fbquestions = new ArrayList<String>();

private String quest;

private int mScore = 0;

Random r = new Random();

private int res = 0;

private int c = 0;

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

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

    ans1 = (Button) findViewById(R.id.ans1);
    ans2 = (Button) findViewById(R.id.ans2);
    ans3 = (Button) findViewById(R.id.ans3);
    ans4 = (Button) findViewById(R.id.ans4);

    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");

            fbquestions.add(quest);

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

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

        }
    });

    question.setText(String.valueOf(fbquestions.get(0)));
  }
}

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.

enter image description here

After adding the code to add value to arraylist, application crashes..

Ahsan Ellahi
  • 55
  • 1
  • 9

2 Answers2

1

You cannot simply get the value of fbquestions.get(0) outside the onDataChange() method because this method has an asynchronous behavior. So you cannot simply create your fbquestions list as a global variable and use it's value outside the callbakc because it will always be empty. Basically, you're trying to use a value synchronously from an API that's asynchronous. That's not a good idea. You should handle the APIs asynchronously as intended.

A quick solve for this problem would be to move the following line of code:

question.setText(String.valueOf(fbquestions.get(0)));

Inside the callback right after this line of code:

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

And your problem will be solved. If you want to use the list outside, I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Perfectly got the solution. But there is a little issue again. I want to use that list to display values on main screen after it had finished adding all elements to the list from firebase db. – Ahsan Ellahi Sep 16 '18 at 14:14
  • 1
    Oh, it's pretty simple. **[This](https://stackoverflow.com/questions/48622480/showing-firebase-data-in-listview)** is a recommended way in which you can retrieve data from a Firebase Realtime database and display it in a `ListView` using an `ArrayAdapter` and **[this](https://stackoverflow.com/questions/49383687/how-can-i-retrieve-data-from-firebase-to-my-adapter/49384849)** is a recommended way in which you can retrieve data from a Firebase Realtime database and display it in a `RecyclerView` using `FirebaseRecyclerAdapter`. – Alex Mamo Sep 16 '18 at 14:18
  • I know that we can use list view or Recyclerview. But that's for list items. I want to show a single question from my list to the main screen using a random number. I am working on a quiz app. – Ahsan Ellahi Sep 16 '18 at 14:19
  • This sounds as another question but since I have already answered a similar one, **[here](https://stackoverflow.com/questions/50413117/how-to-get-unique-random-product-in-node-firebase/50413208)** is how you can get a random item from a section of your database. – Alex Mamo Sep 16 '18 at 14:21
  • You have references in all those answers so you can generate a random item and display it in a `RecyclerView` or `ListView`. So given the information in those answers, please make your own attempt and ask another question if something else comes up. Cheers! – Alex Mamo Sep 16 '18 at 14:25
0

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) {

        }
    });
Atif AbbAsi
  • 5,633
  • 7
  • 26
  • 47