Search code examples
androidfirebasefirebase-realtime-databasecustom-adapter

Unable to make CustomAdapter work in a Loop using Fragments


I'm trying to fill make the data show in my Listview, however when i click on the fragment there is nothing on the list. I've tried move the setAdapter inside the loop but it did not work.

I'm running out of ideas about how to make it work

Has anybody tried to fill an custom adapter with fragments before???

This is my Custom Adapter

import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.List;

/**
 * Created by calvi on 22/05/2018.
 */

public class MyListAdapter extends ArrayAdapter<User> {

    List<User> userList;
    Context context;
    int resource;

    public MyListAdapter(@NonNull Context context, @LayoutRes int resource, List<User> userList) {
        super(context, resource, userList);
        this.context = context;
        this.resource = resource;
        this.userList = userList;
    }

    @NonNull
    @Override
    public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        //And for this we need a layoutinflater
        LayoutInflater layoutInflater = LayoutInflater.from(context);
        Log.d("listando", "Antes do inflater");
        //getting the view
        View view = layoutInflater.inflate(resource, null, false);
        Log.d("listando", "Depois do inflater");
        //getting the view elements of the list from the view
        TextView textViewName = view.findViewById(R.id.list_row);
        Log.d("listando", "Depois de pegar o textview");
        //getting the hero of the specified position
        User user = userList.get(position);
        Log.d("listando", "Depois de pegar o get pisition");
        //adding values to the list item
        textViewName.setText(user.getName());
        Log.d("listando", "Depois de setar o name");
        //finally returning the view
        return view;
    }
}

And this is my Fragment which are taking data from firebase and populating it on the adapter

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.firebase.database.ChildEventListener;
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.GenericTypeIndicator;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class UserMessageListFragment extends Fragment {

    private ProgressDialog progressDialog;
    private final String TAG = "UsersMessageLis";
    private ArrayList<String> arrayList = new ArrayList<>();
    ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
    private int totalUsers = 0;
    private ListView listView;
    private TextView noUsersText;
    private List<User> userList = new ArrayList<>();
    public static UserMessageListFragment newInstance() {
        return new UserMessageListFragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_user_message_list, container, false);

        listView = view.findViewById(R.id.usersListListView);
        noUsersText = view.findViewById(R.id.noUsersText);

        final DatabaseReference refMessages = FirebaseDatabase.getInstance().getReference();
        final DatabaseReference ref= FirebaseDatabase.getInstance().getReference().child("usuarios");

        refMessages.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                if(dataSnapshot.getKey().contains(UserDetails.username+ "_")) {
                    final String[] userChatWithId = dataSnapshot.getKey().split(UserDetails.username+"_");

                    ref.addChildEventListener(new ChildEventListener() {
                        @Override
                        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                            if(dataSnapshot.getKey().equals(userChatWithId[1])) {
                                GenericTypeIndicator<Map<String, String>> genericTypeIndicator = new GenericTypeIndicator<Map<String, String>>() {};
                                Map<String, String> map = dataSnapshot.getValue(genericTypeIndicator);
                                String name = map.get("name").toString();
                                String username = map.get("username").toString();
                                String status = map.get("status").toString();
                                String city = map.get("city").toString();

                                Log.d("listando", name);
                                Log.d("listando", username);
                                Log.d("listando", status);
                                Log.d("listando", city);
                                User newUser = new User(username, status, city, name);

                                Log.d("Listando", newUser.toString());
                                userList.add(newUser);
////                                usersList.setAdapter(new ArrayAdapter<>(getContext(), R.layout.my_list, arrayList));
                            }
                        }

                        @Override
                        public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                        }

                        @Override
                        public void onChildRemoved(DataSnapshot dataSnapshot) {

                        }

                        @Override
                        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {

                        }
                    });

                }
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        MyListAdapter adapter = new MyListAdapter(getContext(), R.layout.my_list, userList);

        //attaching adapter to the listview
        listView.setAdapter(adapter);

//        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                UserDetails.chatWithId = arrayList.get(position);
//                startActivity(new Intent(getContext(), Chat.class));
//            }
//        });

        return view;
    }
//    public void doOnSuccess(String response) {
//
//        try {
//            JSONObject object = new JSONObject(response);
//            Iterator iterator = object.keys();
//            String key = "";
//
//            while(iterator.hasNext()) {
//                key = iterator.next().toString();
//
//                if(! key.equals(UserDetails.username)) {
//                    arrayList.add(key);
//                }
//                totalUsers++;
//            }
//
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//
//        checkIfThereIsAnUser(totalUsers);
//    }
//    public void checkIfThereIsAnUser(int totalUsers) {
//
//
//        if(totalUsers <=1){
//            noUsersText.setVisibility(View.VISIBLE);
//            usersList.setVisibility(View.GONE);
//        }
//        else{
//            noUsersText.setVisibility(View.GONE);
//            usersList.setVisibility(View.VISIBLE);
//            usersList.setAdapter(new ArrayAdapter<>(getContext(), R.layout.my_list, arrayList));
//        }
//        progressDialog.dismiss();
//    }
}

What i have noticed is that the logs inside the adapter are not showing


Solution

  • When you create adapter

     MyListAdapter adapter = new MyListAdapter(getContext(), R.layout.my_list, userList);
    

    the userList is empty. So when you add an item to userList, you have to adapter.notifyDataSetChange() to update your adapter