0
public class HomeScreen_Contacts extends Fragment {

TextView noUsersText;

ProgressDialog mProgressDialogue;

FirebaseAuth mAuth;
FirebaseUser currentUser;
String UID;

String name;
String rId;
ArrayAdapter<String> adapter;

ListView usersList;
ArrayList<String> al = new ArrayList<>();
ListView listView;
DatabaseReference rootRef;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    final View rootView = inflater.inflate(R.layout.fragment_contacts, container, false);
    usersList = (ListView) rootView.findViewById(R.id.usersList);
    noUsersText = (TextView) rootView.findViewById(R.id.noUsersText);

    mAuth = FirebaseAuth.getInstance();
    currentUser = mAuth.getCurrentUser();
    UID = mAuth.getCurrentUser().getUid();

    mProgressDialogue = new ProgressDialog(getActivity());
    mProgressDialogue.setMessage("Loading...");
    mProgressDialogue.show();

    rootRef = FirebaseDatabase.getInstance().getReference();
    listView = (ListView) rootView.findViewById(R.id.usersList);



    readData(new MyCallback() {
        @Override
        public void onCallback(List<String> al) {
            for (String name : al) {
                Log.d("TAG", name);
            }
        }
    });

    usersList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            Intent intent = new Intent(getActivity(), Chat.class);
            intent.putExtra("Recievers_Id", rId);
            intent.putExtra("Recievers_Name", name);
            Log.d("RID", rId);
            Log.d("RN", name);
            startActivity(intent);
        }
    });


    return rootView;

}


public void readData(final MyCallback myCallback) {
    DatabaseReference usersRef = rootRef.child("Users");
    ValueEventListener eventListener = new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, al);
            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                name = ds.child("Name").getValue().toString();
                rId = ds.child("Phone_Number").getValue().toString();
                al.add(name);


            }
            listView.setAdapter(adapter);
            mProgressDialogue.dismiss();
            myCallback.onCallback(al);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Toast.makeText(getActivity(), "Please Check Your Internet Connection", Toast.LENGTH_SHORT).show();
        }
    };
    usersRef.addListenerForSingleValueEvent(eventListener);
}


public interface MyCallback {
    void onCallback(List<String> al);
}

}

Whichever item i click on directs me to the same room. i want to change that. i want the user to go to a different room depending on which item he clicks in the listview. Is my logic correct? If yes where have i gone wrong

Followed the tutorial. Not sure on what should come under myCallback... left it blank... can u help me out pleas

Updated my code again... anything wrong?

  • *Is my logic correct?* . **Debug your code** . – ADM Mar 26 '18 at 15:12
  • whichever item i click on... Logcat returning only one number and one name. im not able to figure out why –  Mar 26 '18 at 15:32
  • Add this in question . Cause right now its looks like an Assignment task to me . – ADM Mar 26 '18 at 15:34
  • Make use of `int position` parameter `onItemClick()`. You have to provide custom adapter implementation to show both fields . Follow [This](https://stackoverflow.com/questions/8166497/custom-adapter-for-list-view). – ADM Mar 26 '18 at 15:41
  • i thought custom adapter was only for recycler. Never mind. can i know how to implement that in my project please? sorry still a learner –  Mar 26 '18 at 16:43
  • I already provided you the link . Before that you have to learn about `ListView` and `Adapter`. – ADM Mar 26 '18 at 17:21

2 Answers2

1

You cannot simply declare rId and name as global variables and just simply use them outside the onDataChange(). This is happening because onDataChange() has an asynchronous behaviour and by the time your are adding those variable into your Intent object, the variables are not loaded yet.

A quick fix to your problem would be to use those values only inside the onDataChange() method or if you need them outside, you need to create your own custom callback and for that I recommend you see the last part of my anser from this post and also take a look at this video.

To get the item that was clicked, you need to use one of these approaches:

adapter.getItem(position);

or

al.get(position)

Edit1: Acording to your lastest edit, please follow the next steps:

Change the interface like this:

public interface MyCallback {
    void onCallback(List<String> al);
}    

Then inside the onDataChange() method right after the mProgressDialogue.dismiss(); line add the following line of code:

myCallback.onCallback(al);

And in the end, just iterate over the ArrayList like this:

readData(new MyCallback() {
    @Override
    public void onCallback(List<String> al) {
        for(String name : al) {
            Log.d("TAG", name);
        }
    }
})

Edit2: This is the entire code. Define the interface:

public interface MyCallback {
    void onCallback(List<String> al);
}

Define the method:

public void readData(final MyCallback myCallback) {
    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference usersRef = rootRef.child("Users");
    ValueEventListener eventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            List<String> al = new ArrayList<>();
            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                String name = ds.child("Name").getValue(String.class);
                String rId = ds.child("Phone_Number").getValue(String.class);
                al.add(name);
            }
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, al);
            ListView listView = (ListView) rootView.findViewById(R.id.usersList);
            listView.setAdapter(adapter);
            mProgressDialogue.dismiss();
            myCallback.onCallback(al);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Toast.makeText(getActivity(), "Please Check Your Internet Connection", Toast.LENGTH_SHORT).show();
        }
    };
    usersRef.addListenerForSingleValueEvent(eventListener);
}

Then simply call the method in your onCreate() method:

readData(new MyCallback() {
    @Override
    public void onCallback(List<String> al) {
        for (String name : al) {
            Log.d("TAG", name);
        }
    }
});

The output should be all the name of your users.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/167682/discussion-on-answer-by-alex-mamo-just-want-to-know-whether-my-listview-is-direc). – Bhargav Rao Mar 28 '18 at 03:53
0

Get value of rId and name from dataset by using index you get in onItemclickListener. Currently you are passing value stored in rId and name variable for every item clicked that's why you always get same value

  • There's no problem with chatactivity because in the logcat when i click on items... whichever item i click on returns just one name and one number. Idk where i have gone wrong –  Mar 26 '18 at 15:33
  • You need to get rid and name from your dataset by using the index you get in onItemclickListener – Abhishek Trivedi Mar 26 '18 at 15:38
  • Currently you are passing value stored in rId and name variable for every item you click.. that's why you always get single value – Abhishek Trivedi Mar 26 '18 at 15:39
  • how do i do that? can i get the code please? still a beginner sorry –  Mar 26 '18 at 16:42
  • Usually on stackoverflow, we expect more detail on answers to questions. – Thom Mar 26 '18 at 17:16