i'm trying to pass a bundle from a product detail activity to a cart with a recycle view but when i click on add to cart the cart is opened but remains empty i don't know what's wrong with the code
here is the first activity
public class product_details extends AppCompatActivity {
ImageView product_img, share;
TextView name, price;
public int img;
public int price1;
public String name1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_details);
product_img = (ImageView) findViewById(R.id.Product_Img);
name = (TextView) findViewById(R.id.product_name);
price = (TextView) findViewById(R.id.product_price);
share = (ImageView) findViewById(R.id.share);
img = getIntent().getIntExtra("img", 00);
Glide.with(this).load(img).into(product_img);
name1 = getIntent().getStringExtra("name");
name.setText(name1);
price1 = getIntent().getIntExtra("price", 0);
price.setText(String.valueOf(price1));
ImageView cart = (ImageView) findViewById(R.id.add_cart);
cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), CartActivity.class);
Bundle extras = new Bundle();
extras.putString("price1", String.valueOf((price1)));
extras.putString("name1", name1);
extras.putString("img1",String.valueOf(img));
intent.putExtras(extras);
startActivity(intent);
}
my second activity class
public class CartRecycler {
int images_id;
String productname,productprice,productquantity;
public String getProductquantity() {
return productquantity;
}
public CartRecycler(int images_id , String productname , String productprice , String productquantity){
this.setImages_id(images_id);
this.setProductname(productname);
this.setProductprice(productprice);
this.setProductquantity(productquantity);
}
public CartRecycler(String productname, int images_id, String productprice) {
this.productname = productname;
this.images_id = images_id;
this.productprice = productprice;
}
public int getImages_id() {
return images_id;
}
public void setImages_id(int images_id) {
this.images_id = images_id;
}
public String getProductname() {
return productname;
}
public void setProductname(String productname) {
this.productname = productname;
}
public String getProductprice() {
return productprice;
}
public void setProductprice(String productprice) {
this.productprice = productprice;
}
public void setProductquantity(String productquantity) {
this.productquantity = productquantity;
}
}
cart adapter
public class CartAdapter extends RecyclerView.Adapter<CartAdapter.CartViewHolder> {
ArrayList<CartRecycler> adapterlist = new ArrayList<>();
CartActivity cartactivity;
Context cnx;
public CartAdapter(ArrayList<CartRecycler> 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(CartViewHolder holder, int position) {
holder.image.setImageResource(adapterlist.get(position).getImages_id());
holder.name.setText(adapterlist.get(position).getProductname());
holder.price.setText(adapterlist.get(position).getProductprice());
holder.quantity.setText(adapterlist.get(position).getProductquantity());
if(!cartactivity.edit_mode){
holder.checkornot.setVisibility(View.GONE);
}
else {
holder.checkornot.setVisibility(View.VISIBLE);
holder.checkornot.setChecked(false);
}
}
#Override
public int getItemCount() {
return adapterlist.size();
}
public static class CartViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView image;
TextView price,quantity,name;
CheckBox checkornot;
CartActivity cartactivity;
CardView cardv;
public CartViewHolder(View itemView, CartActivity cartactivity) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.cartimage);
name = (TextView) itemView.findViewById(R.id.pn);
price = (TextView) itemView.findViewById(R.id.p);
quantity = (TextView) itemView.findViewById(R.id.q);
checkornot = (CheckBox) itemView.findViewById(R.id.ckbox);
this.cartactivity= cartactivity;
cardv = (CardView) itemView.findViewById(R.id.cardd);
cardv.setOnLongClickListener((View.OnLongClickListener) cartactivity);
checkornot.setOnClickListener(this);
}
#Override
public void onClick(View view) {
cartactivity.prepareselection(view,getAdapterPosition());
}
}
public void updateadapter(ArrayList<CartRecycler> list){
for(CartRecycler cartRecycler:list){
adapterlist.remove(cartRecycler);
}
notifyDataSetChanged();
}
}
second activity
public class CartActivity extends AppCompatActivity implements View.OnLongClickListener{
Button l;
ImageView imv;
Toolbar t;
RecyclerView rv;
RecyclerView.LayoutManager layoutmanager;
RecyclerView.Adapter adapter;
ArrayList<CartRecycler> cartitems = new ArrayList<>();
ArrayList<CartRecycler> selected_items_list = new ArrayList<>();
int countt =0;
boolean edit_mode =false;
TextView counterr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
t = (Toolbar) findViewById(R.id.toolb);
setSupportActionBar(t);
getSupportActionBar().setDisplayShowTitleEnabled(false);
l = (Button) findViewById(R.id.checkoutsummary);
l.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent n = new Intent(CartActivity.this,SummaryActivity.class);
startActivity(n);
}
});
rv = (RecyclerView) findViewById(R.id.mycartrecycler);
layoutmanager = new LinearLayoutManager(this);
rv.setLayoutManager(layoutmanager);
rv.setHasFixedSize(true);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String price = extras.getString("price1");
String img1 = extras.getString("img1");
int imag1 = Integer.parseInt(img1);
String name = extras.getString("name1");
for (int i = 0; i < cartitems.size(); i++) {
CartRecycler cart = new CartRecycler(name, imag1, price);
cartitems.add(cart);
adapter.notifyDataSetChanged();
i++;
}
} else {
Intent intent = new Intent(this, test.class);
startActivity(intent);
}
adapter = new CartAdapter(cartitems,CartActivity.this);
rv.setAdapter(adapter);
counterr = (TextView) findViewById(R.id.selecteditemcounter);
counterr.setVisibility(View.GONE);
}
#Override
public boolean onLongClick(View view) {
t.getMenu().clear();
t.inflateMenu(R.menu.cart_edit_mode);
counterr.setVisibility(View.VISIBLE);
edit_mode = true;
adapter.notifyDataSetChanged();
return true;
}
public void prepareselection(View view,int position){
if(((CheckBox)view).isChecked()){
selected_items_list.add(cartitems.get(position));
countt = countt+1;
updatecounter(countt);
}
else {
selected_items_list.remove(cartitems.get(position));
countt = countt -1;
updatecounter(countt);
}
}
public void updatecounter(int counter){
if(counter==0){
counterr.setText("0 items selected");
}
else {
counterr.setText(counter+" item selected");
}
}
public boolean onOptionsItemSelected(MenuItem item){
if(item.getItemId()==R.id.item_delete){
CartAdapter cartAdapter = (CartAdapter) adapter;
cartAdapter.updateadapter(selected_items_list);
}
else if(item.getItemId()== android.R.id.home)
{
adapter.notifyDataSetChanged();
}
return true;
}
}
for (int i = 0; i < cartitems.size(); i++) This loop will not run until and unless size of cartitems is greater than 0 and hence all the code under it's scope will never get executed
Related
TestListModel.class
public class TestListModel {
private String testlist_id;
private String test_price;
private String test_name;
private boolean isSelected;
public TestListModel(String testlist_id, String test_price, String test_name,boolean isSelected) {
this.testlist_id = testlist_id;
this.test_price = test_price;
this.test_name = test_name;
this.isSelected = isSelected;
}
public String getTestlist_id() {
return testlist_id;
}
public void setTestlist_id(String testlist_id) {
this.testlist_id = testlist_id;
}
public String getTest_price() {
return test_price;
}
public void setTest_price(String test_price) {
this.test_price = test_price;
}
public String getTest_name() {
return test_name;
}
public void setTest_name(String test_name) {
this.test_name = test_name;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
}
JsonResponse.java
public class JSONResponse {
private TestListModel[] result;
public TestListModel[] getResult() {
return result;
}
public void setResult(TestListModel[] result) {
this.result = result;
}
}
HealthActivity.java
public class HealthServicesActivity extends AppCompatActivity implements View.OnClickListener {
/*
*Api call
* */
private RecyclerView recyclerView;
private ArrayList<TestListModel> data;
private RecyclerAdapter madapter;
private Button submitButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_health_services);
ButterKnife.bind(this);
sharePreferenceManager = new SharePreferenceManager<>(getApplicationContext());
submitButton=(Button) findViewById(R.id.submit_button);
showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));
initViews();
submitButton.setOnClickListener(this);
/*
* On Click Listner
* */
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.submit_button:
int totalAmount = 0;
int totalPrice = 0;
String testName = "";
String testPrice="";
int count = 0;
List<TestListModel> stList = ((RecyclerAdapter) madapter)
.getTestList();
for (int i = 0; i < stList.size(); i++) {
TestListModel singleStudent = stList.get(i);
//AmountCartModel serialNumber = stList.get(i);
if (singleStudent.isSelected() == true) {
testName = testName + "\n" + singleStudent.getTest_name().toString();
testPrice = testPrice+"\n" + singleStudent.getTest_price().toString();
count++;
totalAmount = Integer.parseInt(stList.get(i).getTest_price());
totalPrice = totalPrice + totalAmount;
}
}
Toast.makeText(HealthServicesActivity.this,
"Selected Lists: \n" + testName+ "" + testPrice, Toast.LENGTH_LONG)
.show();
Intent in= new Intent(HealthServicesActivity.this, AmountCartActivity.class);
in.putExtra("test_name", testName);
in.putExtra("test_price", testPrice);
//in.putExtra("total_price",totalPrice);
in.putExtra("total_price", totalPrice);
in.putExtra("serialNumber", count);
startActivity(in);
finish();
break;
/** back Button Click
* */
case R.id.back_to_add_patient:
startActivity(new Intent(getApplicationContext(), PatientActivity.class));
finish();
break;
default:
break;
}
}
/** show center Id in action bar
* */
#Override
protected void onResume() {
super.onResume();
showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));
}
private void showcenterid(LoginModel userLoginData) {
centerId.setText(userLoginData.getResult().getGenCenterId());
centerId.setText(userLoginData.getResult().getGenCenterId().toUpperCase());
deviceModeName.setText(userLoginData.getResult().getDeviceModeName());
}
private void initViews() {
recyclerView = (RecyclerView)findViewById(R.id.test_list_recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
loadJSON();
}
private void loadJSON() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(" http://192.168.1.80/aoplnew/api/")
//
.baseUrl("https://earthquake.usgs.gov/fdsnws/event/1/query?")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface request = retrofit.create(ApiInterface.class);
Call<JSONResponse> call = request.getTestLists();
call.enqueue(new Callback<JSONResponse>() {
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
JSONResponse jsonResponse = response.body();
data = new ArrayList<>(Arrays.asList(jsonResponse.getResult()));
madapter = new RecyclerAdapter(data);
recyclerView.setAdapter(madapter);
}
#Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Log.d("Error",t.getMessage());
}
});
}
HealthRecyclerAdapter.java
public class RecyclerAdapter extends
RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private ArrayList<TestListModel> android;
public RecyclerAdapter(ArrayList<TestListModel> android) {
this.android = android;
}
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.test_list_row,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerAdapter.ViewHolder holder, final int position) {
holder.test_name.setText(android.get(position).getTest_name());
holder.test_price.setText(android.get(position).getTest_price());
holder.chkSelected.setChecked(android.get(position).isSelected());
holder.chkSelected.setTag(android.get(position));
holder.chkSelected.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
TestListModel contact = (TestListModel) cb.getTag();
contact.setSelected(cb.isChecked());
android.get(position).setSelected(cb.isChecked());
Toast.makeText(
v.getContext(),
"Clicked on Checkbox: " + cb.getText() + " is " + cb.isChecked(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return android.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView test_name;
private TextView test_price;
public CheckBox chkSelected;
public TestListModel testLists;
public ViewHolder(View itemView) {
super(itemView);
test_name = (TextView)itemView.findViewById(R.id.test_name);
test_price = (TextView)itemView.findViewById(R.id.price_name);
chkSelected = (CheckBox) itemView.findViewById(R.id.check_box);
}
}
// method to access in activity after updating selection
public List<TestListModel> getTestList() {
return android;
}
AmountCartModel.java
public class AmountCartModel {
private String testName;
private String testPrice;
private Integer serialNumber;
private Integer totalPrice;
public AmountCartModel() {
this.testName = testName;
this.testPrice = testPrice;
this.serialNumber = serialNumber;
this.totalPrice = totalPrice;
}
public String getTestName() {
return testName;
}
public void setTestName(String testName) {
this.testName = testName;
}
public String getTestPrice() {
return testPrice;
}
public void setTestPrice(String testPrice) {
this.testPrice = testPrice;
}
public Integer getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(Integer serialNumber) {
this.serialNumber = serialNumber;
}
public Integer getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(Integer totalPrice) {
this.totalPrice = totalPrice;
}
}
AmountCartActivity.java
public class AmountCartActivity extends AppCompatActivity implements View.OnClickListener {
#BindView(R.id.total_price)
TextView totalPriceDisplay;
SharePreferenceManager<LoginModel> sharePreferenceManager;
private RecyclerView recyclerView;
List<AmountCartModel> mydataList ;
private MyAdapter madapter;
Bundle extras ;
String testName="";
String testPrice="";
String totalPrice= "";
int counting = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_amount_cart);
ButterKnife.bind(this);
sharePreferenceManager = new SharePreferenceManager<>(getApplicationContext());
showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));
mydataList = new ArrayList<>();
/*
* Getting Values From BUNDLE
* */
extras = getIntent().getExtras();
if (extras != null) {
testName = extras.getString("test_name");
testPrice = extras.getString("test_price");
totalPrice = String.valueOf(extras.getInt("total_price"));
counting = extras.getInt("serialNumber");
//Just add your data in list
AmountCartModel mydata = new AmountCartModel(); // object of Model Class
mydata.setTestName(testName );
mydata.setTestPrice(testPrice);
mydata.setTotalPrice(Integer.valueOf(totalPrice));
mydata.setSerialNumber(counting);
mydataList.add(mydata);
//totalPriceDisplay.setText(totalPrice);
}
madapter=new MyAdapter(mydataList);
madapter.setMyDataList(mydataList);
recyclerView = (RecyclerView)findViewById(R.id.recyler_amount_cart);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(madapter);
RecyclerAdapter.java //RecyclerAdapter for AmountCart
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>
{
private List<AmountCartModel> context;
private List<AmountCartModel> myDataList;
public MyAdapter(List<AmountCartModel> context) {
this.context = context;
myDataList = new ArrayList<>();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
// Replace with your layout
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.amount_cart_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// Set Your Data here to yout Layout Components..
// to get Amount
/* myDataList.get(position).getTestName();
myDataList.get(position).getTestPrice();*/
holder.testName.setText(myDataList.get(position).getTestName());
holder.testPrice.setText(myDataList.get(position).getTestPrice());
holder.textView2.setText(myDataList.get(position).getSerialNumber());
}
#Override
public int getItemCount() {
/*if (myDataList.size() != 0) {
// return Size of List if not empty!
return myDataList.size();
}
return 0;*/
return myDataList.size();
}
public void setMyDataList(List<AmountCartModel> myDataList) {
// getting list from Fragment.
this.myDataList = myDataList;
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView testName,testPrice,textView2;
public ViewHolder(View itemView) {
super(itemView);
// itemView.findViewById
testName=itemView.findViewById(R.id.test_name_one);
testPrice=itemView.findViewById(R.id.test_price);
textView2=itemView.findViewById(R.id.textView2);
}
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new
Intent(AmountCartActivity.this,HealthServicesActivity.class));
finish();
}
}
This is my code.
Here I am taking HealthActivity and in this class by using recycler view I have displayed testList in recycler view. I am passing testList whichever I am selecting through checkbox to AmountCartActivity of recycler View, And, I am calculating total amount of the selected testList and I am getting the result and that result I am passing to the AmountCart Activity through bundle and I am getting correct result in bundle, but, when I am trying to display total amount in a textView its showing me nothing.
And, my second problem is,
I am trying to display serial number to to my AmountCartActivity of recycler view whichever I am selecting from previous HealthCartActivity using checkbox. And, I have implemented some code but I am not getting how to solve it. please help me.
For Issue#1
Data should be passed onto the Adapter through constructor. The issue could simply be adding another parameter to the constructor:
public MyAdapter(List<AmountCartModel> context, List<AmountCartModel> myDataList) {
this.context = context;
myDataList = this.myDataList;
}
Or,
To add selection support to a RecyclerView instance:
Determine which selection key type to use, then build a ItemKeyProvider.
Implement ItemDetailsLookup: it enables the selection library to access information about RecyclerView items given a MotionEvent.
Update item Views in RecyclerView to reflect that the user has selected or unselected it.
The selection library does not provide a default visual decoration for the selected items. You must provide this when you implement onBindViewHolder() like,
In onBindViewHolder(), call setActivated() (not setSelected()) on the View object with true or false (depending on if the item is selected).
Update the styling of the view to represent the activated status.
For Issue #2
Try using passing data through intents.
The easiest way to do this would be to pass the serial num to the activity in the Intent you're using to start the activity:
Intent intent = new Intent(getBaseContext(), HealthServicesActivity.class);
intent.putExtra("EXTRA_SERIAL_NUM", serialNum);
startActivity(intent);
Access that intent on next activity
String sessionId= getIntent().getStringExtra("EXTRA_SERIAL_NUM");
I have list of data in MenuItemsModel(model) class along with image url and two strings fetching from the API. How can I load the image url with Picasso and how to bind the loaded image to recyclerview?
Here is my code
Code for model class
public class MenuItemsModel {
public int image;
public String itemName;
public String itemCost;
public MenuItemsModel(int image, String itemName, String itemCost) {
this.image = image;
this.itemName = itemName;
this.itemCost = itemCost;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemCost() {
return itemCost;
}
public void setItemCost(String itemCost) {
this.itemCost = itemCost;
}
}
Here is my RecyclerAdapter class
public class MenusRecyclearView extends
RecyclerView.Adapter<MenusRecyclearView.RecyclerViewHolder> {
Context context;
List<MenuItemsModel> menuItemsModel;
public MenusRecyclearView(Context context, List<MenuItemsModel> menuItemsModel) {
this.context = context;
this.menuItemsModel = menuItemsModel;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.menu_items_list, parent, false);
return new RecyclerViewHolder(view, context, menuItemsModel);
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
holder.imageView.setImageResource(menuItemsModel.get(position).getImage());
holder.ItemName.setText(menuItemsModel.get(position).getItemName());
holder.ItemCost.setText(menuItemsModel.get(position).getItemCost());
//Picasso.with(context).load(menuItemsModel.get(position).getImage()).into(holder.imageView);
}
#Override
public int getItemCount() {
return menuItemsModel.size();
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
public ImageView imageView;
public TextView ItemName, ItemCost;
Context ctx;
List<MenuItemsModel> menuItemsModels;
public RecyclerViewHolder(View view, Context ctx, List<MenuItemsModel> menuItemsModels) {
super(view);
this.ctx = ctx;
this.menuItemsModels = menuItemsModels;
view.setOnClickListener(this);
imageView = view.findViewById(R.id.biriyani_menu_item);
ItemName = view.findViewById(R.id.item_name);
ItemCost = view.findViewById(R.id.item_cost);
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
MenuItemsModel model = this.menuItemsModels.get(position);
Intent i = new Intent(this.ctx, CategoryDescription.class);
i.putExtra("ImageId", model.getImage());
i.putExtra("ItemName", model.getItemName());
i.putExtra("ItemCost", model.getItemCost());
this.ctx.startActivity(i);
}
}
}
** Here is my MainActivity class **
public class BiryanisActivity extends AppCompatActivity implements
View.OnClickListener, NetworkOperationListener{
RecyclerView recyclerView;
MenusRecyclearView menusRecyclearView;
RecyclerView.LayoutManager layoutManager;
List<MenuItemsModel> menuItemsModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.biriyanis_activity);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
menuItemsModel = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclearview_menu);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setItemAnimator(new DefaultItemAnimator());
menusRecyclearView = new MenusRecyclearView(this, menuItemsModel);
recyclerView.setAdapter(menusRecyclearView);
HttpAdapter.getMenuItemsList(this,"MenuItemsList");
//prepareData();
}
/* public void prepareData() {
MenuItemsModel data = new MenuItemsModel(R.drawable.item5, "Chicken Dhum
Biriyani", "Rs.240");
menuItemsModel.add(data);
MenuItemsModel data1 = new MenuItemsModel(R.drawable.item2, "Chicken
Chilli Biriyani", "Rs.260");
menuItemsModel.add(data1);
MenuItemsModel data2 = new MenuItemsModel(R.drawable.item3, "Chicken
Tandhuri Biriyani", "Rs.280");
menuItemsModel.add(data2);
MenuItemsModel data3 = new MenuItemsModel(R.drawable.item4, "Chicken
Moghulai Biriyani", "Rs.230");
menuItemsModel.add(data3);
MenuItemsModel data4 = new MenuItemsModel(R.drawable.item1, "Chicken
Special Biriyani", "Rs.220");
menuItemsModel.add(data4);
MenuItemsModel data5 = new MenuItemsModel(R.drawable.item1, "Chicken
Mandi Biriyani", "Rs.210");
menuItemsModel.add(data5);
}*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return false;
}
#Override
public void onClick(View view) {
}
#Override
public void operationCompleted(NetworkResponse response) {
if (response.getStatusCode() == 200) {
if (response.getTag().equals("MenuItemsList")) {
try {
JSONObject jsonObjects = new JSONObject(response.getResponseString());
if (jsonObjects.getString("Data").equals("null")) {
Toast.makeText(this, "No Data Found", Toast.LENGTH_SHORT).show();
return;
}
JSONArray jsonArray = jsonObjects.getJSONArray("Data");
for (int j=0; j<jsonArray.length(); j++) {
JSONObject jsonObject = jsonArray.getJSONObject(j);
MenuItemsModel data = new Gson().fromJson(jsonObject.toString(),MenuItemsModel.class);
//Picasso.with(this).load(data.getImage()).into();
Picasso.with(this).load(data.getImage()).into(holder.imageView);
/* int image = data.getImage();
String name = data.getItemName();
String cost = data.getItemCost();
//picaso(image, imageView);*/
menuItemsModel.add(data);
}
MenusRecyclearView menusRecyclearView = new MenusRecyclearView(this,menuItemsModel);
recyclerView.setAdapter(menusRecyclearView);
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
Toast.makeText(this, "Failed to Connect Server, Please try again later", Toast.LENGTH_SHORT).show();
}
}
public void picaso(String path, ImageView imageView) {
if (!path.equals("")) {
Picasso.with(this).load(path).into(imageView);
}
}
}
Well, you are on the right track. You need to uncomment this line:
//Picasso.with(context).load(menuItemsModel.get(position).getImage()).into(holder.imageView);
And, the .getImage() needs to become your URL. That means, you should store the image url inside MenuItemsModel. Now your image is an int, and should be of a type of String so you can pass the URL to it.
Also see this answer here:
https://stackoverflow.com/a/41157030/5457878
Hi I am new android developer i have stuck in my project. Problem is i want to user select items by checked box and after they click on view items button then open a another activity in which shows all those selected items in recyclerview in that recyclerview item name, price, and quantity.
This is my code
OderItems Activity, OderitemAdapter and OrderItemModel.
OderItems Activity
`public class OrderItems extends AppCompatActivity` {
public static final String KEY_ADSID="adsId";
public RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView= (RecyclerView) findViewById(R.id.order_item_recyclerview);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(OrderItems.this,ViewOrder.class));
}
});
parseOrder();
}
public void parseOrder()
{
StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.url_ORDERLISTING,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
Log.d("Response",jsonObject.toString());
if (jsonObject.optString("status").equalsIgnoreCase("1"))
{
// String no_task= jsonObject.getString("error_msg");
Toast.makeText(OrderItems.this,"No Order List List !",Toast.LENGTH_LONG).show();
// txt_noTask.setText("No Task Is Available");
// progressDialog.dismiss();
}
if (jsonObject.optString("status").equalsIgnoreCase("0") || jsonObject.optString("message").equalsIgnoreCase("Success"))
{
// Toast.makeText(getActivity(),jsonObject.toString(),Toast.LENGTH_LONG).show();
JSONArray jsonArray= jsonObject.getJSONArray("ItemList");
ArrayList<OrderItemModel> list =new ArrayList<>();
for (int i=0;i<jsonArray.length();i++)
{
// TodayTaskModel todayTask = new TodayTaskModel();
OrderItemModel orderitemmodel = new OrderItemModel();
JSONObject jsonObj= jsonArray.getJSONObject(i);
String product_Name =jsonObj.getString("productName");
String product_Price =jsonObj.getString("productPrice");
String package_img =jsonObj.getString("productImg");
// For Set data
orderitemmodel.setProductName(product_Name);
orderitemmodel.setProductPrice(product_Price);
orderitemmodel.setProductImg(package_img);
list.add(orderitemmodel);
}
// Setup and Handover data to recyclerview
OrderItemAdapter adapter=new OrderItemAdapter(getApplicationContext(),list);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerView.setHasFixedSize(true);
}
} catch (JSONException e) {
e.printStackTrace();
}
//pDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(OrderItems.this,"Server is not Responding !!! ", Toast.LENGTH_LONG).show();
// Toast.makeText(SpamActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_ADSID,"101");
return params;
}
};
RequestQueue requestQueue =
Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
}
OderitemAdapter
public class OrderItemAdapter extends RecyclerView.Adapter<OrderItemAdapter.ViewHolder> {
ArrayList<OrderItemModel> orderItemList;
Context context;
SqlHandler sqlHandler;
static double summ;
public OrderItemAdapter(Context c, ArrayList<OrderItemModel> orderItemList)
{
this.context=c;
this.orderItemList=orderItemList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.order_item_layout, parent, false);
sqlHandler = new SqlHandler(context);
return new OrderItemAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int i) {
final OrderItemModel position=orderItemList.get(i);
holder.txt_ProductName.setText(position.getProductName());
holder.txt_ProductPrice.setText(position.getProductPrice());
holder.urlProductImg=position.getProductImg();
holder.strRate = position.getProductPrice();
holder.strQuantity=position.getProductQty();
if (holder.urlProductImg.isEmpty()) { //url.isEmpty()
Picasso.with(context)
.load(R.drawable.localbizlist)
.placeholder(R.drawable.localbizlist)
.error(R.drawable.localbizlist)
.into(holder.img_product);
}else{
Picasso.with(context)
.load(orderItemList.get(i).getProductImg())
.placeholder(R.drawable.localbizlist)
.error(R.drawable.localbizlist)
.into(holder.img_product); //this is your ImageView
}
}
#Override
public int getItemCount() {
return orderItemList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
CheckBox chkOrder;
ImageView img_product;
TextView txt_ProductName,txt_ProductPrice;
Spinner itemSpinner;
String urlProductImg,strRate,strQuantity,strProductName;
public ViewHolder(View itemView) {
super(itemView);
context = itemView.getContext();
img_product=(ImageView)itemView.findViewById(R.id.img_product);
txt_ProductName=(TextView)itemView.findViewById(R.id.productName);
txt_ProductPrice=(TextView)itemView.findViewById(R.id.productPrice);
chkOrder=(CheckBox)itemView.findViewById(R.id.chk_order_status);
itemSpinner = (Spinner)itemView.findViewById(R.id.item_spinner);
List<String> itemQuuantity=new ArrayList<String>();
itemQuuantity.add("1");
itemQuuantity.add("2");
itemQuuantity.add("3");
itemQuuantity.add("4");
itemQuuantity.add("5");
ArrayAdapter<String> itemAdapter=new ArrayAdapter<String>(context,android.R.layout.simple_spinner_dropdown_item,itemQuuantity);
itemAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
itemSpinner.setAdapter(itemAdapter);
chkOrder.setOnClickListener(this);
}
#Override
public void onClick(View view) {
context = view.getContext();
double TotalBill=0.00;
if (view.getId()==chkOrder.getId())
{
if (chkOrder.isChecked())
{
double spQuantity = Double.parseDouble(itemSpinner.getSelectedItem().toString());
double itemRate = Double.parseDouble(strRate);
double itemPrice = (spQuantity * itemRate);
TotalBill+=itemPrice;
String strQuatity=Double.toString(spQuantity);
String strTotalBill = Double.toString(TotalBill);
String strProductName= String.valueOf(txt_ProductName.getText());
String strProductPrice=String.valueOf(txt_ProductPrice.getText());
Toast.makeText(context,"Checked Item Bill"+TotalBill,Toast.LENGTH_LONG).show();
String query = "INSERT INTO ORDER_ITEMS(product_name,product_quantity,product_price) values ('"
+ strProductName + "','" + strProductPrice + "','"+strQuatity+"')";
sqlHandler.executeQuery(query);
SumOrderBill(TotalBill);
Toast.makeText(context,"Record Save",Toast.LENGTH_LONG).show();
// showlist();
// strIDCheckBoxStatus=String.valueOf(chkOrder.getId());
}else
{
//saveInSp("Checked",false);
double spQuantity = Double.parseDouble(itemSpinner.getSelectedItem().toString());
double itemRate = Double.parseDouble(strRate);
double itemPrice = (spQuantity * itemRate);
TotalBill+=itemPrice;
String strIdProductName= String.valueOf(txt_ProductName.getText());
Toast.makeText(context,"UNCHECKED Item Bill"+TotalBill,Toast.LENGTH_LONG).show();
MinOrderBill(TotalBill);
String delQuery = "DELETE FROM PHONE_CONTACTS WHERE slno='"+strIdProductName+"' ";
sqlHandler.executeQuery(delQuery);
// showlist();
}
}
}
public void SumOrderBill(double ftotal)
{
summ+=ftotal;
String total2 = String.valueOf(summ);
Toast.makeText(context, "Total Bill"+total2,Toast.LENGTH_LONG).show();
// SharedPreferences myPrefsLogin=context.getSharedPreferences("biling", Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = myPrefsLogin.edit();
// editor.putString("Total", total2);
// editor.commit();
}
public void MinOrderBill(double ftotal)
{
summ-=ftotal;
String total2 = String.valueOf(summ);
Toast.makeText(context, "Detection"+summ,Toast.LENGTH_LONG).show();
// SharedPreferences myPrefsLogin=context.getSharedPreferences("biling", Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = myPrefsLogin.edit();
// editor.putString("Total", total2);
// editor.commit();
}
}
}
public class OrderItemModel {
private String status;
private String message;
private String productId;
private String productName;
private String productType;
private String productQty;
private String productImg;
private String productPrice;
public OrderItemModel()
{
}
public String getProductPrice() {
return productPrice;
}
public void setProductPrice(String productPrice) {
this.productPrice = productPrice;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public String getProductQty() {
return productQty;
}
public void setProductQty(String productQty) {
this.productQty = productQty;
}
public String getProductImg() {
return productImg;
}
public void setProductImg(String productImg) {
this.productImg = productImg;
}
}
Please help me for ViewOrder Activity
Here I am posting my code. After selecting checkbox user click on save button and onClick of that, another activity is open with only selected items(As you want),
Here is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.rView);
context = this;
numberlist = new ArrayList<Number>();
for (int i = 0; i < 50; i++) {
Number number = new Number(String.valueOf(i), false);
number.setSelected(false);
numberlist.add(number);
}
customAdapter = new CustomAdapter(context, R.layout.list_item, numberlist);
recyclerView.setAdapter(customAdapter);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
numberlist= customAdapter.onItemSelected();
customAdapter.setList(numberlist);
}
});
Here is my adapter's code:
public class CustomAdapter extends BaseAdapter {
private ArrayList<Number> numList;
Context context;
int textViewResourceId;
public CustomAdapter(Context context, int textViewResourceId, ArrayList<Number> numberlist) {
this.numList = new ArrayList<Number>();
this.numList.addAll(numberlist);
this.context=context;
this.textViewResourceId=textViewResourceId;
}
#Override
public int getCount() {
return numList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public class ViewHolder {
TextView code;
CheckBox name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
convertView=LayoutInflater.from(context).inflate(textViewResourceId,null);
holder = new ViewHolder();
convertView.findViewById(R.id.code);
holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
holder.name.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Number number = (Number) cb.getTag();
number.setSelected(cb.isChecked());
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
Number number = numList.get(position);
holder.name.setText(number.getName());
holder.name.setChecked(number.isSelected());
holder.name.setTag(number);
if(number.isSelect()){
holder.name.setVisibility(View.GONE);
}
else {
holder.name.setVisibility(View.VISIBLE);
}
return convertView;
}
public ArrayList<Number> onItemSelected() {
StringBuffer text = new StringBuffer();
ArrayList<Number> numberArrayList=new ArrayList<Number>();
text.append("following are selected...\n");
for (int i = 0; i < numList.size(); i++) {
Number item = numList.get(i);
if (item.isSelected()) {
numList.get(i).setSelect(true);
numberArrayList.add(numList.get(i));
text.append("\n" + item.getName());
}
}
Log.e("Text ", text.toString());
return numberArrayList;
}
public void setList(ArrayList<Number> list){
numList.clear();
numList.addAll(list);
notifyDataSetChanged();
}
}
I have a local database that i want get res id from it(string saving) and show in application, also i have a recycler view and I want after click on items, display image.
public class AdapterApp extends RecyclerView.Adapter<AdapterApp.AdapterViewHolder>{
public static class AdapterViewHolder extends RecyclerView.ViewHolder{
public TextView txtDescription;
public ViewGroup layoutRoot;
public TextView txtTitle;
public ImageView imgDesc;
public AdapterViewHolder(View itemView) {
super(itemView);
txtTitle = (TextView) itemView.findViewById(R.id.txtTitle);
txtDescription = (TextView) itemView.findViewById(R.id.txtDesc);
layoutRoot = (ViewGroup) itemView.findViewById(R.id.layoutRoot);
imgDesc = (ImageView) itemView.findViewById(R.id.imgDesc);
}
}
private ArrayList<StructApp> names = new ArrayList<StructApp>();
public AdapterApp(ArrayList<StructApp> names){
this.names = names;
}
#Override
public AdapterViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = G.inflater.from(viewGroup.getContext()).inflate(R.layout.adapter_app,viewGroup,false);
return new AdapterViewHolder(view);
}
#Override
public void onBindViewHolder(final AdapterViewHolder adapterViewHolder, final int i) {
final StructApp name = names.get(i);
adapterViewHolder.txtTitle.setText(name.title);
adapterViewHolder.layoutRoot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(G.currentActivity,ActivityDesc.class);
intent.putExtra("description",name.description);
G.currentActivity.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return names.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
}
database activity:
public class ActivityTitleEngineer extends ActivityEnhanced {
private RecyclerView recyclerView;
private AdapterApp adapter;
private ArrayList<StructApp> applications = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reshte_math);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
LinearLayoutManager manager = new LinearLayoutManager(G.context);
manager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(manager);
adapter = new AdapterApp(G.reshte);
populateFromDatabase();
recyclerView.setAdapter(adapter);
}
public void populateFromDatabase() {
G.reshte.clear();
DataBaseConnection db = new DataBaseConnection(this, "database", 4);
final SQLiteDatabase database = db.getReadableDatabase();
Cursor cursor = database.rawQuery("SELECT * FROM Reshte ", null);
while (cursor.moveToNext()) {
StructApp application = new StructApp();
application.description = cursor.getString(cursor.getColumnIndex("description"));
application.title = cursor.getString(cursor.getColumnIndex("title"));
application.imgDesc = cursor.getString(cursor.getColumnIndex("img"));
G.reshte.add(application);
}
cursor.close();
}
}
activity of display image:
public class ActivityDesc extends AppCompatActivity {
private TextView txtDesc;
private ImageView imgDesc;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reshte_desc);
txtDesc = (TextView) findViewById(R.id.txtDesc);
imgDesc = (ImageView) findViewById(R.id.imgDesc);
Bundle extras = getIntent().getExtras();
if(extras!= null){
String desc = extras.getString("description");
txtDesc.setText(desc);
}
}
}
Try this method :)
StorageReference islandRef = MainGameFragment.storageReference.child("Capture.PNG");
final long ONE_MEGABYTE = 1024 * 1024;
islandRef.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
#Override
public void onSuccess(byte[] bytes) {
ByteArrayInputStream imageStream = new ByteArrayInputStream(bytes);
Bitmap bitmap = BitmapFactory.decodeStream(imageStream);
imageSettings.setImageBitmap(bitmap);
settingsText4.setText("Click to visit site for more information");
settingsText4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = "site";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
mProgress.setVisibility(View.GONE);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
});
I am able to send data on listview in nextpage.But problem is that items with quantity 0 is also passed.I want to show items whose quantity is incremented and not all items present in listview.Here is my code-
MainActivity.java
public class MainActivity extends Activity implements SearchView.OnQueryTextListener{
Button show;
ListView list_item;
ArrayList<Items> itemsArrayList;
SearchView searchview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list_item = (ListView) findViewById(R.id.listdetails);
searchview=(SearchView)findViewById(R.id.searchView);
show = (Button) findViewById(R.id.btnview);
itemsArrayList=new ArrayList<>();
itemsArrayList.add(new Items(1,"Book",20,0,0));
itemsArrayList.add(new Items(2,"Pen",25,0,0));
itemsArrayList.add(new Items(3,"Scale",10,0,0));
itemsArrayList.add(new Items(4,"Eraser",5,0,0));
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Trial.class);
intent.putExtra("data", itemsArrayList);
startActivity(intent);
}
});
Custom c = new Custom(this,itemsArrayList);
list_item.setAdapter(c);
list_item.setTextFilterEnabled(true);
setupSearchView();
}
public void setupSearchView()
{
searchview.setOnQueryTextListener(this);
searchview.setQueryHint("Search Here");
}
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if (TextUtils.isEmpty(s)) {
list_item.clearTextFilter();
} else {
list_item.setFilterText(s);
}
return true;
}
}
Custom.java
public class Custom extends BaseAdapter implements Filterable{
Activity a;
ArrayList<Items> itemsArrayList;
ArrayList<Items> filtered;
public Custom(Activity a, ArrayList<Items> itemsArrayList) {
this.a = a;
this.itemsArrayList = itemsArrayList;
}
#Override
public int getCount() {
return itemsArrayList.size();
}
#Override
public Object getItem(int i) {
return itemsArrayList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
FilterResults results=new FilterResults();
ArrayList<Items> data=new ArrayList<Items>();
if (filtered==null)
filtered=itemsArrayList;
if (filtered != null && filtered.size() > 0) {
for (final Items g : filtered) {
if (g.getItemname().toLowerCase()
.contains(charSequence.toString()))
data.add(g);
}
results.values=data;
}
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
itemsArrayList=(ArrayList<Items>)filterResults.values;
notifyDataSetChanged();
}
};
}
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
public class Holder{
TextView sr,item,qty,price,pl,min,rate;
}
#Override
public View getView(final int position, final View view, ViewGroup viewGroup) {
final Holder holder=new Holder();
LayoutInflater li=a.getLayoutInflater();
final View view1=li.inflate(R.layout.customlist,viewGroup,false);
holder.sr=(TextView)view1.findViewById(R.id.s_no);
holder.item=(TextView)view1.findViewById(R.id.i_name);
holder.qty=(TextView)view1.findViewById(R.id.qty);
holder.price=(TextView)view1.findViewById(R.id.pr);
holder.rate=(TextView)view1.findViewById(R.id.frate);
holder.pl=(TextView) view1.findViewById(R.id.pl);
holder.min=(TextView) view1.findViewById(R.id.min);
final Items model = itemsArrayList.get(position);
holder.sr.setText(String.valueOf(itemsArrayList.get(position).getSrno()));
holder.item.setText(String.valueOf(itemsArrayList.get(position).getItemname()));
holder.rate.setText(String .valueOf(itemsArrayList.get(position).getFixedrate()));
holder.qty.setText(String.valueOf(itemsArrayList.get(position).getQuantity()));
holder.price.setText(String .valueOf(itemsArrayList.get(position).getRate()));
holder.pl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
model.setQuantity(model.getQuantity() + 1);
model.setRate(model.getQuantity()*model.getFixedrate());
holder.qty.setText(String.valueOf(model.getQuantity()));
holder.price.setText(String.valueOf(model.getRate()));
notifyDataSetChanged();
}
});
holder.min.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(model.getQuantity()>0) {
model.setQuantity(model.getQuantity() - 1);
model.setRate(model.getQuantity() * model.getFixedrate());
holder.qty.setText(String.valueOf(model.getQuantity()));
holder.price.setText(String.valueOf(model.getRate()));
notifyDataSetChanged();
}
}
});
return view1;
}
}
Items.java
public class Items implements Serializable {
int srno,fixedrate,quantity,rate;
String itemname;
public Items(int srno, String itemname, int fixedrate, int quantity, int rate) {
this.srno = srno;
this.itemname = itemname;
this.fixedrate = fixedrate;
this.quantity = quantity;
this.rate = rate;
}
public int getSrno() {
return srno;
}
public void setSrno(int srno) {
this.srno = srno;
}
public String getItemname() {
return itemname;
}
public void setItemname(String itemname) {
this.itemname = itemname;
}
public int getFixedrate() {
return fixedrate;
}
public void setFixedrate(int fixedrate) {
this.fixedrate = fixedrate;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getRate() {
return rate;
}
public void setRate(int rate) {
this.rate = rate;
}
}
Custom_Trial.java
public class Custom_Trial extends BaseAdapter {
Activity a;
private ArrayList<Items> data = new ArrayList<>();
public Custom_Trial(Activity a, ArrayList<Items> data) {
this.a = a;
this.data = data;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public class Holder {
TextView sr, it, qty, amt;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder = new Holder();
LayoutInflater li = a.getLayoutInflater();
View view = li.inflate(R.layout.customtrial, parent, false);
holder.sr = (TextView) view.findViewById(R.id.head1);
holder.it = (TextView) view.findViewById(R.id.head2);
holder.qty = (TextView) view.findViewById(R.id.head3);
holder.amt = (TextView) view.findViewById(R.id.head4);
Items m = data.get(position);
holder.sr.setText(String.valueOf(m.getSrno()));
holder.it.setText(m.getItemname());
holder.qty.setText(String.valueOf(m.getQuantity()));
holder.amt.setText(String.valueOf(m.getRate()));
return view;
}
}
Trial.java
public class Trial extends Activity{
ListView listnew;
private ArrayList<Items> data = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.trial);
listnew = (ListView) findViewById(R.id.newlist);
data.addAll((ArrayList<Items>) getIntent().getSerializableExtra("data"));
Custom_Trial ct = new Custom_Trial(this,data);
listnew.setAdapter(ct);
}
}
It's because you passing original list. You're updating values inside adapter and passing not updated list fromadapter, but original. Write method inside adapter to return your updated list.
Inside Custom.java adapter:
public ArrayList<Items> getItems(){
ArrayList<Items> quantityArrayList;
Items item;
for (int i = 0; i < itemsArrayList.size(); i++){
item = itemsArrayList.get(i);
if (item.getQuantity() > 0)
quantityArrayList.add(item);
}
return quantityArrayList;
}
And inside MainActivity onCreate() should look like this. After clicking show button you're going to get Items from Custom Adapter whose quantity >0.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list_item = (ListView) findViewById(R.id.listdetails);
searchview=(SearchView)findViewById(R.id.searchView);
show = (Button) findViewById(R.id.btnview);
itemsArrayList=new ArrayList<>();
itemsArrayList.add(new Items(1,"Book",20,0,0));
itemsArrayList.add(new Items(2,"Pen",25,0,0));
itemsArrayList.add(new Items(3,"Scale",10,0,0));
itemsArrayList.add(new Items(4,"Eraser",5,0,0));
Custom c = new Custom(this,itemsArrayList);
list_item.setAdapter(c);
list_item.setTextFilterEnabled(true);
setupSearchView();
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Trial.class);
List<Items> quantityList = c.getItems();
intent.putExtra("data", quantityList);
startActivity(intent);
}
});
}