When I start the DbActivity (when app is started the firt time), the animation of the RecyclerView is not working (maybe its working but is not showed), but if I reopen the Activity it works fine.
I tryed to move the istruction used to fetch data and creating the adapter on the onStart() method and it didn't work.
What is the problem ?
DbActivity code:
public class DbActivity extends AppCompatActivity {
private Activity contesto;
private ImageButton cercaBtn;
private EditText SSIDEditText;
private EditText PositionEditText;
private DBManager manager;
private ArrayList<Rete> reti;
public static RecyclerView recyclerView;
public static DatabaseRecyclerViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_db);
this.contesto = this;
// dbManager init.
manager = DBManager.getDbInstance(getApplicationContext());
// searching button
cercaBtn = findViewById(R.id.elimina_db);
// searching EditText
SSIDEditText = findViewById(R.id.searchSSID);
PositionEditText = findViewById(R.id.searchPosition);
// adapter creation
adapter = new DatabaseRecyclerViewAdapter();
// recyclerview init.
recyclerView = (RecyclerView) findViewById(R.id.cursor_listview);
recyclerView.setLayoutAnimation(AnimationUtils.loadLayoutAnimation(this, R.anim.layout_animation));
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
// getting data
reti = manager.query();
// updating adapter data
adapter.setReti(reti);
// adding listeners
setListeners();
}
...
}
CustomAdapter:
public class DatabaseRecyclerViewAdapter extends RecyclerView.Adapter<DatabaseRecyclerViewAdapter.ViewHolder> {
ArrayList<Rete> reti;
public DatabaseRecyclerViewAdapter(ArrayList<Rete> reti) {
setReti(reti);
}
public DatabaseRecyclerViewAdapter() {
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_cursoradapter, parent, false);
DatabaseRecyclerViewAdapter.ViewHolder holder = new DatabaseRecyclerViewAdapter.ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
Rete tmp = reti.get(position);
//holder.linearLayout.setAnimation(AnimationUtils.loadAnimation(holder.view.getContext(), R.anim.item_animation_fall_down));
// updating elements text
holder.SSID.setText(tmp.getSSID());
holder.info.setText(tmp.getDettagli());
holder.level.setText(tmp.getLevel());
// decrypting password
try {
holder.password.setText(AESCrypt.decrypt(tmp.getPassword()));
} catch (Exception e) {
holder.password.setText("");
Log.d("ENCRIPTION", "FAIL: " + e);
}
// makes password field clickable
holder.password.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// printing the alert box used to edit the password
AlertBoxManager.displayUpdatePasswordAlertBox((Activity) view.getContext() , holder.password, holder.SSID.getText().toString());
}
});
// getting lat & lon
Double lat = tmp.getLat();
Double lon = tmp.getLon();
// commute coordinates into human readable string
HumanPosition converter = new HumanPosition(holder.view.getContext());
holder.position.setText(converter.coordToString(lat, lon));
}
#Override
public int getItemCount() {
return reti.size();
}
public void setReti(ArrayList<Rete> reti) {
this.reti = reti;
notifyDataSetChanged();
DbActivity.recyclerView.scheduleLayoutAnimation();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView SSID;
private TextView info;
private TextView level;
private TextView password;
private TextView position;
private LinearLayout linearLayout;
private View view;
public ViewHolder(#NonNull final View itemView) {
super(itemView);
view = itemView;
//linearLayout = (LinearLayout) itemView.findViewById(R.id.dbRecyclerViewLinearLayout);
SSID = (TextView) itemView.findViewById(R.id.cursor_SSID);
info = (TextView) itemView.findViewById(R.id.cursor_dettagli);
level = (TextView) itemView.findViewById(R.id.cursor_level);
password = (TextView) itemView.findViewById(R.id.cursor_password);
position = (TextView) itemView.findViewById(R.id.cursor_position);
itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
AlertBoxManager.displayDeleteReteAlertBox((Activity) view.getContext(), SSID.getText().toString());
return false;
}
});
}
}
}
Related
program crashed. and I get this message:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.mob3000.group11.Cars.getImgurl()' on a null object reference
at com.mob3000.group11.Reservation.onCreate(Reservation.java:57)
I want to pass info to another activity
#Reservation class
public class Reservation extends AppCompatActivity {
ImageView imgMakeRes;
TextView pricMakeRes;
TextView brandMakeRes;
TextView girMakeRes;
TextView seatMakeRes;
public static final String BOOKING_INFORMATION= "booking_information";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reservation);
imgMakeRes = (ImageView) findViewById(R.id.imgMakeReservation);
pricMakeRes = (TextView) findViewById(R.id.pricMakereservation);
brandMakeRes = (TextView) findViewById(R.id.brandMakeReservation);
girMakeRes = (TextView) findViewById(R.id.girMakeReservation);
seatMakeRes = (TextView) findViewById(R.id.seatMakeReservation);
Cars cars = getIntent().getParcelableExtra(BOOKING_INFORMATION);
Glide.with(this).load(cars.getImgurl()).into(imgMakeRes);
pricMakeRes.setText((int) cars.getPrice());
brandMakeRes.setText(cars.getBrand());
girMakeRes.setText(cars.getGir());
seatMakeRes.setText(cars.getSeats());
Adapter class
public class FirestoreAdapter extends FirestoreRecyclerAdapter<Cars,FirestoreAdapter.myViewHolder> {
private OnListItemClick onListItemClick;
private Context context;
private ArrayList<Cars> listCars;
public FirestoreAdapter(#NonNull FirestoreRecyclerOptions<Cars> options,OnListItemClick onListItemClick) {
super(options);
this.onListItemClick=onListItemClick;
}
#Override
protected void onBindViewHolder(#NonNull myViewHolder holder, int position, #NonNull Cars cars) {
holder.textpri_ce.setText(cars.getPriceWithLabel());
holder.textbra_nd.setText(cars.getBrand());
holder.textg_ir.setText(cars.getGir());
holder.textsea_ts.setText(cars.getSeatsWithLabel());
Glide.with(holder.img.getContext()).load(cars.getImgurl()).into(holder.img);
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.car_items,
parent, false);
return new myViewHolder(view);
}
public class myViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
CircleImageView img;
TextView textpri_ce,textbra_nd,textg_ir,textsea_ts;
public myViewHolder( View itemView) {
super(itemView);
img = (CircleImageView) itemView.findViewById(R.id.img1);
textpri_ce= (TextView) itemView.findViewById(R.id.textprice);
textbra_nd= (TextView)itemView.findViewById(R.id.textbrand);
textg_ir= (TextView)itemView.findViewById(R.id.textgir);
textsea_ts= (TextView)itemView.findViewById(R.id.textseats);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
onListItemClick.onItemClick(getItem(getAdapterPosition()),getAdapterPosition());
}
}
public interface OnListItemClick{
void onItemClick(Cars snapshot, int position);
}
}
Booking class
public class booking_activity extends AppCompatActivity implements FirestoreAdapter.OnListItemClick{
FirebaseFirestore firebaseFirestore;
RecyclerView mFirestoreList;
private ArrayList<Cars> listCars;
Context context;
FirestoreAdapter adapter;
private static final String TAG = "booking_activity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booking);
// calling function adapetWithRecycle() which contains adapter and recycleview----
adapetWithRecycle();
//--------------------------------------------------------------------------
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.toolbar_title);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// here we call functions for all the spinners to Find Id and set adapters.
priceSpinner();
brandSpinner();
girSpinner();
seatsSpinner();
}
// onStop and onStart for recycle view
#Override public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
protected void adapetWithRecycle() {
firebaseFirestore = FirebaseFirestore.getInstance();
mFirestoreList = findViewById(R.id.recview);
Query query = firebaseFirestore.collection("cars");
FirestoreRecyclerOptions<Cars> options = new FirestoreRecyclerOptions.Builder<Cars>()
.setQuery(query, Cars.class)
.build();
adapter = new FirestoreAdapter(options,this);
mFirestoreList.setHasFixedSize(true);
mFirestoreList.setLayoutManager(new LinearLayoutManager(this));
mFirestoreList.setAdapter(adapter);
}
#Override
public void onItemClick(Cars snapshot, int position) {
Intent intent = new Intent(booking_activity.this, Reservation.class);
// intent.putExtra(Reservation.BOOKING_INFORMATION, listCars.get(position));
//intent.putExtra(Reservation.BOOKING_INFORMATION, listCars);
startActivity(intent);
Log.d("ITEM_CLICK","clicked the item: " + position+ " Gear is : " + snapshot.getGir()+
" Price is: "+ snapshot.getPrice()+" , Brand is "+ snapshot.getBrand()+" ,Seats: "+
snapshot.getSeats());
inside your onBindViewHolder() in setText() add listcars.get(position).getPriceWithLable() apply it to the rest of your TextViews
ex. holder.textpri_ce.setText(listcars.get(position).getPriceWithLable());
I am actually working on a group project and I want to develop a functionnality for our application. My goal is to have a list of several items with their images and when I click on an Item of that list I want to have a text pop in the midle of the screen related to that particular item. I'm afraid I might be using the wrong technical Tools to do so. I am actually using a csv file for the list details, an adapter and a viewHolder for the list. Since I have no idea on what is wrong and what to do I link a big part of my code so you can check how I did until now. I can also give you my xml files if you need to check them out, a really big thanks in advance to all the answers and time spent on my problem
I already managed to have my list of items with the title and the picture (text from csv file) of each list item but I'm stuck on how to show a specific text for each ViewHolder.
this is my Adapter
public class Adapter extends RecyclerView.Adapter<ViewHolder> {
List<Departement> list;
Activity activity;
public Adapter(List<Departement> list, Activity activity) {
this.list = list;
this.activity = activity;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int itemType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.departement,viewGroup,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
Departement departement = list.get(position);
viewHolder.bind(departement, activity);
}
#Override
public int getItemCount() {
return list.size();
}
}
my ViewHolder
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView textViewView;
private ImageView imageView;
public ViewHolder(View itemView) {
super(itemView);
textViewView = (TextView) itemView.findViewById(R.id.text);
imageView = (ImageView) itemView.findViewById(R.id.image);
}
public void bind(Departement departement, Activity activity){
textViewView.setText(departement.getText());
String uri = departement.getImageUrl();
int imageResource = activity.getResources().getIdentifier(uri, null, activity.getPackageName());
Drawable res = activity.getResources().getDrawable(imageResource);
imageView.setImageDrawable(res);
}
}
each item of the list is a Departement
public class Departement {
private String text;
private String imageUrl;
public Departement(String text, String imageUrl) {
this.text = text;
this.imageUrl = imageUrl;
}
public String getText() {
return text;
}
public String getImageUrl() {
return imageUrl;
}
public void setText(String text) {
this.text = text;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
}
and finally my fragment
public class FragmentEspecesProches extends Fragment {
public final static char SEPARATOR=',';
private RecyclerView recyclerView;
private List<Departement> departementsList = new ArrayList<>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.fragment_especes_proches, container, false);
ajouterDepartements();
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new GridLayoutManager(this,2));
recyclerView.setAdapter(new Adapter(departementsList, getActivity()));
return view;
}
private void ajouterDepartements() {
ArrayList<String> lines = new ArrayList<>();
ArrayList<String[]> data = new ArrayList<>();
String sep = new Character(SEPARATOR).toString();
lines = UtilitaireResultat.readFile(getActivity().getResources().openRawResource(R.raw.departement));
for(String line : lines){
String[] oneData = line.split(sep);
data.add(oneData);
}
for(int i=0 ; i<data.size() ; i++){
String[] tabStr = data.get(i);
departementsList.add( new Departement( tabStr[2]+" - "+tabStr[3] ,"#drawable/"+tabStr[5] ));
}
}
}
you can implement item click listener like this
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView tvName;
public TextView tvHometown;
private Context context;
public ViewHolder(Context context, View itemView) {
super(itemView);
this.tvName = (TextView) itemView.findViewById(R.id.tvName);
this.tvHometown = (TextView) itemView.findViewById(R.id.tvHometown);
// Store the context
this.context = context;
// Attach a click listener to the entire row view
itemView.setOnClickListener(this);
}
// Handles the row being being clicked
#Override
public void onClick(View view) {
int position = getAdapterPosition(); // gets item position
// if (position != RecyclerView.NO_POSITION) { // Check if an item was deleted, but the user clicked it before the UI removed it
User user = users.get(position);
// We can access the data within the views
Toast.makeText(context, tvName.getText(), Toast.LENGTH_SHORT).show();
// }
}
}
Use onBindViewHolder to handle any interaction on your list items
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
Departement departement = list.get(position);
viewHolder.bind(departement, activity);
viewHolder.itemView.setOnClickListener(//your action//);
}
ItemView is the whole item; you can access your textviews or imageviews as you use it on your bind method,
You can use your bind method to apply listeners.
Handle on click of the item inside your ViewHolder constructor
like ,
public ViewHolder(View itemView) {
super(itemView);
textViewView = (TextView) itemView.findViewById(R.id.text);
imageView = (ImageView) itemView.findViewById(R.id.image);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position=getAdapterPosition();
Toast.makeText(context, list.get(position).getText(), Toast.LENGTH_SHORT).show();
}
});
}
Create your onClickListner interface as
interface RecylerViewItemClickListner
{
void onItemClick(Department item)
}
set the listner in Adapter class
private final RecylerViewItemClickListner mOnClickListener;
public Adapter(List<Departement> list, Activity activity) {
this.list = list;
this.activity = activity;
this.mOnClickListener = activity;
}
Now in ViewHolder class
public void bind(final Departement item, final mOnClickListener listener) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
mOnClickListener.onItemClick(item);
}
});
}
and change onBindViewHolder as below
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(items.get(position), mOnClickListener);
}
Override onItemClick(Department item) in activity
#override
onItemClick(Department item)
{
//show toast here...
}
implement OnClickListener in your ViewHolder class
public class ViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener
{
#Override
public void onClick(View v)
{
//do action
}
}
Implement below method in your ViewHolder class.
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final User currentItem = users.get(getAdapterPosition());
Toast.makeText(mContext,currentItem.getText()+" is selected!",Toast.LENGTH_SHORT).show();
}
});
Problem: I want to go to the user's selected item
But I can not do it Selected position.
How can I get my position and stay in place???
I tried many ways but it was fruitless
Does my code have problems?
Any way to your opinion to help me
enter image description here
Code Adapter :
public class Adapter_Badan extends RecyclerView.Adapter<Adapter_Badan.ViewHolder> {
private Context context;
private List<Modell_Badan> modells;
public Adapter_Badan(Context context, List<Modell_Badan> modells) {
this.modells = modells;
this.context = context;
}
#NonNull
#Override
public Adapter_Badan.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new Adapter_Badan.ViewHolder(LayoutInflater.from(context).inflate(R.layout.layout_badan, parent, false));
}
#Override
public void onBindViewHolder(#NonNull final Adapter_Badan.ViewHolder holder, final int position) {
final Modell_Badan modell = modells.get(position);
holder.title.setText(modell.getTitle());
holder.content.setText(modell.getContent());
Picasso.get().load(modell.getImage()).into(holder.image1);
Picasso.get().load(modell.getImage2()).into(holder.image2);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Handler().postDelayed(new Runnable() {
public void run() {
Intent intent= new Intent(context,Badan.class);
intent.putExtra(Modell.ID,modell.getId());
intent.putExtra(Modell.TITLE,modell.getTitle());
intent.putExtra(Modell.CONTENT,modell.getContent());
intent.putExtra(Modell.IMAGE1,modell.getImage());
intent.putExtra(Modell.IMAGE12,modell.getImage2());
intent.putExtra("id", "1");
context.startActivity(intent);
((Activity)context).finish();
((Activity)context).overridePendingTransition(R.anim.alpha_f,R.anim.alpha_o);
}
}, 20);
}
});
}
#Override
public int getItemCount() {
return modells.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView image1;
private ImageView image2;
private TextView title;
private TextView content;
private RelativeLayout relativeLayout;
public ViewHolder(View itemView) {
super(itemView);
image1 = (ImageView) itemView.findViewById(R.id.image_badan);
image2 = (ImageView) itemView.findViewById(R.id.image2_badan);
title = (TextView) itemView.findViewById(R.id.title_badan);
content = (TextView) itemView.findViewById(R.id.content_badan);
}
}
But after the item is selected, the position is deleted
Can I prove the item's position?
Code Badan :
public class Badan extends AppCompatActivity {
private SharedP_Thems sharedP_thems;
private ImageView image_layout, image_layout2;
private TextView title_, content_;
private SharedPerfern sharedPerfern;
private Shared_Modell shared_modell;
private Adapter_Badan adapter_badan;
int a;
#Override
protected void onCreate(Bundle savedInstanceState) {
sharedPerfern = new SharedPerfern(this);
shared_modell = sharedPerfern.getShared();
sharedP_thems = new SharedP_Thems(this);
if (sharedP_thems.getLoad().equals(true))
setTheme(R.style.dark_them);
else setTheme(R.style.AppTheme);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_badan);
setUpToolbarLayout();
setUpView();
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recy_badanw);
Adapter_Badan adapter_badan=new Adapter_Badan(this, Data_FackeGen.getModellBadan(this));
recyclerView.setLayoutManager( new StaggeredGridLayoutManager(1,StaggeredGridLayoutManager.HORIZONTAL));
recyclerView.setAdapter(adapter_badan);
getInten();
title_.setTextSize(shared_modell.getFonSize());
content_.setTextSize(shared_modell.getFonSize());
}
private void setUpToolbarLayout() {
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.tollbar_badab);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
private void setUpView() {
image_layout = (ImageView) findViewById(R.id.image_badan2w);
image_layout2 = (ImageView) findViewById(R.id.image2_badanw);
title_ = (TextView) findViewById(R.id.title_badanw);
content_ = (TextView) findViewById(R.id.content_badanw);
}
private void getInten() {
Intent intent = getIntent();
int id = intent.getIntExtra(Modell.ID, 0);
String titel = intent.getStringExtra(Modell.TITLE);
String content = intent.getStringExtra(Modell.CONTENT);
int image1 = intent.getIntExtra(Modell.IMAGE1, 2);
int image2 = intent.getIntExtra(Modell.IMAGE12, 2);
Picasso.get().load(image1).into(image_layout);
Picasso.get().load(image2).into(image_layout2);
title_.setText(titel);
content_.setText(content);
}
}
Try moving the following code inside your click listener:
Modell_Badan modell = modells.get(position);
holder.title.setText(modell.getTitle());
holder.content.setText(modell.getContent());
Picasso.get().load(modell.getImage()).into(holder.image1);
Picasso.get().load(modell.getImage2()).into(holder.image2);
The problem was solved
I used the following method and responded
#Override
protected void onPause() {
super.onPause();
bundle = new Bundle();
Parcelable parcelable = recyclerView.getLayoutManager().onSaveInstanceState();
bundle.putParcelable(KEY_RECYCLER_STATE, parcelable);
}
#Override
protected void onResume()
{
super.onResume();
// restore RecyclerView state
if (bundle != null) {
Parcelable parcelable = bundle.getParcelable(KEY_RECYCLER_STATE);
recyclerView.getLayoutManager().onRestoreInstanceState(parcelable);
}
}
Android recyclerview item click event after update Recyclerview
Image description here
Mail 1 READ
Mail 2 Dont Read
In the item the click event I want to do this to me
How can you help make
public class Mesajlar_Adapter extends RecyclerView.Adapter<Mesajlar_Adapter.ViewHolder>{
private List<Mesajlar> resultModels;
private Context context;
public Mesajlar_Adapter(List<Mesajlar> resultModels, Context context) {
this.resultModels = resultModels;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.mesajlar_listview_desing, parent, false);
ViewHolder view_holder = new ViewHolder(v);
return view_holder;
}
public void resetList() {
int size = this.resultModels.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
resultModels.remove(0);
}
this.notifyItemRangeRemoved(0, size);
}
}
public void addItem(Mesajlar item){
this.resultModels.add(item);
this.notifyDataSetChanged();
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.mesaj_id.setText(resultModels.get(position).getMESAJ_ID());
holder.kullanici_id.setText(resultModels.get(position).getKULLANICI());
holder.gelen_detay.setText(resultModels.get(position).getDETAY());
holder.kategori.setText(resultModels.get(position).getKATEGORI());
holder.konu.setText(resultModels.get(position).getKONU());
holder.tarih.setText(resultModels.get(position).getKAYIT_TARIHI());
String a = resultModels.get(position).getOKUNDU();
holder.okunma.setText(a);
if (a.equals("Hayir")){
holder.kategori.setTextColor(Color.BLACK);
holder.kategori.setTextSize(19);
holder.konu.setTextColor(Color.BLACK);
holder.konu.setTextSize(19);
holder.tarih.setTextColor(Color.BLACK);
}
}
#Override
public int getItemCount() {
return resultModels.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
protected TextView mesaj_id;
protected TextView kullanici_id;
protected TextView gelen_detay;
protected TextView konu;
protected TextView kategori;
protected TextView tarih;
protected CheckBox secim;
protected TextView okunma;
public ViewHolder(View view) {
super(view);
this.okunma =(TextView) view.findViewById(R.id.okunma);
this.mesaj_id = (TextView) view.findViewById(R.id.mesaj_id);
this.kullanici_id = (TextView) view.findViewById(R.id.kullanici_id);
this.gelen_detay = (TextView) view.findViewById(R.id.gelen_detay);
this.konu = (TextView) view.findViewById(R.id.Konu);
this.kategori = (TextView) view.findViewById(R.id.Kategori);
this.tarih = (TextView) view.findViewById(R.id.Tarih);
// this.secim = (CheckBox) view.findViewById(R.id.secim);
view.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Intent i=new Intent(context, Mesaj_Detay_Activity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String detay = gelen_detay.getText().toString();
String mesajid = mesaj_id.getText().toString();
String kullaniciid = kullanici_id.getText().toString();
i.putExtra("detay", detay);
i.putExtra("mesaj_id",mesajid);
i.putExtra("kullanici_id",kullaniciid);
context.startActivity(i);
}
}
}
First of all, add this interface for click event
public interface OnRecyclerItemViewClickListener {
void onClicked(int position, Mesajlar jar);
}
Model
public class Mesajlar {
...
boolean isClicked;
public boolean isClicked() {
return icClicked;
}
public void setClicked(boolean isClicked) {
this.isClicked = isClicked;
}
...
}
Adapter
private OnRecyclerItemViewClickListener listener;
public Mesajlar_Adapter(List<Mesajlar> resultModels, Context context, OnRecyclerItemViewClickListener listener) {
...
this.listener = listener;
}
...
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
if (resultModels.get(position).isClicked()) {
// change pressed background color here!
} else {
// change default background color here!
}
holder.itemView.setOnClickListener(v -> {
listener.onClicked(position, resultModels.get(position));
});
...
}
Activity
When you create RecyclerView Adapter, add OnRecyclerItemViewClickListener to constructor of adapter in Activity
Mesajlar_Adapter adapter = new Mesajlar_Adapter(list, context, new OnRecyclerItemViewClickListener {
#Override
public void onClicked(int position, Mesajlar jar) {
jar.setClicked(true);
adapter.notifyItemChanged(position);
Intent i = new Intent(YourActivity.this, Mesaj_Detay_Activity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("detay", jar.getDETAY());
i.putExtra("mesaj_id",jar.getMESAJ_ID());
i.putExtra("kullanici_id", jar.getKULLANICI());
startActivity(i);
}
});
Instead of handling click event in adapter level you can use interface and do it in activity level. Pass the adapter position to the activity, from activity you can do the actual process
see the sample http://wiki.workassis.com/android-recyclerview-example/
I have a question about passing clicked cardview data to activity, and here the full story :
I have an Activity called "Details", which contains 2 TextViews in it's layout, Title & Description .
I have setup a fragment ( tab_1 ) which contain the recyclerview codes and the the items data, each item of those contain : title & description .
What i want :
When the user click the item, it will open the Details Activity, and change Details layout title, with clicked item title, and the same for description .
I've manged to create the other activity as an example, and made intent to start it, plus adding "addOnTouchlistener" thanks to Stackoverflow, i've found the way to make it .
So, how to make this alive? I've tried many ways of the available answers on Stackoverflow, but all of them not working, or not related to my request .
Here are my files :
itemsdata.java :
public class itemsdata {
int CatPic;
String title;
String Descr;
int Exapnd;
int expand_no;
tab_1.java ( fragment )
public class tab_1 extends Fragment implements SearchView.OnQueryTextListener {
private RecyclerView mRecyclerView;
public RecyclingViewAdapter adapter;
private Activity context;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.tab_1, container, false);
mRecyclerView = (RecyclerView)layout.findViewById(R.id.recycler_view);
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener
(getContext(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent i = new Intent(view.getContext(), DetailsActivity.class);
view.getContext().startActivity(i);
}
}));
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new RecyclingViewAdapter(getActivity(),Listed());
mRecyclerView.setAdapter(adapter);
return layout;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
}
#Override
public boolean onQueryTextChange(String query) {
final List<itemsdata> filteredModelList = filter(Listed(), query);
adapter.animateTo(filteredModelList);
mRecyclerView.scrollToPosition(0);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
private List<itemsdata> filter(List<itemsdata> models, String query) {
query = query.toLowerCase();
final List<itemsdata> filteredModelList = new ArrayList<>();
for (itemsdata model : models) {
final String text = model.title.toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
public List<itemsdata> Listed()
{
//Titles Strings
String sys_title1 = getString(R.string.system_item_title_1);
String sys_title2 = getString(R.string.system_item_title_2);
String sys_title3 = getString(R.string.system_item_title_3);
//Description Strings
String sys_descr1 = getString(R.string.system_item_desc_1);
String sys_descr2 = getString(R.string.system_item_desc_2);
String sys_descr3 = getString(R.string.system_item_desc_3);
//Adding New Cards
List<itemsdata> data = new ArrayList<>();
//Categories Icons New Items ** Make It The Same
int[] icons = {
R.drawable.facebook_icon ,
R.drawable.twitter_icon ,
R.drawable.twitter_icon
};
//Expand Button New Items
int[] expandbutton = {
R.drawable.expanded ,
R.drawable.expanded ,
R.drawable.expanded
};
//UnExpand Button New Items
int[] unexpandbutton = {
R.drawable.ca_expand ,
R.drawable.ca_expand ,
R.drawable.ca_expand
};
//Titles New Items
String[] titles = {
sys_title1 ,
sys_title2 ,
sys_title3
};
//Description New Items
String[] Description = {
sys_descr1 ,
sys_descr2 ,
sys_descr3
};
for(int i = 0;i<titles.length && i < icons.length && i < Description.length && i < unexpandbutton.length && i < expandbutton.length ; i++)
{
itemsdata current = new itemsdata();
current.CatPic = icons[i];
current.title = titles[i];
current.Descr = Description[i];
current.expand_no = unexpandbutton[i];
current.Exapnd = expandbutton[i];
data.add(current);
}
return data;
}
}
Details Activity :
public class DetailsActivity extends AppCompatActivity{
TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
title = (TextView)findViewById(R.id.details_title);
}
EDIT : I've made it, i have added a button which open the fragment, and passed the data, in the Adapter, but i want it via tab_1.java, not the Adapter, i mean i want to click on the item to open the fragment, not on a button, here a snap from my Adapter code ( i've added it in OnBindViewHolder )
I've setup a OnClick and implemented the Vew.setOnClick ..etc, but when i click the item, nothing happen.
#Override
public void onBindViewHolder(final MyRecycleViewHolder holder, int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(),DetailsActivity.class);
v.getContext().startActivity(i);
}
});
//Referencing Data
final itemsdata currentobject = mdata.get(position);
//Referencing Items
holder.ProbTitle.setText(currentobject.title);
holder.ProbDescr.setText(currentobject.Descr);
holder.CategoryPic.setImageResource(currentobject.CatPic);
holder.ExpandButton.setImageResource(currentobject.Exapnd);
holder.ExpandNoButton.setImageResource(currentobject.expand_no);
//What Happen When You Click Expand Button .
holder.ExpandButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), DetailsActivity.class);
i.putExtra("TitleKey",holder.ProbTitle.getText().toString());
v.getContext().startActivity(i);
}
}
);
public static class MyRecycleViewHolder extends RecyclerView.ViewHolder
{
SwipeLayout swipeLayout;
//Defining Items .
TextView ProbTitle;
ImageButton ExpandButton;
TextView ProbDescr;
ImageButton ExpandNoButton;
ImageView CategoryPic;
/*
TextView Card_Star;
TextView Card_UnStar;
*/
TextView Card_Share;
//Referencing Resources
public MyRecycleViewHolder(final View itemView) {
super(itemView);
ProbTitle = (TextView) itemView.findViewById(R.id.prob_title);
CategoryPic = (ImageView) itemView.findViewById(R.id.cat_pic);
ProbDescr = (TextView) itemView.findViewById(R.id.prob_descr);
ExpandButton = (ImageButton) itemView.findViewById(R.id.expand_button);
ExpandNoButton = (ImageButton) itemView.findViewById(R.id.expand_no_button);
/*
Card_Star = (TextView) itemView.findViewById(R.id.card_star);
Card_UnStar = (TextView) itemView.findViewById(R.id.card_unstar);
*/
Card_Share = (TextView) itemView.findViewById(R.id.card_share);
swipeLayout = (SwipeLayout) itemView.findViewById(R.id.swipe);
}
create an Interface inside your adapter containing methods. And while implementing your Adapter, those methods will be implemented in your activity and you can perform whatever action you want.
public class Adapter extends RecyclerView.Adapter<MyRecycleViewHolder> {
public interface Callbacks {
public void onButtonClicked(String titleKey);
}
private Callbacks mCallbacks;
public Adapter() {
}
#Override
public MyRecycleViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_details, null);
return new MyRecycleViewHolder(v);
}
#Override
public void onBindViewHolder(final MyRecycleViewHolder holder, final int i) {
holder.ExpandButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCallbacks != null) {
mCallbacks.onButtonClicked(holder.ProbTitle.getText().toString());
}
}
});
}
#Override
public int getItemCount() {
return;
}
public void setCallbacks(Callbacks callbacks) {
this.mCallbacks = callbacks;
}
}
you may try do this on your onItemClick()
Intent i = new Intent(view.getContext(), DetailsActivity.class);
i.putExtra("title", yourTitle);
i.putExtra("description", yourDescription);
view.getContext().startActivity(i);
and when oncreate in your DetailActivity,do this
String title = getIntent().getStringExtra("title");
String description = getIntent().getStringExtra("description");
so you can pass title and description to DetailActivity
IMO, you implement setOnClickListener inside Adapter of RecyclerView. You can refer to my following sample code, then apply its logic to your code. Hope it helps!
public class MyRVAdapter extends RecyclerView.Adapter<MyRVAdapter.ViewHolder> {
Context mContext;
List<String> mStringList;
public MyRVAdapter(Context mContext, List<String> mStringList) {
this.mContext = mContext;
this.mStringList = mStringList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView textView1 = (TextView) v.findViewById(R.id.textView1);
TextView textView2 = (TextView) v.findViewById(R.id.textView2);
Bundle bundle = new Bundle();
bundle.putString("key1", textView1.getText().toString());
bundle.putString("key2", textView2.getText().toString());
passToAnotherActivity(bundle);
}
});
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// do something...
}
#Override
public int getItemCount() {
if (mStringList != null) {
return mStringList.size();
}
return 0;
}
private void passToAnotherActivity(Bundle bundle) {
if (mContext == null)
return;
if (mContext instanceof MainActivity) {
MainActivity activity = (MainActivity) mContext;
activity.passToAnotherActivity(bundle); // this method must be implemented inside `MainActivity`
}
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ViewHolder(View itemView) {
super(itemView);
// do something...
}
#Override
public void onClick(View v) {
}
}
}
First of all make your "itemsdata" object to implement Parcelable. You can check it here . In your onItemClick method you pass the object to your Details activity using intent.putExtra("key",listOfDataItems.get(position));
In your DetailsActivity you can get your custom object with getParcelable("key")
All above methods worked, but kinda long, so this one worked for me :
Cardview cardview;
cardView = (CardView)itemView.findViewById(R.id.cv);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent (view.getContext(), DetailsActivity.class);
i.putExtra("TitleKey",ProbTitle.getText().toString());
i.putExtra("DescrKey",ProbDescr.getText().toString());
view.getContext().startActivity(i);
}
});
And in Details.java :
TextView title;
TextView Descr;
title = (TextView)findViewById(R.id.details_title);
Descr = (TextView)findViewById(R.id.details_descr);
String titleresult = result.getExtras().getString("TitleKey");
String Descrresult = result.getExtras().getString("DescrKey");
title.setText(titleresult);
Descr.setText(Descrresult);