简体   繁体   中英

How do I retrieve the Firebase parent id of an item in a ListView(created by Firebase Data Elements) is clicked?

I am trying to make a ChatApp that allows users to talk to all other users using the application. On sign up, I have created a database of users with each one under a Firebase generate id. On my ChatSelectionActivity, I have populated a ListView with the users names along with their email. I am trying to make it so that when a user is clicked on in the ChatSelection, their id is passed on to a ChattingActivity. Then the chatting activity is able to retrieve the data associated with the id and set TextView using it. I am having quite a bit of trouble getting the id of the clicked on item because I am not using a FirebaseListAdapter and then passing it onto the Chatting Activity

This is my data structure(I would like to pass the parent id of each email and name):

   users
    -LJzf1AoOffNpl6hcYMK
               email:"vaenugula01@gmail.com"
               name: "Phaniraj Aenugula"
    -LJzhru4UjIT1LyMyvep
               email:"dunkinchicken@gmail.com"
               name: "D'Andre Black"
    -LK4UT0n_LI27AUvBPQH
               email:"nagapvvs01@gmail.com"
               name:"Pavan Kumar"

This is my ChatSelectionActivity:

package com.tamir.offen.OddJob;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.constraint.solver.widgets.Snapshot;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

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.Query;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.List;

import static com.tamir.offen.OddJob.ChatSelectionActivity.getChatterId;

public class ChatSelectionActivity extends AppCompatActivity{
    ListView listViewUsers;

    DatabaseReference databaseUsers;
    List<User> userList;
    private BottomNavigationView bottomNavigationView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat_selection);

        listViewUsers = (ListView) findViewById(R.id.listViewUsers);
        databaseUsers = FirebaseDatabase.getInstance().getReference("users");
        userList = new ArrayList<>();

        bottomNavigationView = findViewById(R.id.bottomNavView_Bar);
        Menu menu = bottomNavigationView.getMenu();
        MenuItem menuItem = menu.getItem(0);
        menuItem.setChecked(true);
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                Intent intent;
                switch(item.getItemId()) {
                    case R.id.nav_messages:
                        //intent = new Intent(messages.this, messages.class);
                        //startActivity(intent);
                        break;

                    case R.id.nav_map:
                        intent = new Intent(ChatSelectionActivity.this, map.class);
                        startActivity(intent);
                        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
                        break;

                    case R.id.nav_add_work:
                        intent = new Intent(ChatSelectionActivity.this, AddActivity.class);
                        startActivity(intent);
                        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
                        break;

                }

                return false;
            }
        });


    }

    @Override
    public void onStart() {
        super.onStart();
        databaseUsers.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                userList.clear();
                for(DataSnapshot userSnapshot: dataSnapshot.getChildren()){
                    User user = userSnapshot.getValue(User.class);
                    userList.add(user);
                }
                final UserList adapter = new UserList(ChatSelectionActivity.this, userList);
                listViewUsers.setAdapter(adapter);
                listViewUsers.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {


                        // I don't know how to retrieve the 

                        Intent chatIntent = new Intent(ChatSelectionActivity.this, ChattingActivity.class);
                        startActivity(chatIntent);


                    }
                });


            }

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

            }
        });


    }


}

This is my Chatting Activity:

package com.tamir.offen.OddJob;

import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

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.ValueEventListener;

public class ChattingActivity extends AppCompatActivity {

    private TextView receiver_name;
    DatabaseReference databaseUsers;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chatting);
        String chat_id = getIntent().getStringExtra("chat_id");
        //the "chat id" in the getString Extra is the id that would have been passed from the ChatSelectionActivity


        receiver_name = (TextView) findViewById(R.id.receiver_name);
        Toast.makeText(ChattingActivity.this, chat_id, Toast.LENGTH_SHORT).show();
    }
}

It's very simple. Use Firebase's DataSnapshot#getKey() method to get key/parent ID.

Here you need to do the below changes.

User model class

public class User implements Serializable {  // implement serializable interface as we need to pass object this class in an Intent
  ...
  ...
  private String parentId;  // use private access because we don't want to set this id in Firebase database.

  // constructors if there any

  // other getter/setter methods

  // add these getter and setter methods
  public void setParentId(String parentId) {
     this.parentId = parentId;
  }

  public String getParentId() {
     return parentId;
  }

}

Now in your ChatSelectionActivity do the below changes.

@Override
public void onStart() {
    super.onStart();
    databaseUsers.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            userList.clear();
            for(DataSnapshot userSnapshot: dataSnapshot.getChildren()){

                String parentId = userSnapshot.getKey();  // get id from Firebase snapshot

                User user = userSnapshot.getValue(User.class);

                user.setParentId(parentId);  // set parent id

                userList.add(user);
            }
            final UserList adapter = new UserList(ChatSelectionActivity.this, userList);
            listViewUsers.setAdapter(adapter);
            listViewUsers.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {


                    // get User object from ArrayList
                    User user = userList.get(position);

                    Intent chatIntent = new Intent(ChatSelectionActivity.this, ChattingActivity.class);

                    chatIntent.putExtra("user", user);  // pass user object to intent

                    startActivity(chatIntent);


                }
            });
        }

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

        }
    });
}

And finally in your ChattingActivity do the below changes.

private User user;  // create an object of User class outside onCreate() method

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

    user = (User) getIntent().getSerializableExtra("user");  // use the same key as you set in intent object in previous activity

    if (user != null) {
      // now you can get receiver's email, user name, parent id etc. 
      String parentId = user.getParentId();
    }

}

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