andorid Recycler View with lists are overlapping each other - android

Here is the image
Please ask me more for more information
public class ProductFragment extends Fragment implements SearchView.OnQueryTextListener,ProductAdaptor.ProductAdapterListener {
private static final String TAG = ProductFragment.class.getSimpleName();
/** The default socket timeout in milliseconds */
public static final int DEFAULT_TIMEOUT_MS = 2500;
/** The default number of retries */
public static final int DEFAULT_MAX_RETRIES = 1;
/** The default backoff multiplier */
public static final float DEFAULT_BACKOFF_MULT = 1f;
private ProductAdaptor adapter;
private RecyclerView recyclerView;
private RequestQueue requestQueue;
private VolleySingleton volleySingleton;
// To store all the products
private static List<ProductInfo> productsList=new ArrayList<>();
ProductAdaptor.ProductAdapterListener listener;
//Progress dialog
private ProgressDialog pDialog;
public static ProductFragment newInstance() {
return new ProductFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pDialog = new ProgressDialog(getActivity());
pDialog.setCancelable(false);
listener=this;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layout=inflater.inflate(R.layout.product_fragment,container,false);
recyclerView= (RecyclerView) layout.findViewById(R.id.productList);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
pDialog.setMessage("Fetching products...");
showpDialog();
volleySingleton=VolleySingleton.getInstance();
requestQueue=volleySingleton.getRequestQueue();
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, AppConfig.URL_PRODUCTS, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//hide the progress dialog
hidepDialog();
adapter=new ProductAdaptor(getActivity(),parseJSONOResponse(response),listener);
recyclerView.setAdapter(adapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(MyApplication.getAppContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Wait 20 seconds and don't retry more than once
jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(
DEFAULT_TIMEOUT_MS,
DEFAULT_MAX_RETRIES,
DEFAULT_BACKOFF_MULT));
requestQueue.add(jsObjRequest);
return layout;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
}
public boolean PerformSearch(String searchString){
//adapter.getFilter().filter(searchString);
return true;
}
public void setDataSet(List<ProductInfo> newDataSet){
productsList = newDataSet;
adapter=new ProductAdaptor(MyApplication.getAppContext(),productsList,this);
recyclerView.swapAdapter(adapter, false);
//new way of filtering data
}
private List<ProductInfo> parseJSONOResponse(JSONObject response){
try {
JSONArray products = response.getJSONArray("products");
for (int i = 0; i < products.length(); i++) {
JSONObject product = (JSONObject) products
.get(i);
String id = product.getString("product_id");
String name = product.getString("name");
String description = product
.getString("description");
String image = AppConfig.URL_IMAGE_PRODUCTS + product.getString("image");
BigDecimal price = new BigDecimal(product
.getString("price"));
ProductInfo p = new ProductInfo(id, name, description,
image, price);
productsList.add(p);
}
return productsList;
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
return productsList;
}
#Override
public void onAddToCartPressed(ProductInfo product) {
CartHandler cartHandler=new CartHandler(MyApplication.getAppContext());
if (cartHandler.getProductsInCartCount()==0) {
cartHandler.addProductInCart(product);
Toast.makeText(MyApplication.getAppContext(),
product.getName() + " added to cart!", Toast.LENGTH_SHORT).show();
}
else{
ProductInfo temp=cartHandler.getProductInCart(Integer.parseInt(product.getId()));
if (temp!=null){
cartHandler.updateProduct(product);
Toast.makeText(MyApplication.getAppContext(),
product.getName() + " added to cart!", Toast.LENGTH_SHORT).show();
}else
{
cartHandler.addProductInCart(product);
Toast.makeText(MyApplication.getAppContext(),
product.getName() + " added to cart!", Toast.LENGTH_SHORT).show();
}
}
}
private void showpDialog() {
if (!pDialog.isShowing()){
pDialog.show();
}
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String query) {
// final List<ProductInfo> filteredModelList = filter(productsList, query);
// adapter.animateTo(filteredModelList);
//recyclerView.scrollToPosition(0);
return true;
}
private List<ProductInfo> filter(List<ProductInfo> models, String query) {
query = query.toLowerCase();
final List<ProductInfo> filteredModelList = new ArrayList<>();
for (ProductInfo model : models) {
final String text = model.getName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
}
Product adaptor
public class ProductAdaptor extends RecyclerView.Adapter<ProductAdaptor.ProductViewHolder>{
//implements Filterable {
private final LayoutInflater inflator;
private final List<ProductInfo> products;
private Context context;
private ProductAdapterListener listener;
ImageLoader imageLoader = VolleySingleton.getInstance().getImageLoader();
//private List<ProductInfo> BackupProducts= Collections.emptyList();
ProductInfo current;
public ProductAdaptor(Context context, List<ProductInfo> data, ProductAdapterListener listener){
inflator= LayoutInflater.from(context);
products=data;
this.context=context;
this.listener=listener;
//BackupProducts=data;
}
#Override
public ProductAdaptor.ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflator.inflate(R.layout.custom_product, parent, false);
ProductViewHolder holder=new ProductViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final ProductAdaptor.ProductViewHolder holder, final int position) {
current=products.get(position);
holder.title.setText(current.getName());
holder.icon.setImageUrl(current.getImage(), imageLoader);
holder.price.setText("Price: Rs. " + current.getPrice());
holder.description.setText(current.getDescription());
holder.add_Cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
products.get(position).setQuantity(Integer.parseInt(holder.etQuantity.getText().toString()));
listener.onAddToCartPressed(products.get(position));
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Reading Position", "" + current.getId());
Intent base=new Intent(context, Products.class);
base.putExtra("product_id", Integer.parseInt(products.get(position).getId()));
base.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
context.startActivity(base);
}
});
}
public void setData(List<ProductInfo> list){
products.clear();
products.addAll(list);
notifyDataSetChanged();
}
/*
public void flushFilter(){
products.clear();
products.addAll(BackupProducts);
notifyDataSetChanged();
}*/
public void animateTo(List<ProductInfo> models) {
applyAndAnimateRemovals(models);
applyAndAnimateAdditions(models);
applyAndAnimateMovedItems(models);
}
private void applyAndAnimateRemovals(List<ProductInfo> newModels) {
for (int i = products.size() - 1; i >= 0; i--) {
final ProductInfo model = products.get(i);
if (!newModels.contains(model)) {
removeItem(i);
}
}
}
private void applyAndAnimateAdditions(List<ProductInfo> newModels) {
for (int i = 0, count = newModels.size(); i < count; i++) {
final ProductInfo model = newModels.get(i);
if (!products.contains(model)) {
addItem(i, model);
}
}
}
private void applyAndAnimateMovedItems(List<ProductInfo> newModels) {
for (int toPosition = newModels.size() - 1; toPosition >= 0; toPosition--) {
final ProductInfo model = newModels.get(toPosition);
final int fromPosition = products.indexOf(model);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
}
public ProductInfo removeItem(int position) {
final ProductInfo model = products.remove(position);
notifyItemRemoved(position);
return model;
}
public void addItem(int position, ProductInfo model) {
products.add(position, model);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition) {
final ProductInfo model = products.remove(fromPosition);
products.add(toPosition, model);
notifyItemMoved(fromPosition, toPosition);
}
#Override
public int getItemCount() {
return products.size();
}
/*
#Override
public Filter getFilter() {
//flushFilter();
return new CardFilter(this,BackupProducts);
}
*/
public interface ProductAdapterListener {
void onAddToCartPressed(ProductInfo product);
}
class ProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView title;
NetworkImageView icon;
TextView price;
TextView description;
LinearLayout add_Cart;
TextView etQuantity;
public ProductViewHolder(final View itemView) {
super(itemView);
icon =(NetworkImageView) itemView.findViewById(R.id.productImage);
title = (TextView) itemView.findViewById(R.id.productName);
price= (TextView) itemView.findViewById(R.id.productPrice);
description=(TextView) itemView.findViewById(R.id.productDescription);
add_Cart= (LinearLayout) itemView.findViewById(R.id.add_cart);
etQuantity= (TextView) itemView.findViewById(R.id.quanity);
}
#Override
public void onClick(View v) {
}
}
These are both of the classes for this Product list please if you need more information please comment
Thanks in advance
There are two classes and those take products from my json and assign it to view holder

This problem is caused because of overlapping fragments and i was starting the fragment like this
fragment=ProductFragment.newInstance();
getSupportFragmentManager().beginTransaction()
.replace(R.id.productFragment,fragment )
.commit();
so making it simply
fragment=ProductFragment.newInstance();
solved my problem.
Thanks guys for help #MohammadAllam

I have this issue too after many search i fixed it whit update gradle dependencies i think its happened because one of old android dependencies.

Related

add integer values selected by checkbox

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

how to checked items from recyclerview to show on another activity recyclerview on button click

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

Un-filtering the result is not working in Recyclerview

I have a recyclerview with some data and I have a searchview, and filter is working just fine. But un-filtering not working. I can't get the whole data in the recyclerview after un-filter. No data is showing. I have to re-open the activity to get data. I tried to used two data sets. But i have no idea where to use them.
My Fragment.
public class YourDealerListFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private static final String STATE_DEALER_LIST = "state_dealer_list";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private VollySingleton vollySingleton;
private RequestQueue requestQueue;
private RecyclerView recyclerView;
private DealerListAdapter dlAdapter;
private HashMap<String, String> hashMap;
private ArrayList<SuggestGetSet> dealerList = new ArrayList<>();
private ArrayList<SuggestGetSet> filteredDealerList = new ArrayList<>();
private String repNo;
private StaggeredGridLayoutManager staggeredGridLayoutManager;
private GridMenuFragment mGridMenuFragment;
private Toolbar toolbar;
private ItemSorter itemSorter;
private Button sortButton;
private SearchView searchView;
private ProgressView progressView;
public static List<String> disChannel;
public YourDealerListFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment YourDealerListFragment.
*/
// TODO: Rename and change types and number of parameters
public static YourDealerListFragment newInstance(String param1, String param2) {
YourDealerListFragment fragment = new YourDealerListFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
vollySingleton = VollySingleton.getsInstance();
requestQueue = vollySingleton.getmRequestQueue();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_your_dealer_list, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.dealerListRecyclerView);
progressView = (ProgressView) view.findViewById(R.id.pViewew);
itemSorter = new ItemSorter();
dlAdapter = new DealerListAdapter();
disChannel = new ArrayList<String>();
repNo = UserLogIn.getRepNo();
if (savedInstanceState != null) {
dealerList = savedInstanceState.getParcelableArrayList(STATE_DEALER_LIST);
dlAdapter.setDealertList(dealerList);
} else {
getJsonRequest();
}
final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.frame_layout);
frameLayout.getBackground().setAlpha(0);
final FloatingActionsMenu fabMenu = (FloatingActionsMenu) view.findViewById(R.id.fab_menu);
final FloatingActionButton fabName = (FloatingActionButton) view.findViewById(R.id.fab_name);
final FloatingActionButton fabCollection = (FloatingActionButton) view.findViewById(R.id.fab_collection);
fabName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onSortByName();
fabMenu.collapse();
}
});
fabMenu.setOnFloatingActionsMenuUpdateListener(new FloatingActionsMenu.OnFloatingActionsMenuUpdateListener() {
#Override
public void onMenuExpanded() {
frameLayout.getBackground().setAlpha(240);
frameLayout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
fabMenu.collapse();
return true;
}
});
}
#Override
public void onMenuCollapsed() {
frameLayout.getBackground().setAlpha(0);
frameLayout.setOnTouchListener(null);
}
});
searchView = (SearchView) view.findViewById(R.id.dealerNameSearchView);
searchView.setOnQueryTextListener(listener);
//custom context menu
mGridMenuFragment = GridMenuFragment.newInstance(R.drawable.background);
setupGridMenu();
mGridMenuFragment.setOnClickMenuListener(new GridMenuFragment.OnClickMenuListener() {
#Override
public void onClickMenu(GridMenu gridMenu, int position) {
switch (position) {
case 0:
Intent intent = new Intent(getActivity(), SelectItem.class);
getActivity().finish();
startActivity(intent);
getActivity();
break;
}
}
});
//dealers' recycler view item click
recyclerView.addOnItemTouchListener(new NavigationDrawerFragment.RecycleTouchListner(getActivity(), recyclerView, new NavigationDrawerFragment.ClickListener() {
#Override
public void onClick(View view, int position) {
FragmentTransaction tx = getActivity().getSupportFragmentManager().beginTransaction();
tx.replace(R.id.main_frame, mGridMenuFragment);
tx.addToBackStack(null);
tx.commit();
}
}));
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(staggeredGridLayoutManager);
final ArrayList<SuggestGetSet> filteredModelList = new ArrayList<>();
for (SuggestGetSet movie : filteredModelList) {
filteredModelList.add(movie);
}
dlAdapter = new DealerListAdapter(filteredModelList, getActivity());
recyclerView.setAdapter(dlAdapter);
}
//search dealer from search view
SearchView.OnQueryTextListener listener = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
final ArrayList<SuggestGetSet> filteredModelList = filter(dealerList, s);
dlAdapter.animateTo(filteredModelList);
recyclerView.scrollToPosition(0);
return true;
}
};
private ArrayList<SuggestGetSet> filter(ArrayList<SuggestGetSet> models, String query) {
query = query.toLowerCase();
final ArrayList<SuggestGetSet> filteredModelList = new ArrayList<>();
for (SuggestGetSet model : models) {
final String text = model.getName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
//custom context menu data
private void setupGridMenu() {
List<GridMenu> menus = new ArrayList<>();
menus.add(new GridMenu("Order", R.drawable.nnn));
menus.add(new GridMenu("Banking", R.drawable.n));
menus.add(new GridMenu("Credit Note", R.drawable.nn));
menus.add(new GridMenu("Cheques", R.drawable.nnnn));
menus.add(new GridMenu("Invoice Dispatch", R.drawable.nnnnn));
menus.add(new GridMenu("Goods Return", R.drawable.nnnnnn));
mGridMenuFragment.setupMenu(menus);
}
private void getJsonRequest() {
progressView.start();
final SQLiteHandler sqLiteHandler = new SQLiteHandler(getActivity().getApplicationContext());
Cursor cr = sqLiteHandler.getData(sqLiteHandler);
cr.moveToFirst();
do {
repNo = cr.getString(0);
} while (cr.moveToNext());
cr.close();
CustomJsonObjectRequest request = new CustomJsonObjectRequest(Request.Method.POST, AppConfig.URL_JSON_DEALER_LIST, hashMap, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progressView.stop();
try {
JSONObject jsonObject = new JSONObject(String.valueOf(response));
if (jsonObject.names().get(0).equals("feed")) {
dealerList = parseJsonResponse(response);
dlAdapter.setDealertList(dealerList);
JSONArray arrayAchSum = response.getJSONArray("feedd");
for (int i = 0; i < arrayAchSum.length(); i++) {
JSONObject obj3 = arrayAchSum.getJSONObject(i);
String a = obj3.getString("dis_channel");
disChannel.add(a);
}
} else {
Toast.makeText(getActivity(), "No Dealers Available", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
/*dealerList = parseJsonResponse(response);
dlAdapter.setDealertList(dealerList);*/
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
protected Map<String, String> getParams() throws AuthFailureError {
hashMap = new HashMap<String, String>();
hashMap.put("repNo", repNo);
return hashMap;
}
};
requestQueue.add(request);
request.setRetryPolicy(new DefaultRetryPolicy(15 * 1000, 0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
private ArrayList<SuggestGetSet> parseJsonResponse(JSONObject response) {
ArrayList<SuggestGetSet> groupList = new ArrayList<>();
if (response != null || response.length() > 0) {
try {
JSONArray arrayDelaers = response.getJSONArray(KEY_FEED_NAME);
for (int i = 0; i < arrayDelaers.length(); i++) {
JSONObject currentObject = arrayDelaers.getJSONObject(i);
String rep = currentObject.getString(KEY_REP_ID);
String name = currentObject.getString(KEY_REP_NAME);
String dealerId = currentObject.getString(KEY_DEALER_ID);
SuggestGetSet delaers = new SuggestGetSet();
delaers.setId(rep);
delaers.setName(name);
delaers.setDealerId(dealerId);
groupList.add(delaers);
}
//Toast.makeText(getApplicationContext(), productList.toString(), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
return groupList;
}
public void onSortByName() {
itemSorter.sortItemByName(dealerList);
dlAdapter.notifyDataSetChanged();
}
public static interface ClickListener {
public void onClick(View view, int position);
//public void onLongClick(View view, int position);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(STATE_DEALER_LIST, dealerList);
}
}
My Adapter class.
public class DealerListAdapter extends RecyclerView.Adapter<DealerListAdapter.ViewHolderDealerList> {
private LayoutInflater layoutInflater;
public Context mcontext;
private List<SuggestGetSet> dealerArrayList;
private List<SuggestGetSet> originalDealerArrayList;
Typeface type;
private static String selectedRepId, selectedDealerId, selectedDealerName;
public DealerListAdapter() {
}
public DealerListAdapter(Context context) {
layoutInflater = LayoutInflater.from(context);
type = Typeface.createFromAsset(context.getAssets(), "helvr.ttf");
}
public static String getDealerName() {
return selectedDealerName;
}
public static String getDealerID() {
return selectedDealerId;
}
public static String getRepID() {
return selectedRepId;
}
public DealerListAdapter(ArrayList<SuggestGetSet> dList, Context context) {
this.mcontext = context;
layoutInflater = LayoutInflater.from(context);
dealerArrayList = new ArrayList<>(dList);
originalDealerArrayList = new ArrayList<>(dList);
type = Typeface.createFromAsset(context.getAssets(), "helvr.ttf");
}
public void setDealertList(ArrayList<SuggestGetSet> dealerAList) {
this.dealerArrayList = dealerAList;
originalDealerArrayList = new ArrayList<>(dealerAList);
notifyItemRangeChanged(0, dealerArrayList.size());
}
#Override
public ViewHolderDealerList onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.custom_dealer_list_layout, parent, false);
ViewHolderDealerList viewHolderDealerList = new ViewHolderDealerList(view);
return viewHolderDealerList;
}
#Override
public void onBindViewHolder(ViewHolderDealerList holder, int position) {
final SuggestGetSet model = dealerArrayList.get(position);
holder.bind(model);
final int pos = position;
holder.dealerName.setText(dealerArrayList.get(position).getName());
holder.dealerName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedDealerId = dealerArrayList.get(pos).getDealerId();
selectedRepId = dealerArrayList.get(pos).getId();
selectedDealerName = dealerArrayList.get(pos).getName();
Toast.makeText(layoutInflater.getContext(), dealerArrayList.get(pos).getName() + " / " + dealerArrayList.get(pos).getDealerId() + " / " + dealerArrayList.get(pos).getId(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return dealerArrayList.size();
}
public void setModels(ArrayList<SuggestGetSet> models) {
dealerArrayList = new ArrayList<>(models);
}
static class ViewHolderDealerList extends RecyclerView.ViewHolder {
private TextView dealerName, dealerId;
public ViewHolderDealerList(View itemView) {
super(itemView);
dealerName = (TextView) itemView.findViewById(R.id.yourDelaerName);
//dealerId = (TextView) itemView.findViewById(R.id.txtDelaerCollection);
}
public void bind(SuggestGetSet model) {
dealerName.setText(model.getName());
}
}
//search animations
public SuggestGetSet removeItem(int position) {
final SuggestGetSet model = dealerArrayList.remove(position);
notifyItemRemoved(position);
return model;
}
public void addItem(int position, SuggestGetSet model) {
dealerArrayList.add(position, model);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition) {
final SuggestGetSet model = dealerArrayList.remove(fromPosition);
dealerArrayList.add(toPosition, model);
notifyItemMoved(fromPosition, toPosition);
}
public void animateTo(ArrayList<SuggestGetSet> models) {
applyAndAnimateRemovals(models);
applyAndAnimateAdditions(models);
applyAndAnimateMovedItems(models);
}
private void applyAndAnimateMovedItems(ArrayList<SuggestGetSet> models) {
for (int toPosition = dealerArrayList.size() - 1; toPosition >= 0; toPosition--) {
final SuggestGetSet model = dealerArrayList.get(toPosition);
final int fromPosition = models.indexOf(model);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
notifyDataSetChanged();
}
private void applyAndAnimateAdditions(ArrayList<SuggestGetSet> models) {
for (int i = 0, count = dealerArrayList.size(); i < count; i++) {
final SuggestGetSet model = dealerArrayList.get(i);
if (!models.contains(model)) {
addItem(i, model);
}
}
notifyDataSetChanged();
}
private void applyAndAnimateRemovals(ArrayList<SuggestGetSet> models) {
for (int i = dealerArrayList.size() - 1; i >= 0; i--) {
final SuggestGetSet model = dealerArrayList.get(i);
if (!models.contains(model)) {
removeItem(i);
}
}
notifyDataSetChanged();
}
}
Just Modify your function and Add check for null or "" .
it will work fine
private ArrayList<SuggestGetSet> filter(ArrayList<SuggestGetSet> models, String query) {
if(TextUtils.isEmpty(query)){
return models;
}
query = query.toLowerCase();
final ArrayList<SuggestGetSet> filteredModelList = new ArrayList<>();
for (SuggestGetSet model : models) {
final String text = model.getName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}

How to send object value from RecyclerView Item to Another Activity

From a JSON array that I am parsing, I want to send a particular object value (using intent putExtra) to another activity. I have read this this question
and the accepted answer but I don't want to send all the values, in my case I only want to send the news_id as an integer to NewsDetails.class.
And I tried using the accepted answer to do it but I got stuck.
MainActivity
public class MainActivity extends AppCompatActivity{
private final String TAG = "MainActivity";
//Creating a list of newss
private List<NewsItems> mNewsItemsList;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "Device rotated and onCreate called");
//Initializing Views
recyclerView = (RecyclerView) findViewById(R.id.news_recycler);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//Initializing the newslist
mNewsItemsList = new ArrayList<>();
adapter = new NewsAdapter(mNewsItemsList, this);
recyclerView.setAdapter(adapter);
//Caling method to get data
getData();
}
//This method will get data from the web api
private void getData(){
Log.d(TAG, "getData called");
//Showing progress dialog
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setCancelable(false);
mProgressDialog.setMessage(this.getResources().getString(R.string.load_news));
mProgressDialog.show();
//Creating a json request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigNews.GET_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse called");
//Dismissing the progress dialog
if (mProgressDialog != null) {
mProgressDialog.hide();
}
/*progressDialog.dismiss();*/
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData(JSONArray array){
Log.d(TAG, "Parsing array");
for(int i = 0; i<array.length(); i++) {
NewsItems newsItem = new NewsItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
newsItem.setNews_title(jsonObject.getString(ConfigNews.TAG_NEWS_TITLE));
newsItem.setNews_excerpt(jsonObject.getString(ConfigNews.TAG_NEWS_EXCERPT));
newsItem.setNewsId(jsonObject.getInt(ConfigNews.TAG_NEWS_ID));
} catch (JSONException w) {
w.printStackTrace();
}
mNewsItemsList.add(newsItem);
}
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy called");
if (mProgressDialog != null){
mProgressDialog.dismiss();
Log.d(TAG, "mProgress dialog dismissed");
}
}
}
NewsItems class
public class NewsItems {
private String news_title;
private String news_excerpt;
private int news_id;
public String getNews_title() {
return news_title;
}
public void setNews_title(String news_title) {
this.news_title = news_title;
}
public String getNews_excerpt() {
return news_excerpt;
}
public void setNews_excerpt(String news_excerpt) {
this.news_excerpt = news_excerpt;
}
public int getNews_id() {
return news_id;
}
public void setNews_id(int news_id) {
this.news_id = news_id;
}
}
NewsAdapter
public class NewsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private ImageLoader imageLoader;
private Context mContext;
//List of newss
private List<NewsItems> mNewsItems;
private final int VIEW_ITEM = 0;
private final int VIEW_PROG = 1;
private int lastPosition = -1;
public NewsAdapter(List<NewsItems> newsItems, Context context) {
super();
//Getting all newss
this.mNewsItems = newsItems;
this.mContext = context;
}
#Override
public int getItemViewType(int position) {
if (isPositionItem(position))
return VIEW_ITEM;
return VIEW_PROG;
}
private boolean isPositionItem(int position) {
return position != getItemCount()-1;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder (ViewGroup parent, int viewType) {
if (viewType == VIEW_ITEM) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.news_summ, parent, false);
return new TextViewHolder(v, mContext);
} else if (viewType == VIEW_PROG){
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recyclerfooter, parent, false);
return new ProgressViewHolder(v);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof TextViewHolder) {
NewsItems newsList = mNewsItems.get(position);
((TextViewHolder) holder).newsTitle.setText(newsList.getNews_title());
((TextViewHolder) holder).newsExcerpt.setText(newsList.getNews_excerpt());
((TextViewHolder) holder).newsId.setText(String.valueOf(newsList.getNewsId()));
} else {
((ProgressViewHolder) holder).progressBar.setIndeterminate(true);
((ProgressViewHolder) holder).loadButton.setText(R.string.reload);
}
}
#Override
public int getItemCount(){
//Return the number of items in the data set
return mNewsItems.size();
}
public static class TextViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView newsTitle,newsExcerpt, newsId;
public ImageButton imageButton;
public NewsItems dNewsItems;
private Context context;
public TextViewHolder (final View newsView, final Context context) {
super(newsView);
this.context = context;
newsTitle = (TextView) newsView.findViewById(R.id.news_title);
newsExcerpt = (TextView) newsView.findViewById(R.id.news_excerpt);
newsId = (TextView) newsView.findViewById(R.id.news_id);
newsExcerpt.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == newsExcerpt.getId()) {
Intent intent = new Intent(context, NewsDetails.class);
Bundle bundle = new Bundle();
bundle.putSerializable("PostId", //This is where I got confused);
}
}
}
}
public static class ProgressViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
Button loadButton;
ProgressBar progressBar;
public ProgressViewHolder(View footerView){
super(footerView);
loadButton = (Button) footerView.findViewById(R.id.reload_button);
progressBar = (ProgressBar) footerView.findViewById(R.id.progress_load);
loadButton.setOnClickListener(this);
if(NetworkCheck.isAvailableAndConnected(footerView.getContext())) {
progressBar.setVisibility(View.VISIBLE);
} else if (!NetworkCheck.isAvailableAndConnected(footerView.getContext())) {
loadButton.setVisibility(View.VISIBLE);
}
}
#Override
public void onClick(View v) {
if (v.getId() == loadButton.getId()) {
//
}
}
}
}
You can send single value also instead of complete object like this -
#Override
public void onClick(View v) {
if (v.getId() == newsExcerpt.getId()) {
Intent intent = new Intent(context, NewsDetails.class);
intent.putExtra("PostId",<your_news_id_here>);
startActivity(intent);
}
}
}
In your case, remove onClick(View v) and change your onBindViewHolder() to setOnClickListener() on newsExcerpt like this -
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof TextViewHolder) {
NewsItems newsList = mNewsItems.get(position);
((TextViewHolder) holder).newsTitle.setText(newsList.getNews_title());
((TextViewHolder) holder).newsExcerpt.setText(newsList.getNews_excerpt());
((TextViewHolder) holder).newsId.setText(String.valueOf(newsList.getNewsId()));
((TextViewHolder) holder).newsExcerpt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, NewsDetails.class);
intent.putExtra("PostId",newsList.getNewsId()); //Any getter of your class you want
startActivity(intent);
});
} else {
((ProgressViewHolder) holder).progressBar.setIndeterminate(true);
((ProgressViewHolder) holder).loadButton.setText(R.string.reload);
}
}
I don't want to send all the values
You dont' have to send all, It's up to you and your needs.
Intent i = new Intent(context, DestActivity.class);
i.putExtra(KEY_NEWS_ID, news_id );
On the other end:
int news_id = getIntent().getIntExtra(KEY_NEWS_ID, defaultValue);

android recycler view two list are showing above each other

http://i.stack.imgur.com/HZ3v6.png
this is the picture of the recycler view
i dont understand what might be causing this problem. so please guys can you give a probablity of what might be the reason.
Thanks in Advance.
public class ProductAdaptor extends RecyclerView.Adapter<ProductAdaptor.ProductViewHolder> {
//implements Filterable {
private final LayoutInflater inflator;
private final List<ProductInfo> products;
private Context context;
private ProductAdapterListener listener;
ImageLoader imageLoader = VolleySingleton.getInstance().getImageLoader();
//private List<ProductInfo> BackupProducts= Collections.emptyList();
ProductInfo current;
public ProductAdaptor(Context context, List<ProductInfo> data, ProductAdapterListener listener) {
inflator = LayoutInflater.from(context);
products = data;
this.context = context;
this.listener = listener;
//BackupProducts=data;
}
#Override
public ProductAdaptor.ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflator.inflate(R.layout.custom_product, parent, false);
ProductViewHolder holder = new ProductViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final ProductAdaptor.ProductViewHolder holder, final int position) {
current = products.get(position);
holder.title.setText(current.getName());
holder.icon.setImageUrl(current.getImage(), imageLoader);
holder.price.setText("Price: Rs. " + current.getPrice());
holder.description.setText(current.getDescription());
holder.add_Cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
products.get(position).setQuantity(Integer.parseInt(holder.etQuantity.getText().toString()));
listener.onAddToCartPressed(products.get(position));
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Reading Position", "" + current.getId());
Intent base = new Intent(context, Products.class);
base.putExtra("product_id", Integer.parseInt(products.get(position).getId()));
base.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
context.startActivity(base);
}
});
}
public void setData(List<ProductInfo> list) {
products.clear();
products.addAll(list);
notifyDataSetChanged();
}
/*
public void flushFilter(){
products.clear();
products.addAll(BackupProducts);
notifyDataSetChanged();
}*/
public void animateTo(List<ProductInfo> models) {
applyAndAnimateRemovals(models);
applyAndAnimateAdditions(models);
applyAndAnimateMovedItems(models);
}
private void applyAndAnimateRemovals(List<ProductInfo> newModels) {
for (int i = products.size() - 1; i >= 0; i--) {
final ProductInfo model = products.get(i);
if (!newModels.contains(model)) {
removeItem(i);
}
}
}
private void applyAndAnimateAdditions(List<ProductInfo> newModels) {
for (int i = 0, count = newModels.size(); i < count; i++) {
final ProductInfo model = newModels.get(i);
if (!products.contains(model)) {
addItem(i, model);
}
}
}
private void applyAndAnimateMovedItems(List<ProductInfo> newModels) {
for (int toPosition = newModels.size() - 1; toPosition >= 0; toPosition--) {
final ProductInfo model = newModels.get(toPosition);
final int fromPosition = products.indexOf(model);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
}
public ProductInfo removeItem(int position) {
final ProductInfo model = products.remove(position);
notifyItemRemoved(position);
return model;
}
public void addItem(int position, ProductInfo model) {
products.add(position, model);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition) {
final ProductInfo model = products.remove(fromPosition);
products.add(toPosition, model);
notifyItemMoved(fromPosition, toPosition);
}
#Override
public int getItemCount() {
return products.size();
}
/*
#Override
public Filter getFilter() {
//flushFilter();
return new CardFilter(this,BackupProducts);
}
*/
public interface ProductAdapterListener {
void onAddToCartPressed(ProductInfo product);
}
static class ProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title;
NetworkImageView icon;
TextView price;
TextView description;
LinearLayout add_Cart;
TextView etQuantity;
public ProductViewHolder(final View itemView) {
super(itemView);
icon = (NetworkImageView) itemView.findViewById(R.id.productImage);
title = (TextView) itemView.findViewById(R.id.productName);
price = (TextView) itemView.findViewById(R.id.productPrice);
description = (TextView) itemView.findViewById(R.id.productDescription);
add_Cart = (LinearLayout) itemView.findViewById(R.id.add_cart);
etQuantity = (TextView) itemView.findViewById(R.id.quanity);
}
#Override
public void onClick(View v) {
}
}
/*
//FILTER THE SEARCH RESULTS
private static class CardFilter extends Filter {
private final ProductAdaptor adapter;
private final List<ProductInfo> originalList;
private final List<ProductInfo> filteredList;
private CardFilter(ProductAdaptor adapter, List<ProductInfo> originalList) {
super();
this.adapter = adapter;
this.originalList = new LinkedList<ProductInfo>(originalList);
this.filteredList = new ArrayList<ProductInfo>();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
filteredList.clear();
final FilterResults results = new FilterResults();
if (constraint.length() == 0) {
filteredList.addAll(originalList);
} else {
final String filterPattern = constraint.toString().toLowerCase().trim();
for (final ProductInfo productInfo : originalList) {
if (productInfo.getName().toLowerCase().trim().contains(filterPattern)) {
filteredList.add(productInfo);
}
}
}
results.values = filteredList;
results.count = filteredList.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
adapter.setData((ArrayList<ProductInfo>) results.values);
adapter.notifyDataSetChanged();
}
}
*/
}
Product Fragment
public class ProductFragment extends Fragment implements SearchView.OnQueryTextListener,ProductAdaptor.ProductAdapterListener {
private static final String TAG = ProductFragment.class.getSimpleName();
private ProductAdaptor adapter;
private RecyclerView recyclerView;
private RequestQueue requestQueue;
private VolleySingleton volleySingleton;
// To store all the products
private List<ProductInfo> productsList=new ArrayList<>();
ProductAdaptor.ProductAdapterListener listener;
//Progress dialog
private ProgressDialog pDialog;
public static ProductFragment newInstance() {
return new ProductFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pDialog = new ProgressDialog(getActivity());
pDialog.setCancelable(false);
listener=this;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layout=inflater.inflate(R.layout.product_fragment,container,false);
recyclerView= (RecyclerView) layout.findViewById(R.id.productList);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
pDialog.setMessage("Fetching products...");
showpDialog();
volleySingleton=VolleySingleton.getInstance();
requestQueue=volleySingleton.getRequestQueue();
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, AppConfig.URL_PRODUCTS, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//hide the progress dialog
hidepDialog();
adapter=new ProductAdaptor(getActivity(),parseJSONOResponse(response),listener);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(MyApplication.getAppContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Wait 20 seconds and don't retry more than once
requestQueue.add(jsObjRequest);
recyclerView.setAdapter(adapter);
return layout;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
}
/*
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main,menu);
final MenuItem item = menu.findItem(R.id.search);
final SearchView searchView = (android.support.v7.widget.SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
}
*/
public boolean PerformSearch(String searchString){
//adapter.getFilter().filter(searchString);
return true;
}
public void setDataSet(List<ProductInfo> newDataSet){
adapter=new ProductAdaptor(MyApplication.getAppContext(),newDataSet,this);
recyclerView.swapAdapter(adapter, false);
//new way of filtering data
}
private List<ProductInfo> parseJSONOResponse(JSONObject response){
try {
JSONArray products = response.getJSONArray("products");
for (int i = 0; i < products.length(); i++) {
JSONObject product = (JSONObject) products
.get(i);
String id = product.getString("product_id");
String name = product.getString("name");
String description = product
.getString("description");
String image = AppConfig.URL_IMAGE_PRODUCTS + product.getString("image");
BigDecimal price = new BigDecimal(product
.getString("price"));
ProductInfo p = new ProductInfo(id, name, description,
image, price);
productsList.add(p);
}
return productsList;
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
return productsList;
}
#Override
public void onAddToCartPressed(ProductInfo product) {
CartHandler cartHandler=new CartHandler(MyApplication.getAppContext());
Log.d("Insert: ", "Inserting ..");
if (cartHandler.getProductsInCartCount()==0) {
cartHandler.addProductInCart(product);
Toast.makeText(MyApplication.getAppContext(),
product.getName() + " added to cart!", Toast.LENGTH_SHORT).show();
}
else{
ProductInfo temp=cartHandler.getProductInCart(Integer.parseInt(product.getId()));
if (temp!=null){
cartHandler.updateProduct(product);
Toast.makeText(MyApplication.getAppContext(),
product.getName() + " added to cart!", Toast.LENGTH_SHORT).show();
}else
{
cartHandler.addProductInCart(product);
Toast.makeText(MyApplication.getAppContext(),
product.getName() + " added to cart!", Toast.LENGTH_SHORT).show();
}
}
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String query) {
final List<ProductInfo> filteredModelList = filter(productsList, query);
adapter.animateTo(filteredModelList);
recyclerView.scrollToPosition(0);
return true;
}
private List<ProductInfo> filter(List<ProductInfo> models, String query) {
query = query.toLowerCase();
final List<ProductInfo> filteredModelList = new ArrayList<>();
for (ProductInfo model : models) {
final String text = model.getName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
}
This problem is caused because of overlapping fragments and i was starting the fragment like this
fragment=ProductFragment.newInstance();
getSupportFragmentManager().beginTransaction()
.replace(R.id.productFragment,fragment )
.commit();
so making it simply
fragment=ProductFragment.newInstance();
solved my problem.
Thanks guys for help #MohammadAllam

Categories

Resources