如何在单击ListView(由Firebase Data Elements创建)中检索项目的Firebase父ID?

时间:2018-08-17 19:50:07

标签: android firebase listview

我正在尝试制作一个允许用户使用该应用程序与所有其他用户交谈的ChatApp。在注册时,我已经创建了一个用户数据库,每个用户都有一个Firebase生成ID。在我的ChatSelectionActivity上,我用用户名和电子邮件填充了ListView。我试图做到这一点,以便当在ChatSelection中单击用户时,其ID会传递给ChattingActivity。然后,聊天活动能够检索与id关联的数据并使用它设置TextView。我在获取被点击项目的ID时遇到了很多麻烦,因为我没有使用FirebaseListAdapter,然后将其传递给Chating Activity

这是我的数据结构(我想传递每个电子邮件的父ID和名称):

   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"

这是我的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) {

            }
        });


    }


}

这是我的聊天活动:

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();
    }
}

1 个答案:

答案 0 :(得分:0)

这很简单。使用Firebase的DataSnapshot#getKey()方法来获取密钥/父ID。

在这里您需要进行以下更改。

User模型类

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;
  }

}

现在您的ChatSelectionActivity中进行以下更改。

@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) {

        }
    });
}

最后在您的ChattingActivity中进行以下更改。

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();
    }

}