Trouble with intent in RecyclerView - android

I started in the android programming and and I encountered a problem when i tried to send data from my Adapter to an another activity
.
I want to show the content of "description" in my other activity when I click on an item.
MyAdapter class :
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private final List<FakeNews> list = FakeNewsList.all;
#Override
public int getItemCount() {
return list.size();
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.list_cell, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
FakeNews pair = list.get(position);
holder.display(pair);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private final TextView name;
private final TextView description;
private FakeNews currentPair;
public MyViewHolder(final View itemView) {
super(itemView);
name = ((TextView) itemView.findViewById(R.id.name));
description = ((TextView) itemView.findViewById(R.id.description));
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MyViewHolder.this ,Affich.class);
intent.putExtra("description", String.valueOf((description)));
startActivity(intent);
}
});
}
public void display(FakeNews pair) {
currentPair = pair;
name.setText(pair.title);
}
}
}
Can someone help me?

I assume that you do not really want to pass the TextView to your next activity, but the content which is shown in it. Also, you need to pass a Context to the Intent and startActivity() is a method of an activity, so you need to call it on the context:
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext() ,Affich.class);
intent.putExtra("description", description.getText().toString());
view.getContext().startActivity(intent);
}
});

Pass the Context or Activity instance into your adapter class.
then while starting new Activity and suppose instance variable is mContext use like this-
Intent intent = new Intent(mContext ,Affich.class);
intent.putExtra("description", String.valueOf((description)));
mContext.startActivity(intent);

To pass value from TextView to your new activity, do this:
intent.putExtra("description", description.getText().toString());
on your new activity, get the description value using:
String descriptionValue = getIntent().getStringExtra("description");

Related

item.view on clickListener does not work with my viewholder

I've created an adapter for my Category gridview to show in my Main activity.
Categories are shown inside a CardView.
In order to click on each category, i can only access by the image or the text in the viewholder. that's not ideal, as you have to clicl exactly on the image to open new activity.
I would love to add the "itemview" to be able to click in any point of the cardview. I did it, but it does not work. I can only see the click but nothing happens.
Something like this:
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, categoryModel.getCatName(), Toast.LENGTH_SHORT).show();
}
});
My Adapter:
public class categoryCardViewAdpt extends RecyclerView.Adapter<categoryCardViewAdpt.ViewHolder> {
CategoryModel[] categoryModels;
Context context;
public categoryCardViewAdpt (CategoryModel[] categoryModels, MainActivity activity){
this.categoryModels = categoryModels;
this.context = activity;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView catImageView;
public TextView catTv;
public ViewHolder(#NonNull View itemView) {
super(itemView);
catImageView = (ImageView) itemView.findViewById(R.id.category_img2);
catTv = (TextView) itemView.findViewById(R.id.category_name_2);
}
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.card_view_layout,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final CategoryModel categoryModel = categoryModels[position];
holder.catTv.setText(categoryModel.getCatName());
holder.catImageView.setImageResource(categoryModel.getCatImage());
holder.catImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Toast.makeText(context, categoryModel.getCatName(), Toast.LENGTH_SHORT).show();
if (categoryModel.getCatName().equals(R.string.farina)){
Intent intent = new Intent(context, FarinaActivity.class);
context.startActivity(intent);
}
else if (categoryModel.getCatName().equals(R.string.farina_inverso)){
Intent intent = new Intent(context, FarinaInversoActivity.class);
context.startActivity(intent);
//overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
else if (categoryModel.getCatName().equals(R.string.alcol)){
Intent intent = new Intent(context, AlcolActivity.class);
context.startActivity(intent);
}
else if (categoryModel.getCatName().equals(R.string.panna)){
Intent intent = new Intent(context, PannaActivity.class);
context.startActivity(intent);
}
else if (categoryModel.getCatName().equals(R.string.chocolate)){
Intent intent = new Intent(context, ChocoActivity.class);
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return categoryModels.length;
}
}
your holder.catImageView is in your ItemView. so the click event may intercepted by ItemView.
Do not use holder.catImageView.setOnClickListener
use : holder.itemView.setonClickListener.

I am failing to make a succesful indent from adapter

I am setting this adapter for an RecyclerView, I am failing to make an indent from that adapter I don't know why can some body guide me what is going on here because I am not an expert in programming as well in this android.
Below is my Adapter class and Activity class.
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private String[] mDatasetname;
private Integer[] mexp;
private Context context;
public ToggleButton select;
Integer selectedcountint=0;
private Bitmap[] mpro;
private String[] mloc;
private String[] mobj;Context m;
private String[] mselected;
public ArrayList<String> nselected = new ArrayList<>();
public static class MyViewHolder extends RecyclerView.ViewHolder{
public CardView mCardView;
public TextView mTextView;
public TextView texp;
public Button pdf;
public ToggleButton select;
public ImageView pro;
public TextView loc;
public View layout;
Context context;
private RecyclerView.ViewHolder s;
public MyViewHolder(View v){
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
mTextView = (TextView) v.findViewById(R.id.tv_text);
texp = (TextView) v.findViewById(R.id.setexp);
pdf = (Button) v.findViewById(R.id.moreinfo);
select = (ToggleButton) v.findViewById(R.id.select);
pro = (ImageView) v.findViewById(R.id.setpropic);
loc = (TextView) v.findViewById(R.id.setlocation);
}
void bind(String name, Integer exp, String location, final Bitmap image, final String obj ) {
mTextView.setText(name);
texp.setText(String.valueOf(exp)+" yrs");
pro.setImageBitmap(image);
loc.setText(location);
pdf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Dashboard.this, com.parse.starter.View.class);
intent.putExtra("no", "6382551203");
startActivity(intent);
}
});
}
}
public MyAdapter(Context s,String[] myDataset,Integer[] exp,Bitmap[] pro,String[] loc,String[] obj){
mDatasetname = myDataset;
mexp=exp;
mpro=pro;
mloc=loc;
mobj=obj;
m=s;
}
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
context=parent.getContext();
View vs = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item, parent, false);
MyViewHolder vh = new MyViewHolder(vs);
return vh;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position){
holder.bind(mDatasetname[position],mexp[position],mloc[position],mpro[position],mobj[position]);
}
#Override
public int getItemCount() { return mDatasetname.length; }
}
Solution:
Instead of this:
Intent intent = new Intent(Dashboard.this, com.parse.starter.View.class);
intent.putExtra("no", "6382551203");
startActivity(intent);
Write like this:
Intent intent = new Intent(Dashboard.this, (your_destination_class_name).class);
intent.putExtra("no", "6382551203");
startActivity(intent);
For Example:
Intent intent = new Intent(Dashboard.this, RegisterActivity.class);
intent.putExtra("no", "6382551203");
startActivity(intent);
If you're destination class name is View.class then change it to something else.
If the above method doesn't work,
Replace:
View vs = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item, parent, false);
with:
View vs = LayoutInflater.from(m).inflate(R.layout.card_item, parent, false);
and try. Hope it works.
first make constructor, adapter wont work with out constructor, its a big miss please check
holder.pdf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,YourIndentClassName.class);
intent.putExtra("no", "6382551203");
context.startActivity(intent);
}
});
Edit your code with this:
pdf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, com.parse.starter.View.class/*should be a proper class name*/);
intent.putExtra("no", "6382551203");
context.startActivity(intent);
}
});
holder.pdf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,YourIndentClassName.class);
intent.putExtra("no", "6382551203");
context.startActivity(intent);
}
});
strong text
use this code in your onBindViewHolder method of RecyclerVieAdapter

Alternative to Switch Case in android

I have a recyclerview with an 30 images and on click of particular image i am opening a new activity which shows a different image.I have uploaded my images to a server and accessing the image from there. When my activity is opened on click ofrecyclerview` i am passing the position through intent so that i can know which image was clicked,then i am using switch case in my activity and load whatever image i want.I have written 30 cases of switch as i have 30 images.Is there any alternative to this.I don't want to use if and else if.
public class ModelLineUpAdapter extends RecyclerView.Adapter<ModelLineUpAdapter.MyViewHolder> {
private Context context;
private List<Bikers> bikersList;
public ModelLineUpAdapter(List<Bikers> bikersList,Context context) {
this.bikersList=bikersList;
this.context = context;
}
public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView bikesImageView;
public TextView nameTextView, priceTextView;
private Button brocheurebutton;
private final Context context;
public MyViewHolder(View itemView) {
super(itemView);
context = itemView.getContext();
bikesImageView = itemView.findViewById(R.id.bikelistitemImageview);
nameTextView = itemView.findViewById(R.id.bikelistitemname);
priceTextView = itemView.findViewById(R.id.bikelistitemprice);
brocheurebutton = itemView.findViewById(R.id.bikelistitembutton);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ModelLineUpInnerActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("position",getAdapterPosition());
context.startActivity(intent);
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.bikelistitem, null);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Bikers bikers = bikersList.get(position);
holder.nameTextView.setText(bikers.getBikename());
holder.priceTextView.setText(bikers.getBikeprice());
Glide.with(context).load(bikers.getBikeImageUrl()).into(holder.bikesImageView);
}
#Override
public int getItemCount() {
//Log.i(TAG, "getItemCount: "+bikersList.size());
return bikersList == null ? 0 : bikersList.size();
}
}
just pass image url with intent and recieve in your ModelLineUpInnerActivity
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ModelLineUpInnerActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("position",getAdapterPosition());
intent.putExtra("IMG",bikersList.get(getAdapterPosition()).getBikeImageUrl());
context.startActivity(intent);
}

How to edit and update Recyclerview item?

I'm building a to do app and I'm trying to add the edit function. When an item is clicked, it takes the user to EditItemActivity.java where the user can edit that particular to do. For example, it could be edited from "Do Homework" to "Go to the gym".
So far I've been able to get the item that was clicked and have its text display in the EditText field that will be used for the editing. However, I couldn't figure out how to save the edit when the button is clicked and go back to the main screen.
So in my adapter, I'm calling the intent with extra:
public class ToDoAdapter extends RecyclerView.Adapter<ToDoAdapter.ViewHolder> {
private List<ToDoData> toDoList;
private Context context;
public ToDoAdapter(List<ToDoData> todoList, Context context) {
this.toDoList = todoList;
this.context = context;
}
public ToDoAdapter(Context context){}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView todoView;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
todoView = itemView.findViewById(R.id.to_do_display);
}
#Override
public void onClick(View view) {
Toast.makeText(context, "position = " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, EditItemActivity.class);
intent.putExtra("data", todoView.getText());
intent.putExtra("position", getAdapterPosition());
context.startActivity(intent);
}
}
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.to_do_list_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ToDoData todoPosition = toDoList.get(position);
holder.todoView.setText(todoPosition.getToDo());
}
#Override
public int getItemCount() {
return (toDoList == null) ? 0 : toDoList.size();
}
}
And in my EditItemActivity.java, I'm retrieving the text and placing it in my EditText field:
public class EditItemActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_item);
final ToDoData toDoData = new ToDoData(this);
final ToDoAdapter toDoAdapter = new ToDoAdapter(this);
final EditText editToDo = (EditText)findViewById(R.id.edit_todo_item);
Button button = (Button)findViewById(R.id.save_changes);
final String text = getIntent().getExtras().getString("data");
editToDo.setText(text);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(editToDo.getText().toString() != text){
toDoData.setToDo(editToDo.getText().toString());
toDoAdapter.notifyDataSetChanged();
finish();
}
}
});
}
}
But I don't know how to go further than this unfortunately.
what you will do is that :
1- send view position to edit activity
#Override
public void onClick(View view) {
Toast.makeText(context, "position = " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, EditItemActivity.class);
intent.putExtra("data", todoView.getText());
intent.putExtra("position", getAdapterPosition());
context.startActivity(intent);
}
2- in edit activity
final String position= getIntent().getExtras().getString("position");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new intent(this, [PREVIOUS_ACTIVITY]);
intent.putExtra("new data", todoView.getText().toString());
intent.putExtra("position", position);
startActivity(intent);
}
});
4 - in activity which contains the adapter create hashmap hold the upcoming extras (position - text) as ( key - value )
HashMap<Integer, String> hashMap = new HashMap<>();
hashMap.put(position, newText);
5- then pass this hash map to your adapter class when you create its instance. and in onBindViewHolder() check the upcoming view position is contained in hashmap if yes set your new data
if(hashMap.containsKey(position))
view.todoView.setText(hashMap.get(position));

Start new Intent from RecyclerViewAdapter

I have RecyclerViewAdapter :
public class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewAdapter.MyViewHolder> {
private List<Cards> items;
private int itemLayout;
Context context;
public RecycleViewAdapter(List<Cards> items, int itemLayout) {
this.items = items;
this.itemLayout= itemLayout;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=LayoutInflater.from(parent.getContext()).inflate(itemLayout,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Cards item=items.get(position);
holder.title.setText(item.getName());
String cardvalue = item.getCountry();
String cardCode = item.getCode();
String cardCountry = item.getCountry();
}
#Override
public int getItemCount() {
return items.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView title;
public MyViewHolder(View itemView) {
super(itemView);
title= (TextView) itemView.findViewById(R.id.listText);
title.setOnClickListener(this);
}
#Override
public void onClick(View v) {
}
}
}
and I need to start new Intent (OnCardsSelected.class) , but I cant add this line to my method onClick:
Intent intent = new Intent (this, OnCardSelected.class);
I don't understand whats I do wrong, I just need to start Intent and put some information to this intent, I read some manuals but didn't understand theirs explanation so I hope u will help me .Thanks
Probably trying to start Activity from onClick method then use v.getContext() instead of this(which refer to onClick method context) as first parameter to Intent constructor :
Intent intent = new Intent (v.getContext(), OnCardSelected.class);
Add this line of code in your onBindViewHolder method
Intent intent = new Intent(v.getContext(), YourClassName.class);
v.getContext().startActivity(intent);
And you're good to go.
public RecycleViewAdapter(Context context,List<Cards> items, int itemLayout) {
this.mContext = context;
this.items = items;
this.itemLayout= itemLayout;
}
...
Intent intent = new Intent(mContext, YOUR_ACTIVITY.class);
mContext.startActivity(intent)
Intent i = new Intent(holder.itemView.getContext(), NewOnCLickAccount.class);
holder.itemView.getContext().startActivity(i);
works fine for me.
This can save someone, especialy one with different activities to open for each item click. I was in same situation.
Create a model class (or restructure your old one) to add Intent . Here is my example.
Class SampleModel{
String sampleString;
Intent sampleIntent;
public SampleModel(String sampleString, Intent sampleIntent){
this.sampleString = sampleString;
this.sampleIntent = sampleIntent;
}
//add getters
}
In your recyclerview adapter add Context (let's call it sampleContext) and ArrayList (lets call it list)that will carry your model.
In your onBindViewHolder
SampleModel model = list.get(position);
//inside holder.viewclick setOnClickListner, here we open intent
sampleContext.starActivity(model.getIntent);
The rest is just like normal recyclerview process. i.e
SampleModel model = new SampleModel ("sample text", new Intent(this, "AnotherActivity.class));
Here is an example of me using an OnClickListener inside the adapter's BindViewHolder
#Override
public void onBindViewHolder(#NonNull ItemHolder holder, int position) {
Item playerItem = (Item) itemList.get(position);
itemName = playerItem.getName();
itemPosition = holder.getAdapterPosition();
itemHolder = holder;
//Sets Text
holder.name.setText(itemName);
//holder.playerName.setTag(R.string.listSize, playerList.size());
holder.name.setTag(position);
//holder.image.setImageAlpha(playerItem.getImage());
holder.image.setImageResource(playerItem.getImage());
holder.image.setTag(position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//goes to new activity passing the item name
Intent intent = new Intent(itemHolder.itemView.getContext(), MapActivity.class);
Bundle b = new Bundle();
//get text for current item
String textGet = itemName;
//put text into a bundle and add to intent
intent.putExtra("text", textGet);
//get position to carry integer
intent.putExtra("position", itemPosition);
intent.putExtras(b);
//begin activity
itemHolder.itemView.getContext().startActivity(intent);
}
});
}
You already Passing the Context into the adapter. Therefore inside the onBindViewHolder() you can create the intent.
Intent intent = new Intent(context,OnCardsSelected.class);
context.startActivity(intent);

Categories

Resources