简体   繁体   中英

how do i make a recyclerview with data from firebase clickable with an intent

i am trying to write a code where data from firebase can be populated in recyclerview and also make it clickable so that it can pass the clicked data to a different activity anytime it is clicked

package com.example.helpresponse;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;

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;

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

public class ShowStudentDetailsActivity extends AppCompatActivity {

    DatabaseReference databaseReference;
    ProgressDialog progressDialog;
    List<StudentDetails> list = new ArrayList<>();
    RecyclerView recyclerView;
    RecyclerView.Adapter adapter ;

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

        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(ShowStudentDetailsActivity.this));
        progressDialog = new ProgressDialog(ShowStudentDetailsActivity.this);
        progressDialog.setMessage("Loading Data from Firebase Database");
        progressDialog.show();

        databaseReference = FirebaseDatabase.getInstance().getReference("Police").child("Chats");

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

                for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                    StudentDetails studentDetails = dataSnapshot.getValue(StudentDetails.class);
                    list.add(studentDetails);
                }

                adapter = new RecyclerViewAdapter(ShowStudentDetailsActivity.this, list);
                recyclerView.setAdapter(adapter);
                progressDialog.dismiss();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

                progressDialog.dismiss();

            }
        });


    }
}

the above code displays the data from firebase being populated in recyclerview. but i want to make it clickable so that it will open a new activity that will pass the specific data that was clicked to the new activity.


package com.example.helpresponse;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Locale;

public class TargetDataAdapter extends RecyclerView.Adapter<TargetDataAdapter.TargetViewHolder>{

    ArrayList<AndroidTargets> targetsArrayList;

    public TargetDataAdapter(ArrayList<AndroidTargets> mTargetData) {
        targetsArrayList = mTargetData;
    }

    @NonNull
    @Override
    public TargetViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View v= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.target_row,viewGroup,false);
        return new TargetViewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull TargetViewHolder viewHolder, int i) {
        viewHolder.androidTargetName.setText(targetsArrayList.get(i).FIELD1 );
        viewHolder.androidTargetNumber.setText(String.format(Locale.getDefault(), "API Level: %d", targetsArrayList.get(i).FIELD2));
        viewHolder.androidTargetShortName.setText(targetsArrayList.get(i).FIELD3);
    }

    @Override
    public int getItemCount() {
        if(targetsArrayList == null)
            return 0;
        return targetsArrayList.size();
    }

    public static class TargetViewHolder extends RecyclerView.ViewHolder {
        protected TextView androidTargetName;
        protected TextView androidTargetNumber;
        protected TextView androidTargetShortName;
        public TargetViewHolder(@NonNull View itemView) {
            super(itemView);
            androidTargetShortName=  itemView.findViewById(R.id.textView2);
            androidTargetName= itemView.findViewById(R.id.textView3);
            androidTargetNumber= itemView.findViewById(R.id.textView4);
        }
    }



}

the above code is the recyclerview adapter

You can set up a clickable view in onBindViewHolder and pass your data in the intent. Something like this:

Add a context field to your TargetDataAdapter class:

private Context context;

Assign the context in onCreateViewHolder:

context = viewGroup.getContext();

Set up the clickable view and pass it an intent with your data:

@Override
public void onBindViewHolder(@NonNull TargetViewHolder viewHolder, int i) {
    viewHolder.androidTargetName.setText(targetsArrayList.get(i).FIELD1 );
    viewHolder.androidTargetNumber.setText(String.format(Locale.getDefault(), "API Level: %d", targetsArrayList.get(i).FIELD2));
    viewHolder.androidTargetShortName.setText(targetsArrayList.get(i).FIELD3);
    View myClickableView = viewHolder.itemView.findViewById(R.id.my_clickable_view);
    myClickableView.setOnClickListener((v) -> {
        Intent intent = new Intent(context, MyClassIWantToSendDataTo.class);
        intent.putExtra("myDataKey", myData);
        //more intent.putExtra(s) as needed
        context.startActivity(intent);
    });
}

First Step : Create Interface with any name .

public interface HandleClick {

    void onItemClick(int index);

}

after that : you need declare member variable of this interface in Adapter :

private HandleClick mHandleClick;

public void setmHandleClick(HandleClick handleClick) {
    this.mHandleClick = handleClick;
}

after that : you need pass the actual implementation for this interface when declare adapter in main activity :

 adapter = new RecyclerViewAdapter(ShowStudentDetailsActivity.this, list);
           adapter.setmHandleClcik(new HandleClick() {
                @Override
                public void onItemClick(int index) {
                   // Here You can Add Any Java Code 
                   Intent intent = new Intent(getApplicationContext() , TargetActivity.class);
                   startActivity(intent);
                }
            }); 

after that : you need trigger this Code when item click in recyclerView : add this code in method onBindViewHolder :

 myClickableView.setOnClickListener((v) -> {
     mHandleClick.onItemClick(i);
 });

This Way it's allow for developer use features of Activity it's host The recycler View as : 1- startAactivityForResult 2- if you use pagination in your request you can make new request from activity not adapter .

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