Go to the item selected on the RecyclerView - java

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);
}
}

Related

Android Activity cold start animation issue

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;
}
});
}
}
}

How to initialize right TextView in RecyclerView Adapter class?

I want to set the text of a custom build popup.
As soon as I want to set the text, the classic NullPointerException comes. How can I access the text field in my custom popup? How can I change the text of the TextView order_overview_number.setText(...).
How do I have to properly initialize this? TextView order_overview_number = epicDialog.findViewById(R.id.order_overview_number);
this is Unfortunately wrong...
public class UserBestellAdapter extends RecyclerView.Adapter<UserBestellAdapter.ViewHolder> {
ArrayList<Bestellung> bestellung;
Context mContext;
Dialog epicDialog;
public UserBestellAdapter(Context context, ArrayList<Bestellung> list) {
mContext = context;
bestellung = list;
epicDialog = new Dialog(mContext);
}
#NonNull
#Override
public UserBestellAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.adapter_bestell, parent, false);
UserBestellAdapter.ViewHolder viewHolder = new UserBestellAdapter.ViewHolder(view);
return viewHolder;
}
#NonNull
#Override
public void onBindViewHolder(#NonNull UserBestellAdapter.ViewHolder holder, final int position) {
//Gesamtpreis: holder.item_betrag.setText(String.valueOf(bestellung.get(position).getBetrag()));
// Datum: holder.item_datum.setText(bestellung.get(position).getDatum());
holder.item_items.setText(bestellung.get(position).getProdukte());
//holder.item_code.setText(bestellung.get(position).getBestellnummer());
String bestellid =bestellung.get(position).getBestellnummer() + "";
holder.item_code.setText(bestellid);
holder.item_betrag.setText(Double.toString(bestellung.get(position).getSumme()));
holder.item_datum.setText(bestellung.get(position).getDatum());
holder.layout_user_bestellung.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView order_overview_number = epicDialog.findViewById(R.id.order_overview_number);
//order_overview_number.setText();
epicDialog.setContentView(R.layout.user_popup_order_overview);
epicDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Button btn_order_overview_finish = (Button) epicDialog.findViewById(R.id.btn_order_overview_finish);
System.out.println(bestellung.get(position).getBestellnummer());
// HERE IS THE ERROR :(
//order_overview_number.setText(String.valueOf(bestellung.get(position).getDatum()));
btn_order_overview_finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
epicDialog.dismiss();
}
});
epicDialog.show();
}
});
}
#Override
public int getItemCount() {
return bestellung.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView item_items, item_betrag, item_datum, item_code;
private ConstraintLayout layout_user_bestellung;
public ViewHolder(#NonNull View itemView) {
super(itemView);
item_items = itemView.findViewById(R.id.items);
item_betrag = itemView.findViewById(R.id.betrag);
item_datum = itemView.findViewById(R.id.datum);
item_code = itemView.findViewById(R.id.code);
layout_user_bestellung = itemView.findViewById(R.id.layout_user_bestellung);
}
}
}
EDIT (didn't work)
I tried to set the text via itemView like the epicDialog.
#Override
public int getItemCount() {
return bestellung.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView item_items, item_betrag, item_datum, item_code;
private ConstraintLayout layout_user_bestellung;
private TextView tw;
public ViewHolder(#NonNull View itemView) {
super(itemView);
item_items = itemView.findViewById(R.id.items);
item_betrag = itemView.findViewById(R.id.betrag);
item_datum = itemView.findViewById(R.id.datum);
item_code = itemView.findViewById(R.id.code);
layout_user_bestellung = itemView.findViewById(R.id.layout_user_bestellung);
tw = itemView.findViewById(R.id.order_overview_number);
}
}
#Override
public void onBindViewHolder(#NonNull UserBestellAdapter.ViewHolder holder, final int position) {
//Gesamtpreis: holder.item_betrag.setText(String.valueOf(bestellung.get(position).getBetrag()));
// Datum: holder.item_datum.setText(bestellung.get(position).getDatum());
holder.item_items.setText(bestellung.get(position).getProdukte());
//holder.item_code.setText(bestellung.get(position).getBestellnummer());
String bestellid =bestellung.get(position).getBestellnummer() + "";
holder.item_code.setText(bestellid);
holder.item_betrag.setText(Double.toString(bestellung.get(position).getSumme()));
holder.item_datum.setText(bestellung.get(position).getDatum());
holder.layout_user_bestellung.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//TextView order_overview_number = epicDialog.findViewById(R.id.order_overview_number);
//order_overview_number.setText();
epicDialog.setContentView(R.layout.user_popup_order_overview);
epicDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Button btn_order_overview_finish = (Button) epicDialog.findViewById(R.id.btn_order_overview_finish);
System.out.println(bestellung.get(position).getBestellnummer());
holder.tw.setText("hallo");
btn_order_overview_finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
epicDialog.dismiss();
}
});
epicDialog.show();
}
});
}
Try
holder.layout_user_bestellung.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View v = View.inflate(mContext, R.layout.user_popup_order_overview, null);
EditText order_overview_number = (EditText) v.findViewById(R.id.order_overview_number);
order_overview_number.setText(String.valueOf(bestellung.get(position).getDatum()));
Button btn_order_overview_finish = (Button) v.findViewById(R.id.btn_order_overview_finish);
System.out.println(bestellung.get(position).getBestellnummer());
btn_order_overview_finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
epicDialog.dismiss();
}
});
epicDialog.setContentView(v);
epicDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
epicDialog.show();
}
});

android: how to increase number of quantity of an item in the cart

when user adds same item in the cart for multiple times it should be add that item only for one time and increase number of quantity of that item but in my case whole item is added for each time.
below is cart activity:
public class CartActivity extends AppCompatActivity implements CartAdapter.OnCartDataChangeListener {
DatabaseHandler helper;
public static List<ProductModel> dbList;
RecyclerView mRecyclerView;
Toolbar toolbar;
Button btnCheckout, btnContinueShopping;
public TextView tvTotalNoOfItems, tvTotalPrice;
String productVaiantId;
String selectedProductId;
private RecyclerView.Adapter mAdapter;
private LinearLayoutManager mLayoutManager;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
productVaiantId = getIntent().getStringExtra("variant_id");
selectedProductId = getIntent().getStringExtra("product_id");
Bundle extras = getIntent().getExtras();
if (extras != null) {
productVaiantId = extras.getString("variant_id");
selectedProductId = extras.getString("product_id");
}
toolbar = (Toolbar) findViewById(R.id.customToolBar);
setSupportActionBar(toolbar);
setTitle("Check-out");
toolbar.setTitleTextColor(Color.BLACK);
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
helper = new DatabaseHandler(this);
dbList = new ArrayList<ProductModel>();
dbList = helper.getDataFromDB();
mRecyclerView = (RecyclerView) findViewById(R.id.rv_cart_item_list);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mLayoutManager = new LinearLayoutManager(this) {
#Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
LinearSmoothScroller smoothScroller = new LinearSmoothScroller(CartActivity.this) {
private static final float SPEED = 300f;// Change this value (default=25f)
#Override
protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
return SPEED / displayMetrics.densityDpi;
}
};
smoothScroller.setTargetPosition(position);
startSmoothScroll(smoothScroller);
}
};
mAdapter = new CartAdapter(this, dbList, this);
tvTotalNoOfItems = (TextView) findViewById(R.id.tvTotalCartItems);
tvTotalPrice = (TextView) findViewById(R.id.tvTotalCartItemsPrice);
tvTotalNoOfItems.setText(dbList.size() + "");
double totalPrice = 0.0;
for (int i = 0; i < dbList.size(); i++) {
totalPrice += Double.parseDouble(dbList.get(i).getPrice());
}
tvTotalPrice.setText("" + totalPrice);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setItemAnimator(new SlideInUpAnimator());
btnContinueShopping = (Button) findViewById(R.id.btnBackToProductActivity);
btnContinueShopping.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent launchCollectionActivity = new Intent(CartActivity.this, CollectionActivity.class);
startActivity(launchCollectionActivity);
finish();
}
});
btnCheckout = (Button) findViewById(R.id.btn_checkout);
btnCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mAdapter.getItemCount() == 0){
Toast.makeText(CartActivity.this,"Your cart is empty",Toast.LENGTH_SHORT).show();
}
else {
Intent launchCheckoutActivity = new Intent(CartActivity.this, CheckoutActivity.class);
startActivity(launchCheckoutActivity);
} }
});
}
#Override
public void dataChanged() {
tvTotalNoOfItems.setText(dbList.size() + "");
double totalPrice = 0.0;
for (int i = 0; i < dbList.size(); i++) {
totalPrice += Double.parseDouble(dbList.get(i).getPrice());
}
tvTotalPrice.setText("" + totalPrice);
}
}
below is cart adapter:
public class CartAdapter extends RecyclerView.Adapter<CartAdapter.ViewHolder> {
public interface OnCartDataChangeListener{
public void dataChanged();
}
private OnCartDataChangeListener listener;
private List<ProductView.Data> productData = Collections.emptyList();
static List<ProductModel> productModelList;
static Context context;
DatabaseHandler mDatabaseHandler;
public CartAdapter(Context context, List<ProductModel> dbList, OnCartDataChangeListener listener ){
this.productModelList = new ArrayList<ProductModel>();
this.context = context;
this.productModelList = dbList;
mDatabaseHandler = new DatabaseHandler( context );
this.listener = listener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View cartListView = inflater.inflate(R.layout.list_item_cart, parent, false);
// Return a new holder instance
ViewHolder viewHolder = new ViewHolder(context,cartListView);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.tvProductName.setText(productModelList.get(position).getTitle());
holder.tvProductPrice.setText(productModelList.get(position).getPrice());
Glide
.with(context)
.load(productModelList.get(position).getImageUrl())
.placeholder(R.drawable.placeholder_loading)
.into(holder.imgProduct);
holder.tvSize.setText(productModelList.get(position).getSize());
holder.tvProductQuantity.setText(Integer.toString(productModelList.get(position).getQuantity()));
holder.tvColor.setText(productModelList.get(position).getColor());
holder.imgDelete.setClickable(true);
holder.imgDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String idForDelete = String.valueOf(productModelList.get(position).getVariantId());
mDatabaseHandler.deleteARow(idForDelete);
productModelList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position,productModelList.size());
CartActivity.dbList = productModelList;
listener.dataChanged();
}
});
}
#Override
public int getItemCount() {
return productModelList.size();
}
public void Refresh(ArrayList<ProductModel> datas) {
this.productModelList.clear();
this.productModelList.addAll(datas);
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvProductName, tvProductPrice, tvProductQuantity, tvColor,
tvSize;
ImageView imgProduct;
ImageButton imgDelete;
Context context;
public ViewHolder(Context mContext, View itemView) {
super(itemView);
this.tvProductName = (TextView) itemView.findViewById(R.id.tv_cart_product_name);
this.tvProductPrice = (TextView) itemView.findViewById(R.id.tv_cart_product_price);
this.tvProductQuantity = (TextView) itemView.findViewById(R.id.tv_cart_product_Quantity);
this.imgProduct = (ImageView) itemView.findViewById(R.id.img_cart_item_product);
this.tvColor = (TextView) itemView.findViewById(R.id.tv_color);
this.tvSize = (TextView) itemView.findViewById(R.id.tv_size);
this.imgDelete = (ImageButton) itemView.findViewById(R.id.img_cart_delete);
// store the context ///
this.context = mContext;
}
}
and this snippet is from previous activity from i get product when addToCart button is pressed:
btn_addToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String title = tv_productName.getText().toString();
String price = tv_productPrice.getText().toString();
String status = tv_productStatus.getText().toString();
String imageUrl = productImageList.get(0);
String productColor = String.valueOf(sp_productColor.getSelectedItem());
String productSize = String.valueOf(sp_productSize.getSelectedItem());
String productQuantity = String.valueOf(tv_productQuantity.getText());
final String productId = response.data().node().asProduct().id();
final String variantId = response.data().node().asProduct().variants().edges().get(0).node().id();
// save into database
helper = new DatabaseHandler(ProductDetailActivity.this);
helper.insertIntoDB(variantId, title, price, imageUrl, status, productSize, productQuantity, productColor);
// display snackbar to navigate to cart activity
Snackbar.make(view, R.string.snackbar_text, Snackbar.LENGTH_LONG)
.setAction(R.string.snackbar_action, new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent launchCartActivity = new Intent(ProductDetailActivity.this, CartActivity.class);
// adding the first product and its first variant to the cart
launchCartActivity.putExtra("product_id", productId);
launchCartActivity.putExtra("variant_id", variantId);
startActivity(launchCartActivity);
finish();
}
}).show();
}
});
You should apply check . If the item already exists in the cart then only increase the quantity
Try it like this.
private boolean isAlreadyInCart(int targetItemId) {
boolean isAlreadyInCart = false;
for (int i = 0; i < itemIds.length; i++) {
if (targetItemId == itemIds[i]) {
isAlreadyInCart = true;
break;
}
}
return isAlreadyInCart;
}
Now call use this method like this.
if (!isAlreadyInCart(itemId)) {
// TODO: add item to cart
} else {
// TODO: increase quantity
}

Android Recyclerview Update (Example = Gmail Read Change font )

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/

Passing RecyclerView CardView Clicked Item Data To Activity

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);

Categories

Resources