我有两个活动首先是产品,其中有按钮来递增和递减每个产品,第二个是显示在第一个活动中从sharedPrefrence
列表填充的产品的购物车,计数器工作正常,但我不知道如何将每个产品的数量添加到sharedPreference
列表中,这两个活动都是recycleViews
这是我的第一个活动适配器类
public class productsAdapter extends RecyclerView.Adapter<productsAdapter.MyViewHolder> {
private Context mContext;
public List<products> productList;
SharedPreference sharedPreference;
int quantity;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, count, quantity;
public ImageView thumbnail, cart, inc, dec;
private Context context;
public MyViewHolder(View view) {
super(view);
context = itemView.getContext();
title = (TextView) view.findViewById(R.id.title);
count = (TextView) view.findViewById(R.id.count);
thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
cart = (ImageView) view.findViewById(R.id.cart);
inc = (ImageView) view.findViewById(R.id.add);
dec = (ImageView) view.findViewById(R.id.remove);
quantity = (TextView) view.findViewById(R.id.quantity);
}
}
public productsAdapter(Context mContext, List<products> productList) {
this.mContext = mContext;
this.productList = productList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.products_card, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final products p = productList.get(position);
holder.title.setText(p.getName());
holder.count.setText(p.getPrice() + "L.E");
Glide.with(mContext).load(p.getThumbnail()).into(holder.thumbnail);
holder.quantity.setText(String.valueOf(p.getQuantity()));
holder.thumbnail.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), product_details.class);
Bundle bundle = new Bundle();
bundle.putString("img", p.getThumbnail());
bundle.putString("name", p.getName());
bundle.putInt("price", p.getPrice());
intent.putExtras(bundle);
v.getContext().startActivity(intent);
}
});
holder.cart.setImageResource(R.drawable.ic_cart_black_24dp);
holder.cart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sharedPreference = new SharedPreference();
sharedPreference.addFavorite(mContext, productList.get(position));
holder.cart.setImageResource(R.drawable.ic_add_cart);
Toast.makeText(mContext, "تم الاضافة للسلة", Toast.LENGTH_SHORT).show();
holder.cart.setClickable(false);
}
});
quantity =0;
holder.inc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
quantity = p.getQuantity()+1 ;
p.setQuantity(quantity);
notifyDataSetChanged();
Log.v("current quantity", String.valueOf(quantity));
}
});
holder.dec.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
quantity = p.getQuantity()-1;
p.setQuantity(quantity);
notifyDataSetChanged();
}
});
}
public int getItemCount() {
return productList.size();
}
public void setfilter(ArrayList<products> newlist) {
productList = new ArrayList<>();
productList.addAll(newlist);
notifyDataSetChanged();
;
}
}
第一项活动的主要内容
public class ell2lban extends AppCompatActivity {
RecyclerView recyclerView;
productsAdapter adapter;
List<products> List;
public static final String ARG_ITEM_ID = "product_list";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ell2lban);
List = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(ell2lban.this, 2);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.addItemDecoration(new ell2lban.GridSpacingItemDecoration(2, dpToPx(10), true));
recyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new productsAdapter(ell2lban.this, List);
recyclerView.setAdapter(adapter);
recyclerView.setItemViewCacheSize(300);
new BooksAsyns().execute();
}
private class BooksAsyns extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(ell2lban.this);
HttpURLConnection conn;
URL url = null;
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
@Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
@Override
protected String doInBackground(String... urls) {
String JsonResponse = null;
BufferedReader reader = null;
try {
// Enter URL address where your json file resides
// Even you can make call to php file which returns json data
url = new URL("http://192.168.1.13//grad/category1.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// conn.setRequestProperty("User-Agent","Mozilla/5.0(compatible)");
// conn.setRequestProperty("Accept","*/*");
// setDoOutput to true as we recieve data from json file
// conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
StringBuilder result = new StringBuilder();
InputStream input = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(input, Charset.forName("UTF-8"));
reader = new BufferedReader(inputStreamReader);
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
// Pass data to onPostExecute method
}
JsonResponse = result.toString().trim();
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
if (conn != null) {
conn.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
}
}
}
try {
return JsonResponse;
} catch (Exception e) {
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pdLoading.dismiss();
try {
JSONArray itmes = new JSONArray(s);
for (int i = 0; i < itmes.length(); i++) {
JSONObject subObject = itmes.getJSONObject(i);
String NAME = subObject.getString("NAME");
int price = subObject.getInt("PRICE");
String img = subObject.getString("PICTURE");
List.add(new products(NAME,img,price));
adapter.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
private int spanCount;
private int spacing;
private boolean includeEdge;
public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
this.spanCount = spanCount;
this.spacing = spacing;
this.includeEdge = includeEdge;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view); // item position
int column = position % spanCount; // item column
if (includeEdge) {
outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)
if (position < spanCount) { // top edge
outRect.top = spacing;
}
outRect.bottom = spacing; // item bottom
} else {
outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f / spanCount) * spacing)
if (position >= spanCount) {
outRect.top = spacing; // item top
}
}
}
}
private int dpToPx(int dp) {
Resources r = getResources();
return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}
}
第二个活动适配器
public class CartAdapter extends RecyclerView.Adapter<CartAdapter.CartViewHolder> {
List<products> adapterlist = new ArrayList<>();
CartActivity cartactivity;
Context cnx;
SharedPreference sharedPreference;
public CartAdapter(List<products> adapterlist, Context cnx) {
this.adapterlist = adapterlist;
this.cnx = cnx;
cartactivity = (CartActivity) cnx;
}
@Override
public CartViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_cards, parent, false);
CartViewHolder cartviewholder = new CartViewHolder(v, cartactivity);
return cartviewholder;
}
@Override
public void onBindViewHolder(final CartViewHolder holder, final int position) {
final products p = adapterlist.get(position);
holder.name.setText(p.getName());
holder.price.setText(p.getPrice() + "L.E");
holder.quantity.setText(String.valueOf(p.getQuantity()));
Glide.with(cnx).load(p.getThumbnail()).into(holder.image);
holder.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SharedPreference sharedPreference = new SharedPreference();
adapterlist.remove(holder.getAdapterPosition());
sharedPreference.saveFavorites(cnx, adapterlist);
notifyDataSetChanged();
}
});
Log.v("Quantity",String.valueOf(p));
}
@Override
public int getItemCount() {
return adapterlist.size();
}
public static class CartViewHolder extends RecyclerView.ViewHolder {
ImageView image;
TextView price, name,quantity;
Button button;
CartActivity cartactivity;
CardView cardv;
public CartViewHolder(View itemView, CartActivity cartactivity) {
super(itemView);
this.cartactivity = cartactivity;
image = (ImageView) itemView.findViewById(R.id.cartimage);
name = (TextView) itemView.findViewById(R.id.pn);
price = (TextView) itemView.findViewById(p);
button = (Button) itemView.findViewById(R.id.remove);
cardv = (CardView) itemView.findViewById(R.id.cardd);
quantity=(TextView)itemView.findViewById(R.id.quantity) ;
}
}
}
第二个活动主要
public class CartActivity extends AppCompatActivity {
Button l;
ImageView imv;
Toolbar t;
RecyclerView rv;
RecyclerView.LayoutManager layoutmanager;
RecyclerView.Adapter adapter;
List<products> cartitems;
ArrayList<products> selected_items_list = new ArrayList<>();
SharedPreference sharedPreference;
public static final String MyPREFERENCES = "MyPrefs";
int countt = 0;
boolean edit_mode = false;
TextView counterr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
sharedPreference = new SharedPreference();
cartitems = sharedPreference.getFavorites(CartActivity.this);
if (cartitems == null) {
Intent intent = new Intent(this, test.class);
startActivity(intent);
} else {
if (cartitems.size() == 0) {
Intent intent = new Intent(this, test.class);
startActivity(intent);
}
}
if (cartitems != null) {
rv = (RecyclerView) findViewById(R.id.mycartrecycler);
layoutmanager = new LinearLayoutManager(this);
rv.setLayoutManager(layoutmanager);
adapter = new CartAdapter(cartitems, CartActivity.this);
rv.setAdapter(adapter);
}
} }