How to get some data after click on certain item RecyclerView? - android

I have already seen a lot of material on this subject even here, namely the list of individual elements of the list. My application receives from the server two lists of messages, incoming and outgoing. And when you click on one of these two lists, you need to switch to the activation, which contains the selected message. When you press it, you need to somehow pull it out the way we said and throw this id into the query. I currently have such an adapter for RecyclerView:
package com.example.developer_4.test_login.Tabs;
import android.content.Context;
import android.content.SharedPreferences;
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 com.example.developer_4.test_login.R;
import com.example.developer_4.test_login.data.model.Message;
import java.util.List;
class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> {
private RecyclerView recyclerViewItemClickListener;
private List<Message> messageList;
private Context ctx;
MessageAdapter(List<Message> messageList, Context ctx) {
this.messageList = messageList;
this.ctx = ctx;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_of_rec_m, viewGroup, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Message message = messageList.get(position);
String id = String.valueOf(message.getId());
holder.subject.setText(message.getSubject());
holder.from.setText(message.getSender_name());
holder.date.setText(message.getDate());
holder.getAdapterPosition();
}
#Override
public int getItemCount() {
return messageList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
final TextView from, subject, date;
int position = 0;
ViewHolder(View v) {
super(v);
subject = v.findViewById(R.id.subject);
from = v.findViewById(R.id.from);
date = v.findViewById(R.id.date);
//id = v.findViewById(R.id.id);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
}
}
at the moment I have hung on a click on the message element sending a request with the id of the message that I entered manually, I have a function getId in the response class from the server, that is, I can get this id, but I do not understand how to catch clicking on a separate list item . I've seen ways to use position but I somehow did not get accustomed to them)) after clicking on a certain element of this list, I need to pass on to another activity of the id of the message by which we clicked in the list, in order to display this message on the other screen.
Thank you all for valuable advice, answers and criticism)). Thank you in advance for your cooperation.

Just try setting :
holder.setTag(position);
then
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int pos = (int)view.getTag();
Message message = messageList.get(pos);
}
});

You can add data by adding tag to any view in your onBindViewHolder method.
holder.itemView.setTag("Some Data");
And then get that tag when clicked.
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String someData=(String)view.getTag();
}
});

Related

onitemclick listener doesnt work from Dialog

I'm invoking an android Dialog from button click defined inside oncreate. The dialog appears with the set recyclerview. But clicking on recyclerview items doesnt work atall. Actually .setonclicklistener is defined. Pls find the code below.
public void openreview() {
rv_review=(RecyclerView)slctssn.findViewById(R.id.rv_test);
adapter_review = new review_adapter(this, questions);
rv_review.setLayoutManager(new GridLayoutManager(this,10));
rv_review.setAdapter(adapter_review);
adapter_review.setOnItemClickListener(onClickedReview);
slctssn.show();
}
Code for clicklistener definition :
public View.OnClickListener onClickedReview = new View.OnClickListener() {
#Override
public void onClick(View view) {
RecyclerView.ViewHolder viewHolder = (RecyclerView.ViewHolder) view.getTag();
int revposition = viewHolder.getAdapterPosition();
mcqoptions one = new mcqoptions();
mcqoptions two = new mcqoptions();
mcqoptions three = new mcqoptions();
mcqoptions four = new mcqoptions();
one.setOption(qSet[revposition][1].toString());
two.setOption(qSet[revposition][2].toString());
three.setOption(qSet[revposition][3].toString());
four.setOption(qSet[revposition][4].toString());
nowStory.clear();
nowStory.add(one);
nowStory.add(two);
nowStory.add(three);
nowStory.add(four);
adapter.notifyDataSetChanged();
questionTxt=(TextView)findViewById(R.id.txtvQ);
questionTxt.setText(qSet[qsetCntr][0].toString());
}
};
Pls help to fix this.
here is my adapter code :
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class review_adapter extends RecyclerView.Adapter<review_adapter.rvViewHolder>{
private List<review_objects> questions;
private Context contxt;
/*** for item click listener purpose as collected from GIT HUB RohitSurwase /
RvClickListenerExample ***/
private View.OnClickListener adOnItemClickListener;
public review_adapter(Context c, List<review_objects> review_objects){
this.contxt= c;
this.questions=review_objects;
}
#NonNull
#Override
public rvViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType){
LayoutInflater inflater = LayoutInflater.from(contxt);
View view = inflater.inflate(R.layout.reviews_layout,parent,false);
return new rvViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull rvViewHolder holder, int position){
String postmtr= questions.get(position).getSerial();
holder.qstnum.setText(postmtr);
}
#Override
public int getItemCount() {
return questions.size();
}
public void setOnItemClickListener(View.OnClickListener itemClickListener) {
adOnItemClickListener = itemClickListener;
}
public class rvViewHolder extends RecyclerView.ViewHolder{
TextView qstnum;
public rvViewHolder(#NonNull View itemView) {
super(itemView);
qstnum = itemView.findViewById(R.id.reviewqnum);
itemView.setTag(this);
itemView.setOnClickListener(adOnItemClickListener);
}
}
}
I could fix it. There were two problems.
questionTxt.setText(qSet[qsetCntr][0].toString()); it was to be like :
questionTxt.setText(qSet[revposition][0].toString());
also one textview element in two places were sharing name. I corrected that also.
So the problem is over.
Thank you.

How to set OnclickListener for the dynamically added items in recyclerview?

In my application I'm using a recycler view to show some data and for each item in recyclerview I'm adding a list of checked text view. These checked textviews are added according to the size of list provided and it works fine. Now I want to add the click listener for those items to know if they are checked or not?
When items are checked those checked items should be taken to another activity. But now the click listener is added directly in recycler view which won't access me to do out of box code. So I'm looking for how to add a click listener and access it in another activity.
My Recyclerview code:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckedTextView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.allio.customer.R;
import com.allio.customer.models.Types_Item;
import com.bumptech.glide.Glide;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.github.florent37.expansionpanel.ExpansionLayout;
import com.github.florent37.expansionpanel.viewgroup.ExpansionLayoutCollection;
public class Types_adapter extends FirestoreRecyclerAdapter<Types_Item, Types_adapter.RecyclerHolder> {
private final ExpansionLayoutCollection expansionsCollection = new ExpansionLayoutCollection();
Context context;
public Types_adapter(#NonNull FirestoreRecyclerOptions<Types_Item> options, Context context) {
super(options);
expansionsCollection.openOnlyOne(true);
this.context = context;
}
#Override
protected void onBindViewHolder(#NonNull RecyclerHolder holder, int position, #NonNull Types_Item model) {
expansionsCollection.add(holder.getExpansionLayout());
holder.textView.setText(model.getName());
Glide.with(holder.imageView.getContext())
.load(model.getImageURL())
.into(holder.imageView);
CheckedTextView[] textView = new CheckedTextView[model.getProblems().size()];
holder.problems.removeAllViews();
for (int i = 0; i < model.getProblems().size(); i++){
textView[i] = new CheckedTextView(context);
textView[i].setText(model.getProblems().get(i));
textView[i].setPadding(10,10,10,10);
textView[i].setTextSize(15);
int finalI = i;
textView[i].setOnClickListener(v -> {
if (textView[finalI].isChecked()){
textView[finalI].setChecked(false);
textView[finalI].setCheckMarkDrawable(0);
}else {
textView[finalI].setChecked(true);
textView[finalI].setCheckMarkDrawable(R.drawable.checked);
}
});
holder.problems.addView(textView[i]);
}
}
#NonNull
#Override
public RecyclerHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return RecyclerHolder.buildFor(parent);
}
public final static class RecyclerHolder extends RecyclerView.ViewHolder {
private static final int LAYOUT = R.layout.item_types;
ExpansionLayout expansionLayout;
TextView textView;
ImageView imageView;
LinearLayout problems;
public static RecyclerHolder buildFor(ViewGroup viewGroup){
return new RecyclerHolder(LayoutInflater.from(viewGroup.getContext()).inflate(LAYOUT, viewGroup, false));
}
public RecyclerHolder(View itemView) {
super(itemView);
expansionLayout = itemView.findViewById(R.id.expansionLayout);
textView = itemView.findViewById(R.id.type_name);
imageView = itemView.findViewById(R.id.type_image);
problems = itemView.findViewById(R.id.problems_list);
}
public ExpansionLayout getExpansionLayout() {
return expansionLayout;
}
}
}
make an interface class and bind this interface into constructor of adapter class.
public interface CustomDialogListener {
void onItemClicked(CheckedTextView checkedTextView);
}
this is for adapter class
private CustomDialogListener mViewClickListener;
public ProductsAdapter(Context context,boolean status) {
this.context = context;
this.status = status;
this.mViewClickListener = (CustomDialogListener) context;
}
and assign interface class method on your required action like onClick on any view.
textView[i].setOnClickListener(v -> {
if (textView[finalI].isChecked()){
textView[finalI].setChecked(false);
textView[finalI].setCheckMarkDrawable(0);
}else {
textView[finalI].setChecked(true);
textView[finalI].setCheckMarkDrawable(R.drawable.checked);
}
listener.onItemClicked(textView);
});
add implementation of interface in parent activity class and override the interface method.
public class ParentActivity extends AppCompatActivity implements
YourAdapter.CustomDialogListener {
#Override
public void onItemClicked(CheckedTextView checkedTextView) {
//Log.d("Item clicked", checkedTextView.isChecked()+"");
}
}
thats the way to track event of recyclerView.
hope i made myself clear.

How to get dataset data from EditText in String format?

I want to get link data in OnClickListener so I have created array Model with an object and store all data which is dynamic.
now I want to extract data so I have use array object to get data. like
I want to link data with string format and I use String urls=object.link; and when I generate toast it shows me Null.
So please Tell me How can I get link data into String Format so I can pass it on Uri.parse(urls));
File Code:
package com.ejobbox.ejobbox;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class RecyclerViewAdapter extends RecyclerView.Adapter{
private ArrayList<Model> dataset;
private Context mContext;
public RecyclerViewAdapter(ArrayList<Model> mlist, Context context) {
this.dataset=mlist;
this.mContext=context;
}
public static class ImageTypeViewHolder extends RecyclerView.ViewHolder{
TextView title,subtitle,link,date;
ImageView imageView;
public ImageTypeViewHolder(View itemView){
super(itemView);
this.title=(TextView)itemView.findViewById(R.id.title);
//this.link=(TextView)itemView.findViewById(R.id.link);
this.subtitle=(TextView) itemView.findViewById(R.id.subtitle);
this.imageView=(ImageView) itemView.findViewById(R.id.icon);
this.date=(TextView)itemView.findViewById(R.id.date);
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.postdetails,parent,false);
return new ImageTypeViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final Model object=dataset.get(position);
((ImageTypeViewHolder) holder).title.setText(object.title);
((ImageTypeViewHolder) holder).subtitle.setText(object.subtitle);
//((ImageTypeViewHolder) holder).link.setText(object.link);
((ImageTypeViewHolder) holder).date.setText((CharSequence) object.date);
((ImageTypeViewHolder) holder).title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String urls=object.link;
Toast.makeText(mContext,urls, Toast.LENGTH_SHORT).show();
Intent browserIntent = new Intent(
Intent.ACTION_VIEW,
Uri.parse(urls));
mContext.startActivity(browserIntent);
}
});
}
#Override
public int getItemCount() { return dataset.size();}
}
Use the getText() method of the link object of EditText.
Do this:
String urls = ((ImageTypeViewHolder) holder).link.getText().toString();
But before this, remove the lines you have commented out.
((ImageTypeViewHolder) holder).title.setText(object.title);
I don't know why u casting here use holder directly so instead of the above line use this
holder.title.setText(object.title)
this will work perfectly and if it didn't` work plz let me know

How do I update a SQLite row from a ListView item?

I have an application that uses sqlite, it stores information about hardware store items and displays them in a ListView, this list view shows the name of the item, the price, the quantity, and the supplier. And each list item also has a Sell button and when I click the button it is supposed to subtract 1 from that specific item's quantity and update the database, but since the button is created in the CursorAdapter Im not sure how to access the database and update it.
This is my CursorAdapter:
package com.example.android.inventoryapp;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.android.inventoryapp.data.InventoryContract.InventoryEntry;
public class InventoryCursorAdapter extends CursorAdapter {
public InventoryCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView itemNameView = view.findViewById(R.id.item_name);
TextView itemPriceView = view.findViewById(R.id.item_price);
TextView itemQuantityView = view.findViewById(R.id.item_quantity);
TextView itemSupplierView = view.findViewById(R.id.item_supplier);
ImageView sellButton = view.findViewById(R.id.sell_button);
int nameColumnIndex = cursor.getColumnIndex(InventoryEntry.COLUMN_ITEM_NAME);
int priceColumnIndex = cursor.getColumnIndex(InventoryEntry.COLUMN_ITEM_PRICE);
int quantityColumnIndex = cursor.getColumnIndex(InventoryEntry.COLUMN_ITEM_QUANTITY);
int supplierColumnIndex = cursor.getColumnIndex(InventoryEntry.COLUMN_ITEM_SUPPLIER);
int quantity = cursor.getInt(quantityColumnIndex);
String name = cursor.getString(nameColumnIndex);
String price = String.valueOf(cursor.getInt(priceColumnIndex)) + context.getString(R.string.currency_symbol);
String quantityStr = String.valueOf(quantity);
String supplier = cursor.getString(supplierColumnIndex);
itemNameView.setText(name);
itemPriceView.setText(price);
itemQuantityView.setText(quantityStr);
itemSupplierView.setText(supplier);
}
}
In your activity that holds the adapter reference, create an inner class something like:
public class MyClickListener {
public void handleClick(Item item) {
// access your DB here, {item} is available if you need the data
}
}
then when you create your adapter
myAdapter = new InventoryCursorAdapter(context, cursor, new MyClickListener());
save the reference to that click listener in your adapter.
then in the adapter's BindView method (if you need the item data to update the database, pass it through the click listener)
sellButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Item item = myItemSet.get(position);
myListener.handleClick(item);
}
});

Android: Implementing mopub native ads in recyclerview gives incorrect item positions and IndexOutOfBoundsException

In my android app I'm trying to implement mopub native ads. Before using these native ads my app was functioning correctly as expected. Now it gives outofbound exceptions and incorrect items when list item is clicked. I'm using recyclerview and using infinite scrolling, it gets item from my api and displays item correctly, but when clicking on item it gives incorrect item.
Here is my recyclerview adapter below.
package com.example.adapters;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.MyApplication;
import com.example.R;
import com.example.events.ErrorLoadingFeed;
import com.example.events.FeedLoaded;
import com.example.events.LoadMoreFeed;
import com.example.model.Post;
import com.example.model.Pagination;
import com.example.ui.InfoActivity;
import com.example.utils.MyAppConstants;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import java.util.List;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Header;
import retrofit.client.Response;
/**
* Created by starwar on 08/09/15.
*/
public class PostRecycleAdapter extends RecyclerView.Adapter<com.example.adapters.PostRecycleAdapter.PostViewHolder> implements Callback<List<Post>> {
private Context mContext;
private List<Post> mPosts;
// Allows to remember the last item shown on screen
private int lastPosition = -1;
// Pagination
private Pagination mPagination;
public PostRecycleAdapter(Context context, List<Post> posts) {
mContext = context;
mPosts = posts;
}
#Override
public PostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
PostViewHolder viewHolder = new PostViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(PostViewHolder holder, int position) {
holder.bindPost(mPosts.get(position));
// Here you apply the animation when the view is bound
setAnimation(holder.mPostName, position);
//check for last item
if ((position >= getItemCount() - 1)) {
// Loading next set of list items on scroll
if (mPagination != null && !mPagination.getOutOfRange() && mPagination.getNextPage() != null){
MyApplication.bus.post(new LoadMoreFeed(mPagination));
}
}
}
#Override
public int getItemCount() {
return mPosts == null ? 0 : mPosts.size();
}
/**
* Here is the key method to apply the animation
*/
private void setAnimation(View viewToAnimate, int position)
{
// If the bound view wasn't previously displayed on screen, it's animated
if (position > lastPosition)
{
Animation animation = AnimationUtils.loadAnimation(mContext, android.R.anim.slide_in_left);
viewToAnimate.startAnimation(animation);
lastPosition = position;
}
}
public class PostViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView mPostName;
public ImageView mAnchorImage;
public PostViewHolder(View itemView) {
super(itemView);
mPostName = (TextView) itemView.findViewById(R.id.postName);
mAnchorImage = (ImageView) itemView.findViewById(R.id.anchorImage);
itemView.setOnClickListener(this);
}
public void bindPost(Post post) {
mPostName.setText(post.getName());
String postImage = post.getPostImage();
Picasso.with(mContext)
.load(postImage)
.placeholder(R.drawable.avatar_empty)
.into(mAnchorImage);
}
#Override
public void onClick(View view) {
int position = getAdapterPosition(); // gets item position
Post post = mPosts.get(position);
int postId = post.getId();
String postName = post.getName();
Intent intent = new Intent(mContext, InfoActivity.class);
intent.putExtra(MyAppConstants.POST_ID, postId);
intent.putExtra(MyAppConstants.POST_NAME, postName);
mContext.startActivity(intent);
}
}
#Override
public void success(List<Post> posts, Response response) {
if (mPosts == null) {
mPosts = posts;
} else {
mPosts.addAll(posts);
}
notifyDataSetChanged();
List<Header> headerList = response.getHeaders();
for(Header header : headerList) {
if ("X-Pagination".equals(header.getName())) {
Gson gson = new Gson();
mPagination = gson.fromJson(header.getValue(), Pagination.class);
}
}
MyApplication.bus.post(new FeedLoaded(mPagination));
}
#Override
public void failure(RetrofitError error) {
Log.d("Call", " : Failed => " + error);
MyApplication.bus.post(new ErrorLoadingFeed(error));
}
public void clearData() {
if (mPosts != null) {
mPosts.clear();
notifyDataSetChanged();
}
}
public List<Post> getPosts() {
return mPosts;
}
}
And I'm using guide given here to show ads
https://dev.twitter.com/mopub/native/native-android-sdk-integration
Please help. what I can/should do to resolve this.
Thanks in advance.
I know this is an old question, but I was looking for the answer for a couple of hours. Probably I'll save someone's time with this solution.
If you will look carefully documentation here: https://github.com/mopub/mopub-android-sdk/wiki/Native-Ads-with-Recycler-View you will find this:
If you register any data observers on your original Adapter, you should instead register them on the MoPubRecyclerAdapter so they will receive messages with the adjusted position of content items. If you do not do this, the positions you receive for insertion and removal messages may be inaccurate. Be sure to check isAd(position) and use MoPubRecyclerAdapter#getOriginalPosition if you need the position of the item in your local adapter.
So, to get real position, it is necessary to use MoPubRecyclerAdapter.getOriginalPosition(position_in_your_adapter) method.

Categories

Resources