This is my Adapter class:
public class ItemsAdapter extends RecyclerView.Adapter<ItemsAdapter.RecyclerViewHolder> {
ArrayList<Item> arrayList=new ArrayList<>();
public ItemsAdapter(ArrayList<Item> arrayList, Context context) {
this.arrayList = arrayList;
this.context = context;
}
Context context;
public void update(ArrayList<Item> items)
{
this.arrayList=items;
this.notifyDataSetChanged();
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=LayoutInflater.from(context).inflate(R.layout.displays_searchitems,parent,false);
RecyclerViewHolder recyclerViewHolder=new RecyclerViewHolder(view);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
Item item=arrayList.get(position);
holder.ets_ean1.setText(item.getItem_ean());
holder.ets_company.setText(item.getItem_company());
holder.ets_name.setText(item.getItem_name());
holder.ets_desc.setText(item.getItem_desc());
holder.ets_brand.setText(item.getItem_brand());
}
#Override
public int getItemCount() {
return arrayList.size();
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder{
EditText ets_company,ets_name,ets_desc,ets_brand,ets_ean1;
public RecyclerViewHolder(View view) {
super(view);
ets_company= (EditText) view.findViewById(R.id.ets_company);
ets_name=(EditText) view.findViewById(R.id.ets_name);
ets_desc=(EditText) view.findViewById(R.id.ets_desc);
ets_brand=(EditText) view.findViewById(R.id.ets_brand);
ets_ean1=(EditText) view.findViewById(R.id.ets_ean1);
}
}
My POJO class:
public class Item {
private int item_number;
private String item_ean;
private String item_desc;
private String item_name;
private String item_company;
private String item_brand;
public Item(int item_number, String item_ean, String item_desc, String item_name, String item_company, String item_brand) {
this.item_number = item_number;
this.item_ean = item_ean;
this.item_desc = item_desc;
this.item_name = item_name;
this.item_company = item_company;
this.item_brand = item_brand;
}
public Item() {
}
public int getItem_number() {
return item_number;
}
public void setItem_number(int item_number) {
this.item_number = item_number;
}
public String getItem_ean() {
return item_ean;
}
public void setItem_ean(String item_ean) {
this.item_ean = item_ean;
}
public String getItem_desc() {
return item_desc;
}
public void setItem_desc(String item_desc) {
this.item_desc = item_desc;
}
public String getItem_name() {
return item_name;
}
public void setItem_name(String item_name) {
this.item_name = item_name;
}
public String getItem_company() {
return item_company;
}
public void setItem_company(String item_company) {
this.item_company = item_company;
}
public String getItem_brand() {
return item_brand;
}
public void setItem_brand(String item_brand) {
this.item_brand = item_brand;
}
Activity class:
public class Search extends Activity {
TextView textView;
EditText editText,editText1;
ToggleButton toggleButton;
private DBController dbcontroller;
private SQLiteDatabase database;
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
private static final int CAMERA_PHOTO = 111;
private ImageView ImgPhoto;
private Uri imagaeToUploadUri;
ArrayList<HashMap<String, String>> selected = new ArrayList<>();
ArrayList<HashMap<String, String>> pselected = new ArrayList<>();
private ArrayList<Item> arrayList=new ArrayList<>();
ItemsAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
editText = (EditText) findViewById(R.id.et_sdata);
textView = (TextView) findViewById(R.id.textView);
dbcontroller = new DBController(this);
textView = (TextView) findViewById(R.id.txt_message);
toggleButton = (ToggleButton) findViewById(R.id.tggl_btn);
ImgPhoto = (ImageView) findViewById(R.id.imageView);
editText1 = (EditText) findViewById(R.id.ets_ean1);
recyclerView= (RecyclerView) findViewById(R.id.customList);
adapter=new ItemsAdapter(arrayList,this);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
#Override
protected void onResume() {
super.onResume();
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String string = s.toString();
if (string.length() > 0 && string.charAt(string.length() - 1) == '\n') {
displayItems();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
public void displayItems() {
String s2 = editText.getText().toString();
ArrayList<HashMap<String, String>> allItems = dbcontroller.searchdata(s2);
//ArrayList<HashMap<String, String>> predicted = dbcontroller.getpdata(s4);
ArrayList<Item> itemList=new ArrayList<Item>();
s2 = s2.replace("\\n", "").replace("\n", "");
long ean_num=Long.parseLong(s2.trim());
Item item=new Item();
if (allItems.size() == 0) {
allItems = dbcontroller.getpdata(s2);
for (HashMap<String, String> map : allItems)
{
long ean_num_pred = Long.parseLong(map.get("EAN"));
selected=pselected;
selected.add(map);
item.setItem_ean(map.get("item_ean"));
item.setItem_company(map.get("item_company"));
item.setItem_name(map.get("item_name"));
item.setItem_brand(map.get("item_brand"));
item.setItem_desc(map.get("item_desc"));
itemList.add(item);
Log.d("Cpredictor","Items are"+item);
boolean isInserted = dbcontroller.insertReport(editText.getText().toString(), "2");
Log.d("coredictor", "the value is " + ean_num);
Log.d("coredictor", "the predicted value is " + ean_num_pred);
textView.setText("(S)"+s2+"(P)"+map.get("item_ean"));
textView.setTextColor(Color.GREEN);
editText.setText("");
if (isInserted = true)
{
Toast.makeText(Search.this, "Data inserted", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(Search.this, "Data not inserted", Toast.LENGTH_LONG).show();
}
toggleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (((ToggleButton) v).isChecked()) {
boolean isUpdated = dbcontroller.updatePrediction(editText.getText().toString(), "4");
Toast.makeText(getBaseContext(), "Toggle is on" + isUpdated, Toast.LENGTH_LONG).show();
editText.setText("");
} else {
boolean isUpdated = dbcontroller.updatePrediction(editText.getText().toString(), "3");
Toast.makeText(getBaseContext(), "Toggle is off", Toast.LENGTH_LONG).show();
editText.setText("");
}
}
});
}
} else {
for (HashMap<String, String> map : allItems)
{
if (map.get("EAN").equals(s2))
{
item=new Item();
item.setItem_ean(map.get("item_ean"));
item.setItem_company(map.get("item_company"));
item.setItem_name(map.get("item_name"));
item.setItem_brand(map.get("item_brand"));
item.setItem_desc(map.get("item_desc"));
itemList.add(item);
boolean isInserted = dbcontroller.insertReport(editText.getText().toString(), "1");
selected=pselected;
selected.add(map);
textView.setText("ITEM FOUND!!!!!");
textView.setTextColor(Color.BLUE);
editText.setText("");
if (isInserted = true)
Toast.makeText(Search.this, "Data inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(Search.this, "Data not inserted", Toast.LENGTH_LONG).show();
}
}
}
adapter.update(itemList);
//ListAdapter adapter = new SimpleAdapter(Search.this,selected,R.layout.displays_searchitems, new String[]{"EAN", "COMPANY", "NAME", "DESCRIPTION", "BRAND"}, new int[]{
// R.id.ets_ean1, R.id.ets_company, R.id.ets_name, R.id.ets_desc, R.id.ets_brand});
//tomList.setAdapter(adapter);
}
I'm trying to display the data from the database(sqlite).
The logic is working fine. I've put log and i can see it's showing the perfect data. But i dont know why the data is not displayed in my recyclerview.
Guys i need help.
Replace
adapter.update(itemList);
with
arrayList.clear();
arrayList.addAll(itemList);
adapter.notifyDataSetChanged()
inside displaysItem method.
Granular updates is better than Calling notifyDatasetchanged().Be specific and use notifyitem inserted.
public void addItems(List<T> Items)
{
for(T object:Items)
{
add(object);
}
}
public void add(final T object) {
arrayList.add(object);
notifyItemInserted(getItemCount() - 1);
}
#Override
public int getItemCount() {
return arrayList== null ? 0 : arrayList.size();
}
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 am trying implement search function in my section recyclerview
its not working but also not showing error...
i try with edittext addTextChangedListener method.
then in adapter add notifydatachanged method.
try with normal recyclerview its working fine but when use with section recyclerview its not working
sorry for bad english
here is mainActivty
here i get data from server and pass to the adapter in this class i am add the method for filter recyclerview
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_section_rv_search_prac);
init();
initView();
setUpRecyclerView();
tempModels = new ArrayList<TempModel>();
serviceRequest();
searchItem();
}
private void init() {
mAdapter = new ItemRecyclerViewAdapter(SectionRvSearchPrac.this);
}
private void initView() {
mEt_search = findViewById(R.id.et_search_main);
}
///////////////////////////////
private void searchItem() {
mEt_search.addTextChangedListener(
new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
#Override
public void afterTextChanged(Editable s) {
filter(s.toString());
}
});
}
//method for filter list is here..
private void filter(String text) {
ArrayList<TempModel> mFilter_list = new ArrayList<>();
for (TempModel tempModel : tempModels) {
if (tempModel.getName().toLowerCase().contains(text.toLowerCase())) {
mFilter_list.add(tempModel);
}
}
Log.d(TAG, "filter: " + mFilter_list);
mAdapter.filterList(mFilter_list);
}
//////////////////
private void setUpRecyclerView() {
recyclerView = (RecyclerView) findViewById(R.id.sectioned_recycler_view);
recyclerView.setHasFixedSize(true);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
}
private void serviceRequest() {
StringRequest stringRequest =
new StringRequest(
Request.Method.GET,
JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
parseJason(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT)
.show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void parseJason(String response) {
{
Log.d(TAG, "onResponse: " + response);
String[] first;
ArrayList<String> sewction_list = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("data");
String data = jsonArray.getString(0);
first = data.split(Pattern.quote("***^^^***"));
myList_sec = new ArrayList<>(Arrays.asList(first));
for (int j = 0; j < myList_sec.size(); j++) {
myList_first =
new ArrayList<>(Arrays.asList(myList_sec.get(j).split(Pattern.quote("^^^^"))));
sewction_list.add(myList_first.get(0));
myList_second =
new ArrayList<>(Arrays.asList(myList_first.get(1).split(Pattern.quote("^^"))));
ArrayList<String> id = new ArrayList<>();
ArrayList<String> url = new ArrayList<>();
ArrayList<String> img = new ArrayList<>();
ArrayList<String> name = new ArrayList<>();
for (int i = 0; i < myList_second.size(); i++) {
myList_third =
new ArrayList<>(Arrays.asList(myList_second.get(i).split(Pattern.quote("**"))));
url.add(myList_third.get(0));
img.add(myList_third.get(1));
name.add(myList_third.get(2));
id.add(myList_third.get(3));
tempModels.add(
new TempModel(
myList_third.get(2),
myList_third.get(0),
myList_third.get(1),
myList_third.get(3)));
}
sectionModelArrayList.add(new SectionModel(sewction_list, tempModels));
SectionRecyclerViewAdapter adapter =
new SectionRecyclerViewAdapter(
SectionRvSearchPrac.this, recyclerViewType, sectionModelArrayList);
recyclerView.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
here is myitemadapter class for child item
public class ItemRecyclerViewAdapter
extends RecyclerView.Adapter<ItemRecyclerViewAdapter.ItemViewHolder> {
private static final String TAG = "adapter";
private Context context;
ArrayList<TempModel> tempModels;
public ItemRecyclerViewAdapter(Context context) {
this.context = context;
}
public void setData(ArrayList<TempModel> data) {
this.tempModels = data;
}
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view =
LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_custom_row_layout, parent, false);
return new ItemViewHolder(view);
}
#Override
public void onBindViewHolder(ItemViewHolder holder, final int position) {
String path = tempModels.get(position).getImage();
holder.itemLabel.setText(tempModels.get(position).getName());
Picasso.get().load(path).into(holder.imageView);
holder.cardView.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {}
});
}
#Override
public int getItemCount() {
return tempModels.size();
}
/// here method for update filter list
public void filterList(ArrayList<TempModel> filterdNames) {
this.tempModels = filterdNames;
notifyDataSetChanged();
}
class ItemViewHolder extends RecyclerView.ViewHolder {
private TextView itemLabel;
ImageView imageView;
CardView cardView;
public ItemViewHolder(View itemView) {
super(itemView);
itemLabel = (TextView) itemView.findViewById(R.id.item_label);
cardView = itemView.findViewById(R.id.cardview);
imageView = itemView.findViewById(R.id.img);
}
}
section model for section item
public class SectionModel {
private ArrayList<String> sectionLabel;
private ArrayList<TempModel> tempModels;
public SectionModel(ArrayList<String> sectionLabel, ArrayList<TempModel> tempModels) {
this.sectionLabel = sectionLabel;
this.tempModels = tempModels;
}
public ArrayList<String> getSectionLabel() {
return sectionLabel;
}
public ArrayList<TempModel> getTempModels() {
return tempModels;
}
}
model class for item
public class TempModel implements Parcelable{
String name;
String url;
String image;
String num;
public TempModel() {
}
public TempModel(String name, String url, String image, String num) {
this.name = name;
this.url = url;
this.image = image;
this.num = num;
}
protected TempModel(Parcel in) {
name = in.readString();
url = in.readString();
image = in.readString();
num = in.readString();
}
public static final Creator<TempModel> CREATOR = new Creator<TempModel>() {
#Override
public TempModel createFromParcel(Parcel in) {
return new TempModel(in);
}
#Override
public TempModel[] newArray(int size) {
return new TempModel[size];
}
};
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(url);
dest.writeString(image);
dest.writeString(num);
}
}
sectionadapter class
public class SectionRecyclerViewAdapter
extends RecyclerView.Adapter<SectionRecyclerViewAdapter.SectionViewHolder> {
private static final String TAG = "section";
class SectionViewHolder extends RecyclerView.ViewHolder {
private TextView sectionLabel, showAllButton;
private RecyclerView itemRecyclerView;
public SectionViewHolder(View itemView) {
super(itemView);
sectionLabel = (TextView) itemView.findViewById(R.id.section_label);
itemRecyclerView = (RecyclerView) itemView.findViewById(R.id.item_recycler_view);
}
}
private Context context;
private RecyclerViewType recyclerViewType;
private ArrayList<SectionModel> sectionModelArrayList;
public SectionRecyclerViewAdapter(
Context context,
RecyclerViewType recyclerViewType,
ArrayList<SectionModel> sectionModelArrayList) {
this.context = context;
this.recyclerViewType = recyclerViewType;
this.sectionModelArrayList = sectionModelArrayList;
}
#Override
public SectionViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rrow, parent, false);
return new SectionViewHolder(view);
}
#Override
public void onBindViewHolder(SectionViewHolder holder, int position) {
final SectionModel sectionModel = sectionModelArrayList.get(position);
holder.sectionLabel.setText(sectionModel.getSectionLabel().get(position));
// recycler view for items
holder.itemRecyclerView.setHasFixedSize(true);
holder.itemRecyclerView.setNestedScrollingEnabled(false);
GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 3);
holder.itemRecyclerView.setLayoutManager(gridLayoutManager);
/* set layout manager on basis of recyclerview enum type */
ItemRecyclerViewAdapter adapter = new ItemRecyclerViewAdapter(context);
adapter.setData(sectionModel.getTempModels());
holder.itemRecyclerView.setAdapter(adapter);
}
#Override
public int getItemCount() {
return sectionModelArrayList.size();
}
Your code very confusing so i just write my solution.
public class SomeAdapter extends RecyclerView.Adapter<SomeAdapter.SomeViewHolder> implements Filterable{
...
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
mMainList = mYourJSONResponseList;
FilterResults results = new FilterResults();
ArrayList<YourModel> mFilter_list = new ArrayList<>();
//Place your logic
for (YourModel model : mMainList) {
if(model.getName().
toLowerCase().contains(text.toLowerCase())) {
mFilter_list.add(model);
}
}
results.count = mFilter_list.size();
results.values = mFilter_list;
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
mMainList = (ArrayList<YourModel>) filterResults.values;
notifyDataSetChanged();
}
};
return filter;
}
And add this into your text listener
#Override
public void afterTextChanged(Editable s) {
//Add this
adapter.getFilter().filter(s.toString())
}
NOTE!! You will show mMainList only this list in your RecyclerView, And check nullpointerexceptions
I'm not able to see the recycle view, not sure where It has gone wrong. It would be great if you can help me.
Fragment
public class CallDurationFragment extends Fragment {
final FirebaseDatabase database = FirebaseDatabase.getInstance();
ArrayList<CallHistroy> callList = new ArrayList<>();
ArrayList<CallHistroy> callListTemp = new ArrayList<>();
ArrayList<CallHistroy> callObject = new ArrayList<>();
ArrayList<CallHistroy> callListText = new ArrayList<>();
private CallDurationFragment.OnFragmentInteractionListener mListener;
private RecyclerView rvCall;
private RecyclerView.Adapter callAdaptor;
private RecyclerView.LayoutManager eLayoutManager;
private EditText phoneNumber;
private static final int DIALOG_DATE_PICKER = 100;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_callduration_list, container, false);
phoneNumber = (EditText) getActivity().findViewById(editTextSearchKeyPhoneNo);
Context context = getActivity();
rvCall = (RecyclerView) rootView.findViewById(R.id.rvCallDuration);
rvCall.setHasFixedSize(true);
rvCall.setLayoutManager(eLayoutManager);
eLayoutManager = new LinearLayoutManager(getActivity());
phoneNumber.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
callListTemp = getAllCallRecords();
for(int i = 0 ; i < callListTemp.size() ; i++)
if(callListTemp.get(i).getPhoneNumber().contains(s.toString()) )
callListText.add(callListTemp.get(i));
callList = calculateIncomingOutgoing();
callAdaptor = new CallDurationAdapter(getActivity(), callList);
rvCall.setAdapter(callAdaptor);
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
}
});
callList = calculateIncomingOutgoing();
callAdaptor = new CallDurationAdapter(getActivity(), callList);
rvCall.setAdapter(callAdaptor);
return rootView;
}
public ArrayList<CallHistroy> getAllCallRecords(){
DatabaseReference ref = database.getReference();
ref.child("Call").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
callObject.clear();
HashMap<String,Object> call = null;
Iterator<DataSnapshot> items = dataSnapshot.getChildren().iterator();
while(items.hasNext()){
DataSnapshot item = items.next();
Log.e("Listener",item.toString() );
call =(HashMap<String, Object>) item.getValue();
callObject.add(new CallHistroy(call.get("phoneNumber").toString(),call.get("mode").toString(),call.get("duration").toString(), call.get("date").toString(),item.getKey()));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return callObject;
}
public ArrayList<CallHistroy> calculateIncomingOutgoing(){
if(callListText.size() > 0){
callList = callListText;
}else {
callList = getAllCallRecords();
}
ArrayList<CallHistroy> callHistroyIncomingOutgoing = new ArrayList<>();
if(callList.size() > 0){
if(callList.get(0).getMode().equals("Outgoing")) {
callHistroyIncomingOutgoing.add(new CallHistroy(callList.get(0).getPhoneNumber(), "0", callList.get(0).getDuration()));
}else{
callHistroyIncomingOutgoing.add(new CallHistroy(callList.get(0).getPhoneNumber(), callList.get(0).getDuration(), "0"));
}
}
for( int i = 1 ; i < callList.size() ; i++){
boolean setValue = false;
for (int j = 0; j < callHistroyIncomingOutgoing.size() ;j++){
if( callHistroyIncomingOutgoing.get(j).getPhoneNumber().equals(callList.get(i).getPhoneNumber())){
setValue = true;
int incoming = Integer.parseInt(callHistroyIncomingOutgoing.get(j).getIncomingDuration());
int outgoing = Integer.parseInt( callHistroyIncomingOutgoing.get(j).getOutgoingDuration());
int duration = Integer.parseInt( callList.get(i).getDuration());
if(callList.get(i).getMode().equals("Outgoing")) {
callHistroyIncomingOutgoing.get(j).updateDuration(String.valueOf(incoming), String.valueOf(outgoing + duration));
}else{
callHistroyIncomingOutgoing.get(j).updateDuration(String.valueOf(incoming + duration), String.valueOf(outgoing));
}
}
}
if(!setValue) {
if(callList.get(i).getMode() == "Outgoing") {
callHistroyIncomingOutgoing.add(new CallHistroy(callList.get(i).getPhoneNumber(), "0", callList.get(i).getDuration()));
}else{
callHistroyIncomingOutgoing.add(new CallHistroy(callList.get(i).getPhoneNumber(), callList.get(i).getDuration(), "0"));
}
}
}
return callHistroyIncomingOutgoing;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof CallListFragment.OnFragmentInteractionListener) {
mListener = (CallDurationFragment.OnFragmentInteractionListener) context;
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onPause(){
super.onPause();
}
#Override
public void onDestroyView(){
super.onDestroyView();
}
#Override
public void onDestroy(){
super.onDestroy();
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Adaptor
RecyclerView.Adapter<CallDurationAdapter.ViewHolder> {
private List<CallHistroy> mCalls;
private Context mContext;
public CallDurationAdapter(Context context, List<CallHistroy> calls) {
mCalls = calls;
mContext = context;
}
private Context getContext() {
return mContext;
}
#Override
public CallDurationAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View callDurationView = inflater.inflate(R.layout.item_call_duration_details, parent, false);
// Return a new holder instance
ViewHolder viewHolder = new ViewHolder(callDurationView);
return viewHolder;
}
#Override
public void onBindViewHolder(CallDurationAdapter.ViewHolder viewHolder, final int position) {
// Get the data model based on position
final CallHistroy ch = mCalls.get(position);
// Set item views based on your views and data model
viewHolder._phoneNoTextView.setText(ch.getPhoneNumber());
viewHolder._incomingTextView.setText(ch.getIncomingDuration());
viewHolder._outgoingTextView.setText(ch.getOutgoingDuration());
final String key = ch.getKey();
}
#Override
public int getItemCount() {
return mCalls.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView _phoneNoTextView;
public TextView _incomingTextView;
public TextView _outgoingTextView;
public ViewHolder(View itemView) {
super(itemView);
_phoneNoTextView = (TextView) itemView.findViewById(R.id.rvs_duration_phone_no);
_incomingTextView = (TextView) itemView.findViewById(R.id.rvs_duration_outing_total_call);
_outgoingTextView = (TextView) itemView.findViewById(R.id.rvs_duration_incoming_total_call);
}
}
}
Activity
public class CallDurationActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call_duration);
CallDurationFragment newFragment = new CallDurationFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.recordFragmentContainer, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
public void refreshCallDuration(View v) {
Intent intent = new Intent(this, CallDurationActivity.class);
startActivity(intent);
}
protected void onPause() {
super.onPause();
}
protected void onStop() {
super.onStop();
}
protected void onDestroy() {
super.onDestroy();
}
public void onBackCallDuration(View v) {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
}
Object
public class CallHistroy implements Comparable<CallHistroy> {
String phoneNumber;
String mode;
String duration;
String date;
String key;
String incomingDuration;
String outgoingDuration;
int totalIncoming;
int totalOutgoing;
public CallHistroy(String _phontNumber, String _incomingDuration, String _outgoingDuration ){
setPhoneNumber( _phontNumber );
setIncomingDuration( _incomingDuration );
setOutgoingDuration( _outgoingDuration );
}
public CallHistroy(String _date, int _totalIncoming, int _totalOutgoing ){
setDate(_date);
setTotalIncoming( _totalIncoming );
setTotalOutgoing( _totalOutgoing );
}
public void updateCall(int _totalIncoming, int _totalOutgoing){
setTotalIncoming( _totalIncoming );
setTotalOutgoing( _totalOutgoing );
}
public void updateDuration(String _incomingDuration, String _outgoingDuration){
setOutgoingDuration( _incomingDuration );
setIncomingDuration( _outgoingDuration );
}
public CallHistroy(String _phoneNumber, String _mode, String _duration, String _date ){
setPhoneNumber( _phoneNumber );
setDuration( _duration );
setDate( _date );
setMode( _mode );
}
public CallHistroy(String _phoneNumber, String _mode, String _duration, String _date, String _key ){
setPhoneNumber( _phoneNumber );
setDuration( _duration );
setDate( _date );
setMode( _mode );
setKey( _key );
}
public String getIncomingDuration() {
return incomingDuration;
}
public String getOutgoingDuration() {
return outgoingDuration;
}
public int getTotalIncoming() {
return totalIncoming;
}
public int getTotalOutgoing() {
return totalOutgoing;
}
public void setIncomingDuration(String incomingDuration) {
this.incomingDuration = incomingDuration;
}
public void setOutgoingDuration(String outgoingDuration) {
this.outgoingDuration = outgoingDuration;
}
public void setTotalIncoming(int totalIncoming) {
this.totalIncoming = totalIncoming;
}
public void setTotalOutgoing(int totalOutgoing) {
this.totalOutgoing = totalOutgoing;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getDate() {
return date;
}
public String getMode() {
return mode;
}
public String getDuration() {
return duration;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setDate(String date) {
this.date = date;
}
public void setDuration(String duration) {
this.duration = duration;
}
public void setMode(String mode) {
this.mode = mode;
}
#Override
public int compareTo(#NonNull CallHistroy callHistroyObject) {
String[] part = callHistroyObject.date.split("/");
String[] part1 = date.split("/");
int date = Integer.parseInt(part[0]);
int month = Integer.parseInt(part[1]);
String _year = part[2];
int year = Integer.parseInt(_year.substring(0,4));
int date1 = Integer.parseInt(part1[0]);
int month1 = Integer.parseInt(part1[1]);
String _year1 = part1[2];
int year1 = Integer.parseInt(_year1.substring(0,4));
if(year > year1)
return -1;
else if(month > month1)
return -1;
else if(date >date1)
return -1;
else
return 0;
}
}
You're setting your layout manager before it's created
rvCall.setLayoutManager(eLayoutManager);
eLayoutManager = new LinearLayoutManager(getActivity());
should be
eLayoutManager = new LinearLayoutManager(getActivity());
rvCall.setLayoutManager(eLayoutManager);
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();
}
}
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