Home » Android » java – How do I use adapter position to retrieve data from firebase to a new activity-Exceptionshub

java – How do I use adapter position to retrieve data from firebase to a new activity-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

SearchPage where I search the books from firebase

public class SearchPage extends AppCompatActivity {
EditText searchbar;

RecyclerView recyclerView;
DatabaseReference reference;

ArrayList<String> BookNameList;
ArrayList<String> AuthorNameList;
ArrayList<String> PicList;
ArrayList<String> PublisherList;
ArrayList<String> Shelfnols;
ArrayList<String> Desc;
SearchAdapter searchAdapter;

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

    searchbar = (EditText) findViewById(R.id.searchbar);
    reference = FirebaseDatabase.getInstance().getReference();
    reference.keepSynced(true);
    recyclerView = (RecyclerView) findViewById(R.id.rv);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
    BookNameList = new ArrayList<>();
    PublisherList = new ArrayList<>();
    AuthorNameList = new ArrayList<>();
    Shelfnols = new ArrayList<>();
    PicList = new ArrayList<>();
    Desc=new ArrayList<>();







    searchbar.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!s.toString().isEmpty()) {
                setAdapter(s.toString());

            }
            else{
                BookNameList.clear();
                AuthorNameList.clear();
                PicList.clear();
                PublisherList.clear();
                Shelfnols.clear();
                Desc.clear();


            }
        }

        private void setAdapter(final String searchedString) {
            reference.child("books").addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {



                    BookNameList.clear();
                    AuthorNameList.clear();
                    PicList.clear();
                    PublisherList.clear();
                    Shelfnols.clear();
                    Desc.clear();



                    int counter=0;
                    for(DataSnapshot snapshot:dataSnapshot.getChildren()){
                        String uid = snapshot.getKey();


                       Log.i(uid,"ids");
                        String desc = snapshot.child("Desc").getValue(String.class);
                        String bookname = snapshot.child("bookname").getValue(String.class);
                        String author = snapshot.child("author").getValue(String.class);
                        String image = snapshot.child("image").getValue(String.class);
                        String publisher = snapshot.child("Publisher").getValue(String.class);
                        String shelfno = snapshot.child("Shelf_no").getValue(String.class);
                        try {


                            if (bookname.toLowerCase().contains(searchedString.toLowerCase())) {
                                BookNameList.add(bookname);
                                AuthorNameList.add(author);
                                PublisherList.add(publisher);
                                Shelfnols.add(shelfno);
                                PicList.add(image);
                                Desc.add(desc);

                                counter++;
                            } else if (author.toLowerCase().contains(searchedString.toLowerCase())) {
                                BookNameList.add(bookname);
                                AuthorNameList.add(author);
                                PublisherList.add(publisher);
                                Shelfnols.add(shelfno);
                                PicList.add(image);
                                Desc.add(desc);
                                counter++;
                            }
                        }
                        catch (Exception e){
                            Toast.makeText(getApplicationContext(),"not found",Toast.LENGTH_LONG).show();
                        }


                        if(counter==15){
                            break;
                        }
                        SearchAdapter searchAdapter = new SearchAdapter(SearchPage.this, BookNameList, AuthorNameList, PicList, PublisherList, Shelfnols);
                        recyclerView.setAdapter(searchAdapter);
                    }
                }

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

                }




            });
        }
    });


}

this the adapter class SearchAdapter where I am getting the adapter position on click

public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.SearchViewHolder> {
final public String id="bookname";

    Context context;
    ArrayList<String> BookNameList;
    ArrayList<String> AuthorNameList;
ArrayList<String> PicList;
ArrayList<String> PublisherList;
ArrayList<String> Shelfnols;
LinearLayout booklayout;
DatabaseReference reference;





class SearchViewHolder extends RecyclerView.ViewHolder{
    ImageView bookimage;
    TextView bookname, authorname,publisher,shelfno;

    public SearchViewHolder(@NonNull View itemView) {
        super(itemView);
        bookimage =  itemView.findViewById(R.id.Bookimg);
        bookname =  itemView.findViewById(R.id.BookName);
        authorname =  itemView.findViewById(R.id.AuthorName);
        publisher =  itemView.findViewById(R.id.Publications);
        shelfno =  itemView.findViewById(R.id.Shelfno);
        booklayout=itemView.findViewById(R.id.LinLayout);
        reference = FirebaseDatabase.getInstance().getReference();
        reference.keepSynced(true);

    }
}

public SearchAdapter(Context context, ArrayList<String> bookNameList, ArrayList<String> authorNameList, ArrayList<String> picList,ArrayList<String> publisherList,ArrayList<String> shelfnols) {
    this.context = context;
    BookNameList = bookNameList;
    AuthorNameList = authorNameList;
    PicList = picList;
    PublisherList=publisherList;
    Shelfnols=shelfnols;
}


@NonNull
@Override
public SearchAdapter.SearchViewHolder  onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(context).inflate(R.layout.activity_search_layout,parent,false);
     return new SearchAdapter.SearchViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull SearchViewHolder holder, final int position) {
    holder.bookname.setText(BookNameList.get(position));
    holder.authorname.setText(AuthorNameList.get(position));
    holder.publisher.setText(PublisherList.get(position));
    holder.shelfno.setText(Shelfnols.get(position));




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

                 Toast.makeText(context,"clicked "+position,Toast.LENGTH_LONG).show();
                   Intent i = new Intent(context,Bookdetailslayout.class);

                 context.startActivity(i);
               }
           });






    Glide.with(context).asBitmap().load(PicList.get(position)).placeholder(R.mipmap.ic_launcher_round).into(holder.bookimage);

}

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

this is my new activity where i want the book details to be shown

public class Bookdetailslayout extends SearchPage {

DatabaseReference reference;
TextView bookname,author,publisher,desc,location;
ImageView image;




@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bookdetailslayout);
    image=(ImageView)findViewById(R.id.img) ;

    bookname = (TextView)findViewById(R.id.bkname);
    author = (TextView) findViewById(R.id.aname);
    publisher = (TextView) findViewById(R.id.pname);
    desc = (TextView) findViewById(R.id.bkdescription);
    location = (TextView) findViewById(R.id.bklocation);
    String Bname=getIntent().getStringExtra("bookname");
    Log.i(Bname, "onCreate: ");



    DatabaseReference databaseReference=FirebaseDatabase.getInstance().getReference().child("books");



}

till now I was able to set onclick to new activity and get the position of the click as item 1,2,etc…how do I use this position to get data from firebase to the new activity

How to&Answers:

Assign new arraylist

ArrayList<String> bookIdList;

in onCreate() :

bookIdList=new ArrayList<>();

Then clear bookIdList all the time.

bookId.clear();

add data to bookIdList :

bookIdList.add(uid);

Provide Book Id List to RecyclerView :
SearchAdapter searchAdapter = new SearchAdapter(SearchPage.this, BookNameList, AuthorNameList, PicList, PublisherList, Shelfnols, bookIdList);

ArrayList<String> bookIdList;

public SearchAdapter(Context context, ArrayList<String> bookNameList, ArrayList<String> authorNameList, ArrayList<String> picList,ArrayList<String> publisherList,ArrayList<String> shelfnols) {
    this.context = context;
    BookNameList = bookNameList;
    AuthorNameList = authorNameList;
    PicList = picList;
    PublisherList=publisherList;
    Shelfnols=shelfnols;
    bookIdList = bookIdList;
}

then onClick :

holder.itemView.setOnClickListener(new View.OnClickListener() {
    @Override
        public void onClick(View v) {
            Toast.makeText(context,"clicked "+position,Toast.LENGTH_LONG).show();
            Intent i = new Intent(context,Bookdetailslayout.class);
            i.putExtra("BookId", bookIdList.get(position))
            context.startActivity(i);
        }
});

Then get BookId on BookDetail Activity :

String Bid=getIntent().getStringExtra("BookId");

if(Bid != null){
    DatabaseReference databaseReference=FirebaseDatabase.getInstance().getReference().child("books").child(Bid);
}

if you have any problem just Comment Down i’ll explain you

Answer:

create interface

public interface SetclickListener {

    public void  getposition(int position);
}

inside adapter create constructor

 SetclickListener setclicklistener;
public SetclickListener getSetclick(Context context) {
        this.context=context;
        return setclicklistener;
    }

public void setclicklistener(SetclickListener setclickListener){
        setclicklistener=setclickListener;
    }

get selected position

 setclicklistener.getposition(getAdapterPosition());

then you can implement inside SearchPage activity then you can pass selected position data using Bundle you can send data to other activity

@Override
    public void getposition(int position) {
                        Intent intent = new Intent(context,DetailsActivity.class);
                        intent.putExtra("name", bookNameList.get(position));
                        startActivity(intent);

                }

        }

}

Answer:

i used this in my adapter class to get position

 public void onClick(View v) {


                   Intent i = new Intent(context,Bookdetailslayout.class);
                   i.putExtra("bookname",BookNameList.get(position));

                   i.putExtra("Image",PicList.get(position));
                   i.putExtra("author_name",AuthorNameList.get(position));
                   i.putExtra("publisher_name",PublisherList.get(position));
                   context.startActivity(i);
               }
           });

then in the next activity

 String imgs=getIntent().getStringExtra("Image");
    String Bname=getIntent().getStringExtra("bookname");
    title.setText(Bname);
    String Author=getIntent().getStringExtra("author_name");
    author.setText(Author);
    String publisher=getIntent().getStringExtra("publisher_name");
    pub.setText(publisher);
    Toast.makeText(this,"image "+imgs,Toast.LENGTH_LONG).show();
    Picasso.get().load(imgs).into(image);

and it works ..thanks for all the help here