简体   繁体   中英

How to make work an Adapter to Listview inside a fragment

I'm using a fragment with a listview to show some elements from a firebase database. But it looks like the adapter doesn't work properly; i traced the code and everything looks working fine. Does anyone know where i have the error?

I tried getActivity().getBaseContext() and getContext() in the adapter context, but it also doesn't work

public class ListFragment extends Fragment implements View.OnClickListener{

    private RecyclerView rcv;
    private ListView lstvw;
    DatabaseReference ddbbr;

    public ListFragment() {
        // Required empty public constructor
    }


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

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_list, container, false);
        lstvw = v.findViewById(R.id.lstvwlistamini);
        ddbbr = FirebaseDatabase.getInstance().getReference("juegos");
        ddbbr.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                ArrayAdapter<String> adapter;
                ArrayList<String> list = new ArrayList<String>();

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

                    Juego juego =  datasnapshot.getValue(Juego.class);

                    String titulo = juego.getTitulo();
                    list.add(titulo);
                    Toast toast = Toast.makeText(getContext(),list.get(0).toString(),Toast.LENGTH_LONG);
                    toast.show();

                }
                adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,list);
                lstvw.setAdapter(adapter);

            }

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

            }
        });


        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_list, container, false);
    }

As i said, the app doesn't crash and the interface works, but the listview is empty

you are inflating a new view when you return the Fragment's view, at the last line of your onCreateView function return the view that inflated before , replace :

return inflater.inflate(R.layout.fragment_list, container, false);

with :

return v;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM