本文介绍了我想通过Firebase主键相互链接两个数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我试图链接到两个Firebase数据库,所以当我从Firebase的第一个Recyclerview中单击一个项目时.该项目包含一些数据,这些数据我希望在第一个RecyclerView数据库的主键的帮助下显示在第二个recyclerview中.我正在片段中使用第二个recyclerview

hey guys im trying to link to two Firebase Database so when i click on One Item from Firebase first Recyclerview. that item contain some data which i want to show in second recyclerview with the help of Primary key of first RecyclerView Database. I'm using second recyclerview in fragment

第一个Recyclerview包含图像中的数据

First Recyclerview contain data in Image

public class Games extends AppCompatActivity {


    public static  final  String GAME_ID = "gameid";
    public static  final  String GAME_BANNER = "banner";
    private RecyclerView   recyclerView;
    private FirebaseDatabase db = FirebaseDatabase.getInstance();
    private DatabaseReference root = db.getReference().child("Games Tile");
    private GameTileHolder adapter;
    private ArrayList<GameModel> gList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_games);

        // Firebase Settings

        recyclerView = findViewById(R.id.gamesrecyclerview);
        gList = new ArrayList<>();


        root.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {

                for (DataSnapshot dataSnapshot : snapshot.getChildren()){
                    GameModel model = dataSnapshot.getValue(GameModel.class);
                    gList.add( new GameModel(model.banner,model.gameid));

                    Log.i("THE_CURRENT_USER:::", model.toString());
                }
                LinearLayoutManager im = new LinearLayoutManager((Games.this));
                recyclerView.setLayoutManager(im);
                adapter = new GameTileHolder(Games.this,gList);
                recyclerView.setAdapter(adapter);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
            }
        });

    }
}  
public class GameTileHolder extends RecyclerView.Adapter<GameTileHolder.MyViewHolder> {



    public static  final String GAME_ID = "gameid";
    ArrayList<GameModel> mList;
    Context context;

    public GameTileHolder(Context context , ArrayList<GameModel> mList){

        this.mList = mList;
        this.context = context;
    }

    public GameTileHolder(ArrayList<GameModel> mList) {

    }



    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(context).inflate(R.layout.gametile , parent ,false);
        return new MyViewHolder(v);
    }


    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {

        GameModel model  = mList.get(position);

        Glide.with(context).load(mList.get(position).getBanner()).into(holder.gamebanner);

        holder.gamebanner.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {



            }
        });

    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    public static  class MyViewHolder extends RecyclerView.ViewHolder {

        ShapeableImageView gamebanner;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);

            gamebanner = itemView.findViewById(R.id.gametile);

        }
    }}
public class GameModel {
    String banner,gameid;

    public GameModel()
    {

    }

    public GameModel(String banner, String gameid) {
        this.banner = banner;
        this.gameid = gameid;
    }

    public String getBanner() {
        return banner;
    }

    public void setBanner(String banner) {
        this.banner = banner;
    }

    public String getGameid() {
        return gameid;
    }

    public void setGameid(String gameid) {
        this.gameid = gameid;
    }
}
public class matchtab extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // Redirect to Bet Confirm page


    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private Object matchtab;


    private RecyclerView   recyclerView;
    private FirebaseDatabase db = FirebaseDatabase.getInstance();
    private DatabaseReference root = db.getReference().child("Matches");
    private MyAdapter adapter;
    private ArrayList<Model> mList;


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

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment matchtab.
     */
    // TODO: Rename and change types and number of parameters
    public static matchtab newInstance(String param1, String param2) {

        matchtab fragment = new matchtab();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

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

        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment

        View v = inflater.inflate(R.layout.fragment_matchtab, container, false);


        recyclerView = v.findViewById(R.id.matchrecyclerview);
        mList = new ArrayList<>();


        root.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {

                for (DataSnapshot dataSnapshot : snapshot.getChildren()){
                    Model model = dataSnapshot.getValue(Model.class);
                    mList.add( new Model(model.title,model.amt));
                    Log.i("THE_CURRENT_USER:::", model.toString());
                }
                LinearLayoutManager im = new LinearLayoutManager((getContext()));
                recyclerView.setLayoutManager(im);
                adapter = new MyAdapter(getContext(),mList);
                recyclerView.setAdapter(adapter);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
            }

        return v;}

      });


    }
public class BettingPage_Pubgm extends AppCompatActivity {

    public CardView matchCard;
    ImageView bannerShow,ff,codm,valorant,fortnite,dota2,ac,searchbtn;
    TabLayout tabLayout;
    ViewPager2 pager2;
    bettingpage_tabviewer adapter;

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

        tabLayout = findViewById(R.id.bettingtabs);
        pager2 = findViewById(R.id.bettingpagetab);
        bannerShow = findViewById(R.id.gamebanner);



//        bannerShow.setImageResource(getIntent().getIntExtra("banner",0));

        FragmentManager fm = getSupportFragmentManager();
        adapter = new bettingpage_tabviewer(fm, getLifecycle());
        pager2.setAdapter(adapter);

        tabLayout.addTab(tabLayout.newTab().setText("Match Tab"));
        tabLayout.addTab(tabLayout.newTab().setText("Result Tab"));

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                pager2.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        pager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                tabLayout.selectTab(tabLayout.getTabAt(position));
            }
        });

        // Passing Image

        getIncomingint();


    }

    private void getIncomingint(){
        if (getIntent().hasExtra("banner")){
            String banner = getIntent().getStringExtra("banner");
            setImage(banner);
        }
    }


    private  void setImage(String banner){
        Glide.with(this)
                .load(banner)
                .into(bannerShow);
    }
}

我能够像这样主要活动一样从Firebase检索First Recyclerview数据.

I'm able to retrieve First Recyclerview data from firebase like this Main Activity

点击一项后,打开下一个活动,如下所示第二个活动

After clicking on one item next activity open like this Second Activity

第二个活动"中的数据来自Firebase数据库,显示使用Recyclerview

data in Second Activity is from Firebase Database showing using Recyclerview

First Recyclerview"main1"的主键

primary key of First Recyclerview "main1"

推荐答案

  1. 使模型可拆分

  1. Make your model Parcelable

 public class GameModel implements Parcelable {
 String banner,gameid;

 public GameModel()
 {

 }

 public GameModel(String banner, String gameid) {
     this.banner = banner;
     this.gameid = gameid;
 }

 protected GameModel(Parcel in) {
     banner = in.readString();
     gameid = in.readString();
 }

 @Override
 public void writeToParcel(Parcel dest, int flags) {
     dest.writeString(banner);
     dest.writeString(gameid);
 }

 @Override
 public int describeContents() {
     return 0;
 }

 public static final Creator<GameModel> CREATOR = new Creator<GameModel>() {
     @Override
     public GameModel createFromParcel(Parcel in) {
         return new GameModel(in);
     }

     @Override
     public GameModel[] newArray(int size) {
         return new GameModel[size];
     }
 };

 public String getBanner() {
     return banner;
 }

 public void setBanner(String banner) {
     this.banner = banner;
 }

 public String getGameid() {
     return gameid;
 }

 public void setGameid(String gameid) {
     this.gameid = gameid;
 }

}

在第一个回收者视图的onBindViewHolder中,开始第二个Activity,并通过这样的意图传递模型:

in onBindViewHolder of first recycler view start second Activity and pass your model through intent like this:

@Override公开

@Overridepublic

void onBindViewHolder(@NonNull MyViewHolder持有人,int位置){

void onBindViewHolder(@NonNull MyViewHolder holder, int position){

        GameModel model = mList . get (position);

        Glide.with(context).load(mList.get(position).getBanner()).into(holder.gamebanner);

        holder.gamebanner.setOnClickListener(new View . OnClickListener () {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(this, SecondActivity::class.java)
                intent.putExtra("key", model)

                context.startActivity(intent)

            }
        });

    }

  • 在第二个活动中,请按照以下步骤设置选项卡布局之前先获取数据:

  • In the second activity get your data before setting the tab layout as follow:

    公共CardView MatchCard;ImageView bannerShow,ff,codm,valorant,fortnite,dota2,ac,searchbtn;TabLayout tabLayout;ViewPager2 pager2;bettingpage_tabviewer适配器;@Override受保护的void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_betting_page__pubgm);

    public CardView matchCard;ImageView bannerShow,ff,codm,valorant,fortnite,dota2,ac,searchbtn;TabLayout tabLayout;ViewPager2 pager2;bettingpage_tabviewer adapter;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_betting_page__pubgm);

     tabLayout = findViewById(R.id.bettingtabs);
     pager2 = findViewById(R.id.bettingpagetab);
     bannerShow = findViewById(R.id.gamebanner);
                getIncomingint();
                //        bannerShow.setImageResource(getIntent().getIntExtra("banner",0));
    FragmentManager fm = getSupportFragmentManager();
     adapter = new bettingpage_tabviewer(fm, getLifecycle());
     pager2.setAdapter(adapter);
    
     tabLayout.addTab(tabLayout.newTab().setText("Match Tab"));
     tabLayout.addTab(tabLayout.newTab().setText("Result Tab"));
    
     tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
         @Override
         public void onTabSelected(TabLayout.Tab tab) {
             pager2.setCurrentItem(tab.getPosition());
         }
    
         @Override
         public void onTabUnselected(TabLayout.Tab tab) {
    
         }
    
         @Override
         public void onTabReselected(TabLayout.Tab tab) {
    
         }
     });
    
     pager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
         @Override
         public void onPageSelected(int position) {
             tabLayout.selectTab(tabLayout.getTabAt(position));
         }
     });
    
     }     private void getIncomingint(){
         if (getIntent().hasExtra("banner")){
             String banner = getIntent().getStringExtra("banner");
             setImage(banner);
         }
           if (getIntent().hasExtra("key")){
                 model = (GameModel) getIntent().getSerializableExtra("key");
    
             }
         }
         private  void setImage(String banner){
         Glide.with(this)
                 .load(banner)
                 .into(bannerShow);
     }
     }
    

  • 使用捆绑软件将您在第二次活动中获得的该模型传递给片段并检查此链接如何传递活动片段中的数据以及如何获取它链接:将对象从活动传递到片段

    这篇关于我想通过Firebase主键相互链接两个数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

  • 10-28 00:04