0

I am developing an app the will utilize the data from a real-time database from firebase, and i want to present that data on a recyclerView.

I created a recyclerView with an adapter and all that's necessary for one to work, but im not being able to get the data from the database.

The code i currently have on my adapter is:

public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder>{

    Context context;

    ArrayList<User> list;

    public Adapter(Context context, ArrayList<User> list) {
        this.context = context;
        this.list = list;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(context).inflate(R.layout.item,parent, false);
        return new MyViewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {

        User user = list.get(position);

        holder.nome.setText(user.getNome());
        holder.local.setText(user.getLocal());
        holder.preco.setText(user.getPreco());

    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder{

        TextView nome, local, preco;

        public MyViewHolder(@NonNull View itemview){
            super(itemview);

            nome = itemview.findViewById(R.id.textView1);
            local = itemview.findViewById(R.id.textView2);
            preco = itemview.findViewById(R.id.textView3);

        }
    }
}

And this the code i have on the List

public class Userlist extends AppCompatActivity {

    RecyclerView recyclerView;
    DatabaseReference database;
    Adapter adapter;
    ArrayList<User> list;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_userlist);

        recyclerView = findViewById(R.id.userlist);
        //database = FirebaseDatabase.getInstance();
        database = FirebaseDatabase.getInstance().getReference("Esp");
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        list = new ArrayList<>();
        adapter = new Adapter(this,list);
        recyclerView.setAdapter(adapter);

        final Context context = this;
        database.addValueEventListener(new ValueEventListener() {

            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if (snapshot.exists()){
                    Toast.makeText(context, "Dados recebidos da Firebase!", Toast.LENGTH_LONG).show();
                }else {
                    Toast.makeText(context, "Nao ha dados recebidos!", Toast.LENGTH_SHORT).show();
                }

                for (DataSnapshot dataSnapshot : snapshot.getChildren()){

                    User user = dataSnapshot.getValue(User.class);
                    list.add(user);


                }
                adapter.notifyDataSetChanged();

            }


            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) { throw databaseError.toException(); }
        });


    }
}

I tried to change variables, change the path to the database, and still no success. I have checked the permissions on firebase and both read and write are set to true.

This is how i have my data on the realtime database

{
  "Esp": {
    "andre": {
      "local": "Porto",
      "nome": "Andre",
      "preco": "23"
    },
    "andre2": {
      "local": "Gandra",
      "nome": "Andre2",
      "preco": "23"
    }
  }
}

My user class

public class User {

    String nome, local, preco;

    public String getNome() {
        return nome;
    }

    public String getLocal() {
        return local;
    }

    public String getPreco() {
        return preco;
    }
}
  • Step 1 is to stop ignoring potential errors and implement `onCancelled`. At its minimum this should look like: `public void onCancelled(@NonNull DatabaseError databaseError) { throw databaseError.toException(); }` – Frank van Puffelen Mar 16 '23 at 19:20
  • If that doesn't help you solve the problem, we'l probably want to see the data in yoru database thta you expect this code to show (as text, no screenshots please). You can get this by clicking the "Export JSON" link in the overflow menu (⠇) on your [Firebase Database console](https://console.firebase.google.com/project/_/database/data). – Frank van Puffelen Mar 16 '23 at 19:22
  • It did not solve the problem, The data i have on the database is currently this { "Esp": { "andre": { "local": "Porto", "nome": "Andre", "preco": "23" }, "andre2": { "local": "Gandra", "nome": "Andre2", "preco": "23" } } } – Andre Neves Mar 17 '23 at 00:20
  • Please also update the code with the new `onCancelled`, so that others can see you implemented that without them having to read the comments. --- The rest of your code looks fine at first glance, although we of course don't know what your `User` class looks like. It might be best for you to debug the code locally, and share the results. If you set a breakpoint on each line of the code you shared, run the code in a debugger, and then check the value of each variable on each line, which is the **first** line that doesn't do what you expect it to do? – Frank van Puffelen Mar 17 '23 at 02:02
  • Please edit your question and add the information Frank asked for, and please also respond using @. – Alex Mamo Mar 17 '23 at 06:32
  • I am fairly new to android development and devolpment in general, so I'm not really sure how to verify the values using breakpoints, i tried it, but havent found where the values might appear @FrankvanPuffelen. I also added the user class to the post – Andre Neves Mar 17 '23 at 12:02
  • We've all been new to Android development at some point, so no worries. The Android docs have a great page on [debugging your app](https://developer.android.com/studio/debug) to get you started with, including the section on [working with breakpoints](https://developer.android.com/studio/debug#breakPoints) and [inspecting varialbles](https://developer.android.com/studio/debug#variablesAndWatches). – Frank van Puffelen Mar 17 '23 at 13:57
  • From what i have seen the first line that isnt working is `database = FirebaseDatabase.getInstance().getReference("Esp");` . The value of database is null in this line, which from what i understand it should be non null, but correct me if im wrong @FrankvanPuffelen – Andre Neves Mar 17 '23 at 18:36
  • That call should *never* return `null`, as it just creates a pure client-side reference to a path in your database. But of course `database` won't have an assigned value until **after** that line. – Frank van Puffelen Mar 17 '23 at 20:42
  • So what can i do ? @FrankvanPuffelen – Andre Neves Mar 17 '23 at 23:47
  • Do you have any other code in this app that accesses the database, and that *does* work? If not, try a simple write operation like `FirebaseDatabse.getInstance().getReference("test").setValue(true);` to see if that works. If that doesn't work either, the problem is more likely in the configuration than in the specific code you shared. – Frank van Puffelen Mar 18 '23 at 00:09
  • No, thats the only code that has access to the database. The code you sugested does not work. Any tips on what might be wrong with the configuration? @FrankvanPuffelen – Andre Neves Mar 18 '23 at 12:05
  • Yeah, it sounds like your configuration is incomplete. For example, because you downloaded the `firebase.json` file before you created the database in the Firebase console. Redownload the file, or specify the URL *inside* your code: `FirebaseDatabse.getInstance("your database url here").getReference("test").setValue(true);` Also see my answer here: https://stackoverflow.com/questions/68806876/firebase-realtime-database-connection-killed-different-region – Frank van Puffelen Mar 18 '23 at 14:28
  • I redownloaded the json file, and also added the url to the code and still does not work. I also tried to clean the project and rebuild it and still does not work. Im getting a wifi_fowarder error in logcat, could that be the cause why its not connecting? @FrankvanPuffelen – Andre Neves Mar 18 '23 at 16:30
  • Honestly, I don't know anymore at this point. Look at the number of steps we've gone through by now, including showing you how to handle errors, how to debug, how to drastically [simplify the minimal repro](http://stackoverflow.com/help/mcve) (read the link please, it's quite useful) in your question. I'll vote to reopen your question in hopes that somebody else spots the problem, but if you take all the steps we've gone though above *before* posting future questions it'd drastically increase chances that someone can help. – Frank van Puffelen Mar 19 '23 at 03:59

0 Answers0