In my app i have something like a menu that load data stored in SharedPreferences to a Constructor and build from it 2 RecyclerView's.
Now i want to make that if i press an button from the bottom recyclerView like "CICCIO" that has in it constructor item like ID set by 1 i would that in the other recyclerView where there are a lot of colored buttons to be visualized just button's that have also ID set by 1 in their constructor but i'm not very in to android and i can't get how can i make a "sort method" like that.
I have yet the onClick method set on bottom RecyclerView and i have yet method's getID from the bottom recyclerView constructor and getID from the top RecyclerView.
ACTIVITY SCREENSHOT HERE
And here is the code from my activity:
// Builder del BOTTOM recyclerView
public void buildRecyclerViewMenu(){
RecyclerView mRecyclerView = findViewById(R.id.recyclerViewMenu);
mRecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL, false);
RecyclerViewMenu recyclerViewMenu = new RecyclerViewMenu(menuConstructors);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(recyclerViewMenu);
recyclerViewMenu.setOnItemClickListener(new RecyclerViewMenu.OnItemClickListener() {
#Override
public void onItemClick(int position) {
}
});
}
// Builder del TOP recyclerView
public void buildRecyclerView(){
mRecyclerViewBOT = findViewById(R.id.recyclerView);
mRecyclerViewBOT.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 4);
Adapter mAdapter = new Adapter(items);
mRecyclerViewBOT.setLayoutManager(mLayoutManager);
mRecyclerViewBOT.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new Adapter.OnItemClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onItemClick(final int position) {
}
});
}
While here are the method's where i load data to Bottom and top RecyclerView
private void loadDataMenu(){
new ArrayList<MenuConstructor>();
SharedPreferences sharedPreferences = getSharedPreferences("MENU_SAVE", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("menu list",null);
Type type = new TypeToken<ArrayList<MenuConstructor>>() {}.getType();
menuConstructors = gson.fromJson(json, type );
if(menuConstructors == null){
menuConstructors = new ArrayList<>();
Toast.makeText(cassa.this,"NESSUN TASTO DA VISUALIZZARE" ,Toast.LENGTH_SHORT).show();
}
}
private void loadDataTasti(){
new ArrayList<Item>();
SharedPreferences sharedPreferences = getSharedPreferences("TASTI_SAVE", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("tasti list",null);
Type type = new TypeToken<ArrayList<Item>>() {}.getType();
items = gson.fromJson(json, type );
if(items == null){
items = new ArrayList<>();
Toast.makeText(cassa.this,"NESSUN TASTO DA VISUALIZZARE" ,Toast.LENGTH_SHORT).show();
}
}
While here is my Item.java that is the model class of TOP recycler View:
public class Item {
private int menu;
private String tipo;
private String codice;
private String deskT;
private String deskS;
private String sfondo;
private String font;
private String qta;
private double pre;
Item(int id, String typo, String codice_t, String desk_T,String desk_S,String sfondo_c,String font_c,String quant,double prezzo){
menu = id;
tipo = typo;
codice = codice_t;
deskT = desk_T;
deskS = desk_S;
sfondo = sfondo_c;
font = font_c;
qta = quant;
pre = prezzo;
}
public int getMenu(){return menu;}
public String getTipo(){return tipo;}
public String getCodice(){return codice;}
public String getDeskT(){return deskT;}
public String getDeskS(){return deskS;}
public String getSfondo(){return sfondo;}
public String getFont(){return font;}
public String getQuant(){return qta;}
public double getPrice(){return pre;}
}
And here is the model of MenuConstructor (bottom recyclerView)
public class MenuConstructor {
int id;
private String deskT;
private String sfondo;
private String font;
MenuConstructor(int idID,String Desk,String Sfondo,String Font){
id = idID;
deskT = Desk;
sfondo = Sfondo;
font = Font;
}
public int getBtnID(){
return id;
}
public String getDesk(){
return deskT;
}
public String getSfondoColor(){
return sfondo;
}
public String getFontColor(){
return font;
}
}
so i want to compare the id from MenuConstructor with menu (id) from the Item.java and show just item with a certain ID.
You can using Collections.sort()
private List<Item> getSortedItems(List<Item> items) {
Collections.sort(items, new Comparator<Item>() {
#Override
public int compare(Item item, Item nextItem) {
return ComparisonChain.start()
.compare(item.getMenu(), nextItem.getMenu())
.result();
}
});
return items;
}
this method will return the item list sort by menu
hope this helps
Solved by creating a new ArrayList and comparing the item.getMenu() with menuConstructors.getBtnID() in a for cycle which scrolls for the same lenght of the ArrayList.
recyclerViewMenu.setOnItemClickListener(new RecyclerViewMenu.OnItemClickListener() {
#Override
public void onItemClick(int position) {
Toast.makeText(cassa.this,String.valueOf(menuConstructors.get(position).getBtnID()),Toast.LENGTH_SHORT).show();
ArrayList<Item> filteredList = new ArrayList<>();
for(Item item : items) {
if(item.getMenu() == menuConstructors.get(position).getBtnID() ) {
filteredList.add(item);
}
}
mAdapter.filterList(filteredList);
}
});
Related
this is my adapter code
I tried more method, but it's still not working
I don't know where has problem
public class CommentAdapter extends RecyclerView.Adapter<CommentAdapter.CommentViewHolder> {
private Context mContext;
private List<CommentModel> mData;
RequestManager glide;
private LayoutInflater mInflater = null;
private OnItemClickListener mOnItemClickListener = null;
public CommentAdapter(List<CommentModel> mData, Context mContext){
super();
this.mContext = mContext;
this.mData = mData;
this.glide = Glide.with(mContext);
}
#NonNull
#Override
public CommentViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//View row = LayoutInflater.from(mContext).inflate(R.layout.row_comment,parent,false);
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_comment, parent, false);
CommentViewHolder commentViewHolder = new CommentViewHolder(v);
return commentViewHolder;
}
#Override
public void onBindViewHolder(#NonNull CommentViewHolder holder, final int position) {
final CommentModel commentModel = mData.get(position);
//glide.load(mData.get(position).getUserPhoto()).into(holder.img_user);
Glide.with(mContext).load(mData.get(position).getUserPhoto()).into(holder.img_user);
holder.tv_name.setText(mData.get(position).getUsername());
holder.tv_content.setText(mData.get(position).getComment());
holder.tv_date.setText(mData.get(position).getTime());
}
#Override
public int getItemCount() {
return mData==null ? 0 : mData.size();
//return mData.size();
}
public void addTheCommentData(CommentModel commentModel){
if(commentModel!=null){
mData.add(commentModel);
this.notifyDataSetChanged();
}else {
throw new IllegalArgumentException("No Data!");
}
}
public interface OnItemClickListener {
void onClick(View parent, int position);
}
public class CommentViewHolder extends RecyclerView.ViewHolder{
ImageView img_user;
TextView tv_name,tv_content,tv_date;
public CommentViewHolder(View itemView) {
super(itemView);
img_user = itemView.findViewById(R.id.comment_user_img);
tv_name = itemView.findViewById(R.id.comment_username);
tv_content = itemView.findViewById(R.id.comment_comment);
tv_date = itemView.findViewById(R.id.comment_date);
}
}
}
This is my comment code,
When I type the info and submit, it's will writing my server, but the notifyDataSetChanged is no working.
//This method will parse json data
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
//Creating the newFeedModel object
CommentModel newCommentModel = new CommentModel();
JSONObject json = null;
try {
//Getting json
json = array.getJSONObject(i);
String TAG_CommentID = "CommentID";
String TAG_CommentFID = "CommentFID";
String TAG_CommentUID = "CommentUID";
String TAG_Comment = "Comment";
String TAG_PostUserPhoto = "PostUserPhoto";
String TAG_Username = "Username";
String TAG_Time = "Time";
//String TAG_CommentPhoto = "CommentPhoto";
//Adding data to the newFeedModel object
//Log.d("photo", json.getString(TAG_PostUserPhoto));
newCommentModel.setCommentID(json.getString(TAG_CommentID));
newCommentModel.setFeedID(json.getString(TAG_CommentFID));
newCommentModel.setUserID(json.getString(TAG_CommentUID));
newCommentModel.setComment(json.getString(TAG_Comment));
newCommentModel.setUserPhoto(json.getString(TAG_PostUserPhoto));
newCommentModel.setUsername(json.getString(TAG_Username));
newCommentModel.setTime(json.getString(TAG_Time));
//newCommentModel.setTimestamp(json.getString(TAG_CommentPhoto));
} catch (JSONException e) {
e.printStackTrace();
}
//Adding the newFeedModel object to the list
//listCommentModel.add(newCommentModel);
adapter.addTheCommentData(newCommentModel);
}
//Notifying the adapter that data has been added or changed
this.adapter.notifyDataSetChanged();
//getNewDate();
}
But it cannot be working, I don't know what's happen.
Who can told me where need to modify?
I need to leave activity then go back will display.
First Add ArrayList of CommentModel,
Then Add Your Adapter an pass List via constructor of adapter
CommentAdapter adapter;
ArrayList<CommentModel> list;
Inside Parsing
list = new ArrayList<CommentModel>();
list.add(newCommentModel)
adapter = new CommentAdapter(list,this);
So, I need to add under code in CommentModel.java
public class CommentModel {
private String CommentID;
private String FeedID;
private String UserID;
private String Comment;
private String UserPhoto;
private String Username;
private String Time;
CommentAdapter adapter;
ArrayList<CommentModel> list;
public CommentModel(String nickName, String content, String img) {
this.Username = nickName;
this.Comment = content;
this.UserPhoto = img;
}
public String getTime() {
return Time;
}
public void setTime(String time) {
Time = time;
}
then, this code in activicy
editTextComment = findViewById(R.id.post_detail_comment);
feedid = findViewById(R.id.feedid);
recyclerView = (RecyclerView) findViewById(R.id.rv_comment);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
list = new ArrayList<CommentModel>();
list.add(newCommentModel)
adapter = new CommentAdapter(list,this);
is this right?
TestListModel.class
public class TestListModel {
private String testlist_id;
private String test_price;
private String test_name;
private boolean isSelected;
public TestListModel(String testlist_id, String test_price, String test_name,boolean isSelected) {
this.testlist_id = testlist_id;
this.test_price = test_price;
this.test_name = test_name;
this.isSelected = isSelected;
}
public String getTestlist_id() {
return testlist_id;
}
public void setTestlist_id(String testlist_id) {
this.testlist_id = testlist_id;
}
public String getTest_price() {
return test_price;
}
public void setTest_price(String test_price) {
this.test_price = test_price;
}
public String getTest_name() {
return test_name;
}
public void setTest_name(String test_name) {
this.test_name = test_name;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
}
JsonResponse.java
public class JSONResponse {
private TestListModel[] result;
public TestListModel[] getResult() {
return result;
}
public void setResult(TestListModel[] result) {
this.result = result;
}
}
HealthActivity.java
public class HealthServicesActivity extends AppCompatActivity implements View.OnClickListener {
/*
*Api call
* */
private RecyclerView recyclerView;
private ArrayList<TestListModel> data;
private RecyclerAdapter madapter;
private Button submitButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_health_services);
ButterKnife.bind(this);
sharePreferenceManager = new SharePreferenceManager<>(getApplicationContext());
submitButton=(Button) findViewById(R.id.submit_button);
showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));
initViews();
submitButton.setOnClickListener(this);
/*
* On Click Listner
* */
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.submit_button:
int totalAmount = 0;
int totalPrice = 0;
String testName = "";
String testPrice="";
int count = 0;
List<TestListModel> stList = ((RecyclerAdapter) madapter)
.getTestList();
for (int i = 0; i < stList.size(); i++) {
TestListModel singleStudent = stList.get(i);
//AmountCartModel serialNumber = stList.get(i);
if (singleStudent.isSelected() == true) {
testName = testName + "\n" + singleStudent.getTest_name().toString();
testPrice = testPrice+"\n" + singleStudent.getTest_price().toString();
count++;
totalAmount = Integer.parseInt(stList.get(i).getTest_price());
totalPrice = totalPrice + totalAmount;
}
}
Toast.makeText(HealthServicesActivity.this,
"Selected Lists: \n" + testName+ "" + testPrice, Toast.LENGTH_LONG)
.show();
Intent in= new Intent(HealthServicesActivity.this, AmountCartActivity.class);
in.putExtra("test_name", testName);
in.putExtra("test_price", testPrice);
//in.putExtra("total_price",totalPrice);
in.putExtra("total_price", totalPrice);
in.putExtra("serialNumber", count);
startActivity(in);
finish();
break;
/** back Button Click
* */
case R.id.back_to_add_patient:
startActivity(new Intent(getApplicationContext(), PatientActivity.class));
finish();
break;
default:
break;
}
}
/** show center Id in action bar
* */
#Override
protected void onResume() {
super.onResume();
showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));
}
private void showcenterid(LoginModel userLoginData) {
centerId.setText(userLoginData.getResult().getGenCenterId());
centerId.setText(userLoginData.getResult().getGenCenterId().toUpperCase());
deviceModeName.setText(userLoginData.getResult().getDeviceModeName());
}
private void initViews() {
recyclerView = (RecyclerView)findViewById(R.id.test_list_recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
loadJSON();
}
private void loadJSON() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(" http://192.168.1.80/aoplnew/api/")
//
.baseUrl("https://earthquake.usgs.gov/fdsnws/event/1/query?")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface request = retrofit.create(ApiInterface.class);
Call<JSONResponse> call = request.getTestLists();
call.enqueue(new Callback<JSONResponse>() {
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
JSONResponse jsonResponse = response.body();
data = new ArrayList<>(Arrays.asList(jsonResponse.getResult()));
madapter = new RecyclerAdapter(data);
recyclerView.setAdapter(madapter);
}
#Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Log.d("Error",t.getMessage());
}
});
}
HealthRecyclerAdapter.java
public class RecyclerAdapter extends
RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private ArrayList<TestListModel> android;
public RecyclerAdapter(ArrayList<TestListModel> android) {
this.android = android;
}
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.test_list_row,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerAdapter.ViewHolder holder, final int position) {
holder.test_name.setText(android.get(position).getTest_name());
holder.test_price.setText(android.get(position).getTest_price());
holder.chkSelected.setChecked(android.get(position).isSelected());
holder.chkSelected.setTag(android.get(position));
holder.chkSelected.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
TestListModel contact = (TestListModel) cb.getTag();
contact.setSelected(cb.isChecked());
android.get(position).setSelected(cb.isChecked());
Toast.makeText(
v.getContext(),
"Clicked on Checkbox: " + cb.getText() + " is " + cb.isChecked(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return android.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView test_name;
private TextView test_price;
public CheckBox chkSelected;
public TestListModel testLists;
public ViewHolder(View itemView) {
super(itemView);
test_name = (TextView)itemView.findViewById(R.id.test_name);
test_price = (TextView)itemView.findViewById(R.id.price_name);
chkSelected = (CheckBox) itemView.findViewById(R.id.check_box);
}
}
// method to access in activity after updating selection
public List<TestListModel> getTestList() {
return android;
}
AmountCartModel.java
public class AmountCartModel {
private String testName;
private String testPrice;
private Integer serialNumber;
private Integer totalPrice;
public AmountCartModel() {
this.testName = testName;
this.testPrice = testPrice;
this.serialNumber = serialNumber;
this.totalPrice = totalPrice;
}
public String getTestName() {
return testName;
}
public void setTestName(String testName) {
this.testName = testName;
}
public String getTestPrice() {
return testPrice;
}
public void setTestPrice(String testPrice) {
this.testPrice = testPrice;
}
public Integer getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(Integer serialNumber) {
this.serialNumber = serialNumber;
}
public Integer getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(Integer totalPrice) {
this.totalPrice = totalPrice;
}
}
AmountCartActivity.java
public class AmountCartActivity extends AppCompatActivity implements View.OnClickListener {
#BindView(R.id.total_price)
TextView totalPriceDisplay;
SharePreferenceManager<LoginModel> sharePreferenceManager;
private RecyclerView recyclerView;
List<AmountCartModel> mydataList ;
private MyAdapter madapter;
Bundle extras ;
String testName="";
String testPrice="";
String totalPrice= "";
int counting = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_amount_cart);
ButterKnife.bind(this);
sharePreferenceManager = new SharePreferenceManager<>(getApplicationContext());
showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));
mydataList = new ArrayList<>();
/*
* Getting Values From BUNDLE
* */
extras = getIntent().getExtras();
if (extras != null) {
testName = extras.getString("test_name");
testPrice = extras.getString("test_price");
totalPrice = String.valueOf(extras.getInt("total_price"));
counting = extras.getInt("serialNumber");
//Just add your data in list
AmountCartModel mydata = new AmountCartModel(); // object of Model Class
mydata.setTestName(testName );
mydata.setTestPrice(testPrice);
mydata.setTotalPrice(Integer.valueOf(totalPrice));
mydata.setSerialNumber(counting);
mydataList.add(mydata);
//totalPriceDisplay.setText(totalPrice);
}
madapter=new MyAdapter(mydataList);
madapter.setMyDataList(mydataList);
recyclerView = (RecyclerView)findViewById(R.id.recyler_amount_cart);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(madapter);
RecyclerAdapter.java //RecyclerAdapter for AmountCart
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>
{
private List<AmountCartModel> context;
private List<AmountCartModel> myDataList;
public MyAdapter(List<AmountCartModel> context) {
this.context = context;
myDataList = new ArrayList<>();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
// Replace with your layout
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.amount_cart_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// Set Your Data here to yout Layout Components..
// to get Amount
/* myDataList.get(position).getTestName();
myDataList.get(position).getTestPrice();*/
holder.testName.setText(myDataList.get(position).getTestName());
holder.testPrice.setText(myDataList.get(position).getTestPrice());
holder.textView2.setText(myDataList.get(position).getSerialNumber());
}
#Override
public int getItemCount() {
/*if (myDataList.size() != 0) {
// return Size of List if not empty!
return myDataList.size();
}
return 0;*/
return myDataList.size();
}
public void setMyDataList(List<AmountCartModel> myDataList) {
// getting list from Fragment.
this.myDataList = myDataList;
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView testName,testPrice,textView2;
public ViewHolder(View itemView) {
super(itemView);
// itemView.findViewById
testName=itemView.findViewById(R.id.test_name_one);
testPrice=itemView.findViewById(R.id.test_price);
textView2=itemView.findViewById(R.id.textView2);
}
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new
Intent(AmountCartActivity.this,HealthServicesActivity.class));
finish();
}
}
This is my code.
Here I am taking HealthActivity and in this class by using recycler view I have displayed testList in recycler view. I am passing testList whichever I am selecting through checkbox to AmountCartActivity of recycler View, And, I am calculating total amount of the selected testList and I am getting the result and that result I am passing to the AmountCart Activity through bundle and I am getting correct result in bundle, but, when I am trying to display total amount in a textView its showing me nothing.
And, my second problem is,
I am trying to display serial number to to my AmountCartActivity of recycler view whichever I am selecting from previous HealthCartActivity using checkbox. And, I have implemented some code but I am not getting how to solve it. please help me.
For Issue#1
Data should be passed onto the Adapter through constructor. The issue could simply be adding another parameter to the constructor:
public MyAdapter(List<AmountCartModel> context, List<AmountCartModel> myDataList) {
this.context = context;
myDataList = this.myDataList;
}
Or,
To add selection support to a RecyclerView instance:
Determine which selection key type to use, then build a ItemKeyProvider.
Implement ItemDetailsLookup: it enables the selection library to access information about RecyclerView items given a MotionEvent.
Update item Views in RecyclerView to reflect that the user has selected or unselected it.
The selection library does not provide a default visual decoration for the selected items. You must provide this when you implement onBindViewHolder() like,
In onBindViewHolder(), call setActivated() (not setSelected()) on the View object with true or false (depending on if the item is selected).
Update the styling of the view to represent the activated status.
For Issue #2
Try using passing data through intents.
The easiest way to do this would be to pass the serial num to the activity in the Intent you're using to start the activity:
Intent intent = new Intent(getBaseContext(), HealthServicesActivity.class);
intent.putExtra("EXTRA_SERIAL_NUM", serialNum);
startActivity(intent);
Access that intent on next activity
String sessionId= getIntent().getStringExtra("EXTRA_SERIAL_NUM");
I have a list view and I want to sort the list view with four categories, String name (alphabetical), String Category (alphabetical), String Date (from new to old), int Price (from 99999 to 0). I want to sort the list view when radio button is clicked.
This is my Expenses Activity when I want the list view
public class ExpensesActivity extends AppCompatActivity {
Button btnAddExpenses;
ListView lvExpenses;
CustomArrayAdapterExpenses adapter;
ArrayList<String> alExpensesName;
ArrayList<String> alExpensesPrice;
ArrayList<String> alExpensesCategory;
ArrayList<String> alExpensesDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_expenses);
final GlobalClass globalClass = (GlobalClass) getApplicationContext();
final Bundle extras = getIntent().getExtras();
btnAddExpenses = (Button) findViewById(R.id.btnAddExpenses);
lvExpenses = (ListView) findViewById(R.id.lvExpenses);
alExpensesName = globalClass.allTrips.get(extras.getInt("position")).getItemsString();
alExpensesPrice = new ArrayList<>();
for (Double i: globalClass.allTrips.get(extras.getInt("position")).getItemsCost()){
alExpensesPrice.add(String.valueOf(i));
}
alExpensesCategory = globalClass.allTrips.get(extras.getInt("position")).getItemsCategory();
alExpensesDate = globalClass.allTrips.get(extras.getInt("position")).getItemsDate();
adapter = new CustomArrayAdapterExpenses(this, alExpensesName, alExpensesCategory , alExpensesPrice, alExpensesDate);
lvExpenses.setAdapter(adapter);
btnAddExpenses.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ExpensesActivity.this, AddExpensesActivity.class);
intent.putExtra("position", extras.getInt("position"));
finish();
startActivity(intent);
}
});
lvExpenses.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(ExpensesActivity.this, ExpenseActivity.class);
intent.putExtra("position", extras.getInt("position"));
intent.putExtra("positionExpense", position);
finish();
startActivity(intent);
}
});
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.rbName:
if (checked) {
/*
Collections.sort(alExpensesName, new Comparator<String>()
{
#Override
public int compare(String text1, String text2)
{
return text1.compareToIgnoreCase(text2);
}
});
adapter.notifyDataSetChanged();
*/
}
break;
case R.id.rbPrice:
if (checked){
}
break;
case R.id.rbCategory:
if (checked) {
}
break;
case R.id.rbDate:
if (checked) {
}
break;
}
}
#Override
public void onBackPressed() {
//super.onBackPressed();
final Bundle extras = getIntent().getExtras();
Intent intent = new Intent(ExpensesActivity.this, TripActivity.class);
intent.putExtra("position", extras.getInt("position"));
finish();
startActivity(intent);
}
}
This is CustomArrayAdapterExpenses
public class CustomArrayAdapterExpenses extends BaseAdapter {
ArrayList<String> alExpensesName;
ArrayList<String> alExpensesPrice;
ArrayList<String> alExpensesCategory;
ArrayList<String> alExpensesDate;
Context mContext;
//constructor
public CustomArrayAdapterExpenses(Context mContext, ArrayList<String> alExpensesName, ArrayList<String> alExpensesCategory, ArrayList<String> alExpensesPrice, ArrayList<String> alExpensesDate) {
this.mContext = mContext;
this.alExpensesName = alExpensesName;
this.alExpensesCategory = alExpensesCategory;
this.alExpensesPrice = alExpensesPrice;
this.alExpensesDate = alExpensesDate;
}
public int getCount() {
return alExpensesName.size();
}
public Object getItem(int arg0) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View arg1, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.item_list_expenses, viewGroup, false);
TextView tvExpensesName = (TextView) row.findViewById(R.id.tvExpensesName);
TextView tvExpensesCategory = (TextView) row.findViewById(R.id.tvExpensesCategory);
TextView tvExpensesPrice = (TextView) row.findViewById(R.id.tvExpensesPrice);
TextView tvExpensesDate = (TextView) row.findViewById(R.id.tvExpensesDate);
tvExpensesName.setText(alExpensesName.get(position));
tvExpensesCategory.setText(alExpensesCategory.get(position));
tvExpensesPrice.setText(alExpensesPrice.get(position));
tvExpensesDate.setText(alExpensesDate.get(position));
return row;
}
}
This is my Trip Class
public class Trip {
/** A map with category as key and the associed list of items as value */
Map<String,List<Item>> expanses;
private String name;
private Calendar FirstDate;
private Calendar EndDate;
private int HowMuchDays;
private String SFirstDate, SEndDate;
public ArrayList<String> ExpensesCategory = new ArrayList<>();
public ArrayList<String> Adults = new ArrayList<>();
public ArrayList<String> Children = new ArrayList<>();
public ArrayList<String> ShoppingName = new ArrayList<>();
public ArrayList<Double> ShoppingPrice = new ArrayList<>();
public ArrayList<String> ShoppingCategory = new ArrayList<>();
public ArrayList<TraveledDay> TraveledDays = new ArrayList<>();
public ArrayList<Fuel> Fuels = new ArrayList<>();
public double budget = 0;
/** An item in the expanses list */
static class Item {
final String name;
final double cost;
final String Category;
final String Date;
String Description;
public Item(String name, double cost, String Category, String Date) {
this.name = name;
this.cost = cost;
this.Category = Category;
this.Date = Date;
}
#Override public String toString() {
return this.name + " (" + this.cost + "$)";
}
public String getName(){
return name;
}
public String getCategory(){
return Category;
}
public double getCost(){
return cost;
}
public String getDate(){
return Date;
}
public String getDescription(){ return Description; }
}
static class TraveledDay {
final String Date;
final int FirstKM;
final int EndKM;
final int KM;
public TraveledDay(int FirstKM, int EndKM, String Date) {
this.FirstKM = FirstKM;
this.EndKM = EndKM;
this.Date = Date;
KM = EndKM - FirstKM;
}
#Override public String toString() {
return this.Date + " (" + this.KM + ")";
}
public int getFirstKM(){
return FirstKM;
}
public int getEndKM(){
return EndKM;
}
public int getKM(){
return KM;
}
public String getDate(){
return Date;
}
}
static class Fuel {
final String Date;
final int CurrentKM;
final int LastKM;
final int SumKM;
final double SumLiter;
final double LiterPrice;
final double SumPrice;
public String getDate() {
return Date;
}
public int getCurrentKM() {
return CurrentKM;
}
public int getLastKM() {
return LastKM;
}
public int getSumKM() {
return SumKM;
}
public double getSumLiter() {
return SumLiter;
}
public double getLiterPrice() {
return LiterPrice;
}
public double getSumPrice() {
return SumPrice;
}
public Fuel(String Date, int CurrentKM, int LastKM, int SumKM, double SumLiter, double LiterPrice, double SumPrice) {
this.Date = Date;
this.CurrentKM = CurrentKM;
this.LastKM = LastKM;
this.SumKM = SumKM;
this.SumLiter = SumLiter;
this.LiterPrice = LiterPrice;
this.SumPrice = SumPrice;
}
#Override public String toString() {
return this.Date + " (" + this.SumKM + ")";
}
}
public Trip(String name, Calendar FirstDate, Calendar EndDate, String SFirstDate, String SEndDate) {
this.name = name;
this.FirstDate = FirstDate;
this.EndDate = EndDate;
HowMuchDays = (int)((EndDate.getTime().getTime() - FirstDate.getTime().getTime()) / (1000 * 60 * 60 * 24));
this.SEndDate = SEndDate;
this.SFirstDate = SFirstDate;
this.expanses = new HashMap<String,List<Item>>();
ExpensesCategory.add("כרטיסי טיסה");
ExpensesCategory.add("לינה");
ExpensesCategory.add("תחבורה");
ExpensesCategory.add("אוכל");
ExpensesCategory.add("אתרים");
ExpensesCategory.add("שונות");
for (String cat: ExpensesCategory) { // init the categories with empty lists
this.expanses.put(cat, new ArrayList<Item>());
}
}
public String getName(){
return name;
}
public Calendar getFirstDate(){
return FirstDate;
}
public Calendar getEndDate(){
return EndDate;
}
public Integer getHowMuchDays(){
return HowMuchDays;
}
public String getSFirstDate(){
return SFirstDate;
}
public String getSEndDate(){
return SEndDate;
}
/** Register a new expanse to the trip. */
public void add(String item, double cost, String category, String Date) {
List<Item> list = this.expanses.get(category);
if (list == null)
throw new IllegalArgumentException("Category '"+category+"' does not exist.");
list.add( new Item(item, cost, category, Date) );
}
public void addTraveledDay(int FirstKM, int EndKM, String Date) {
ArrayList<TraveledDay> list = TraveledDays;
list.add( new TraveledDay(FirstKM, EndKM, Date) );
}
public void removeTraveledDay(int index) {
ArrayList<TraveledDay> list = TraveledDays;
list.remove(index);
}
public ArrayList<Integer> getTraveledFirstKM(){
ArrayList<Integer> listInteger = new ArrayList<>();
for (TraveledDay traveledDay : TraveledDays){
listInteger.add(traveledDay.getFirstKM());
}
return listInteger;
}
public ArrayList<Integer> getTraveledEndKM(){
ArrayList<Integer> listInteger = new ArrayList<>();
for (TraveledDay traveledDay : TraveledDays){
listInteger.add(traveledDay.getEndKM());
}
return listInteger;
}
public ArrayList<Integer> getTraveledKM(){
ArrayList<Integer> listInteger = new ArrayList<>();
for (TraveledDay traveledDay : TraveledDays){
listInteger.add(traveledDay.getKM());
}
return listInteger;
}
public ArrayList<String> getTraveledDate() {
ArrayList<String> listString = new ArrayList<String>();
for (TraveledDay traveledDay : TraveledDays){
listString.add(traveledDay.getDate());
}
return listString;
}
public ArrayList<String> getFuelDate() {
ArrayList<String> listString = new ArrayList<String>();
for (Fuel fuel : Fuels){
listString.add(fuel.getDate());
}
return listString;
}
public ArrayList<Integer> getFuelCurrentKM(){
ArrayList<Integer> listInteger = new ArrayList<>();
for (Fuel fuel : Fuels){
listInteger.add(fuel.getCurrentKM());
}
return listInteger;
}
public ArrayList<Integer> getFuelLastKM(){
ArrayList<Integer> listInteger = new ArrayList<>();
for (Fuel fuel : Fuels){
listInteger.add(fuel.getLastKM());
}
return listInteger;
}
public ArrayList<Integer> getFuelSumKM(){
ArrayList<Integer> listInteger = new ArrayList<>();
for (Fuel fuel : Fuels){
listInteger.add(fuel.getSumKM());
}
return listInteger;
}
public ArrayList<Double> getFuelSumLiter(){
ArrayList<Double> listDouble = new ArrayList<>();
for (Fuel fuel : Fuels){
listDouble.add(fuel.getSumLiter());
}
return listDouble;
}
public ArrayList<Double> getFuelLiterPrice(){
ArrayList<Double> listDouble = new ArrayList<>();
for (Fuel fuel : Fuels){
listDouble.add(fuel.getLiterPrice());
}
return listDouble;
}
public ArrayList<Double> getFuelSumPrice(){
ArrayList<Double> listDouble = new ArrayList<>();
for (Fuel fuel : Fuels){
listDouble.add(fuel.getSumPrice());
}
return listDouble;
}
/** Get the expanses, given a category.
* #return a fresh ArrayList containing the category elements, or null if the category does not exists
*/
public List<Item> getItems(String category) {
List<Item> list = this.expanses.get(category);
if (list == null)
return null;
return new ArrayList<Item>(list);
}
/** Get the expanses, given a category.
* #return a fresh ArrayList containing all the elements
*/
public List<Item> getItems() {
List<Item> list = new ArrayList<Item>();
for (List<Item> l: this.expanses.values()) // fill with each category items
list.addAll(l);
return list;
}
public ArrayList<String> getItemsString() {
List<Item> list = new ArrayList<Item>();
for (List<Item> l: this.expanses.values()) // fill with each category items
list.addAll(l);
ArrayList<String> listString = new ArrayList<String>();
for (Item item : list){
listString.add(item.getName());
}
return listString;
}
public ArrayList<String> getItemsDescription() {
List<Item> list = new ArrayList<Item>();
for (List<Item> l: this.expanses.values()) // fill with each category items
list.addAll(l);
ArrayList<String> listString = new ArrayList<String>();
for (Item item : list){
listString.add(item.getDescription());
}
return listString;
}
public ArrayList<String> getItemsDate() {
List<Item> list = new ArrayList<Item>();
for (List<Item> l: this.expanses.values()) // fill with each category items
list.addAll(l);
ArrayList<String> listString = new ArrayList<String>();
for (Item item : list){
listString.add(item.getDate());
}
return listString;
}
public ArrayList<Double> getItemsCost(){
List<Item> list = new ArrayList<Item>();
for (List<Item> l: this.expanses.values()) // fill with each category items
list.addAll(l);
ArrayList<Double> listDouble = new ArrayList<>();
for (Item item : list){
listDouble.add(item.getCost());
}
return listDouble;
}
public ArrayList<String> getItemsCategory() {
List<Item> list = new ArrayList<Item>();
for (List<Item> l: this.expanses.values()) // fill with each category items
list.addAll(l);
ArrayList<String> listString = new ArrayList<String>();
for (Item item : list){
listString.add(item.getCategory());
}
return listString;
}
/** Get the total cost, given a category. */
public double getCost(String category) {
List<Item> list = this.expanses.get(category);
if (list == null)
return -1;
double cost = 0;
for (Item item: list)
cost += item.cost;
return cost;
}
/** Get the total cost. */
public double getCost() {
double cost = 0;
for (List<Item> l: this.expanses.values())
for (Item item: l)
cost += item.cost;
cost *= 1000;
cost = (int)(cost);
cost /= 1000;
return cost;
}
}
This is my global class
public class GlobalClass extends Application {
ArrayList<Trip> allTrips = new ArrayList<>();
public ArrayList<String> allTripsString() {
ArrayList<String> allTripsString = new ArrayList<String>();
for (Trip trip : allTrips){
allTripsString.add(trip.getName());
}
return allTripsString;
}
public ArrayList<Integer> allTripsHowMuchDate() {
ArrayList<Integer> allTripsString = new ArrayList<>();
for (Trip trip : allTrips){
allTripsString.add(trip.getHowMuchDays());
}
return allTripsString;
}
public ArrayList<String> allTripsSFirstDate() {
ArrayList<String> allTripsString = new ArrayList<>();
for (Trip trip : allTrips){
allTripsString.add(trip.getSFirstDate());
}
return allTripsString;
}
public ArrayList<String> allTripsSEndDate() {
ArrayList<String> allTripsString = new ArrayList<>();
for (Trip trip : allTrips){
allTripsString.add(trip.getSEndDate());
}
return allTripsString;
}
public void saveList(Context context, List<Trip> list) {
String PREFS_NAME = "PRODUCT_APP";
String KEY_NAME = "KEY_NAME";
SharedPreferences settings;
SharedPreferences.Editor editor;
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonlist = gson.toJson(list);
editor.putString(KEY_NAME, jsonlist);
editor.commit();
}
public void loadList(Context context){
String PREFS_NAME = "PRODUCT_APP";
String KEY_NAME = "KEY_NAME";
SharedPreferences settings;
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
Gson gson = new Gson();
String jsonlist = settings.getString(KEY_NAME, "");
if (jsonlist.isEmpty()) {
allTrips = new ArrayList<>();
} else {
Type type = new TypeToken<ArrayList<Trip>>(){}.getType();
allTrips = gson.fromJson(jsonlist, type);
}
}
}
There are two solution of the issue:
1. Easy way to solve is to create a custom class having 4 attributes: name, category, price and expanse date or use existing class Item. Pass the array of custom objects to adapter. If you try to sort this custom objects array based on any key mapping between different attributes will be never lost and it meets your problem. On RadioButtonClick listener sort the custom array and update the adapter and notify.
Try to sort the 4 array simultaneously based on one key. Like if you want to sort based on name, try to implement the selection sort on name array and on swapping swap elements in all four array to maintain the mapping between all four. Performance of sorting is not good in this solution. To implement this refer How to sort multiple ArrayLists based off order of another?
I want to use Retrofit to load data from server, and I use DataModel for set and get data.
This is what I would like to do. When I click on a Category, I want to see posts from this category in the other Activity.
For showing category posts I use this link : http://tellfa.com/tafrihgah/?json=get_category_posts
For filtering I use category id.
For example : http://tellfa.com/tafrihgah/?json=get_category_posts&id=1 by this link i see all of posts from Category1.
My Retrofit interface for set link: (I set base_url in other class)
public interface Retrofit_ApiInterface {
// For Categories Response
#GET("tafrihgah/?json=get_category_posts&")
Call<R_CatModelResponse> getCatResponse(#Query("id") Integer id);
}
I send category id to other activity by this code :
public class ColoniesAdapter extends RecyclerView.Adapter<ColoniesAdapter.ViewHolder> {
private List<Retrofit_ColoniesModel> mDateSet;
private Context mContext;
private SparseBooleanArray expandState = new SparseBooleanArray();
public ColoniesAdapter(Context context, List<Retrofit_ColoniesModel> dataSet) {
this.mContext = context;
this.mDateSet = dataSet;
for (int i = 0; i < mDateSet.size(); i++) {
expandState.append(i, false);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.colonies_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.colonies_title.setText(mDateSet.get(position).getTitle());
holder.colonies_title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = holder.getPosition();
Retrofit_ColoniesModel model = mDateSet.get(pos);
mContext.startActivity(new Intent(v.getContext(), Category_page.class)
.putExtra("categoryTitle", model.getTitle())
.putExtra("categoryID", model.getId()));
Toast.makeText(mContext, " " + model.getId(), Toast.LENGTH_SHORT).show();
}
});
...
Category_page code:
public class Category_page extends AppCompatActivity {
private static final long RIPPLE_DURATION = 250;
private Toolbar toolbar;
private TextView toolbar_title;
private ImageView toolbar_menuImage;
private RelativeLayout root;
private CategoryAdapter mAdapter;
private RecyclerView cat_recyclerView;
private LinearLayoutManager mLayoutManager;
private RelativeLayout loadLayout;
private String catTitle = "";
private Integer catID;
private Bundle bundle;
private int pageCount = 1;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_page);
//if (!EventBus.getDefault().isRegistered(this)) {
// EventBus.getDefault().register(this);
//}
// Hide StatusBar color
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
// Initializing
context = Category_page.this;
toolbar = (Toolbar) findViewById(R.id.category_toolbar);
cat_recyclerView = (RecyclerView) findViewById(R.id.category_recycler);
toolbar_title = (TextView) toolbar.findViewById(R.id.toolbar_pages_title);
mLayoutManager = new LinearLayoutManager(this);
root = (RelativeLayout) findViewById(R.id.category_root);
loadLayout = (RelativeLayout) findViewById(R.id.category_empty_layout);
// Toolbar
setSupportActionBar(toolbar);
if (toolbar != null) {
getSupportActionBar().setTitle("");
}
// Receive Data
bundle = getIntent().getExtras();
catID = bundle.getInt("categoryID");
if (bundle != null) {
catTitle = bundle.getString("categoryTitle");
}
if (catTitle != null) {
toolbar_title.setText(catTitle);
}
// Load data
//LoadData(catID);
// Menu
View guillotineMenu = LayoutInflater.from(this).inflate(R.layout.menu_layout, null);
root.addView(guillotineMenu);
toolbar_menuImage = (ImageView) toolbar.findViewById(R.id.toolbar_pages_logo);
new GuillotineAnimation.GuillotineBuilder(guillotineMenu, guillotineMenu.findViewById(R.id.menu_layout_image), toolbar_menuImage)
.setStartDelay(RIPPLE_DURATION)
.setActionBarViewForAnimation(toolbar)
.setClosedOnStart(true)
.build();
// RecyclerView
cat_recyclerView.setLayoutManager(mLayoutManager);
cat_recyclerView.setHasFixedSize(true);
// Retrofit //////////
Retrofit_ApiInterface apiInterface = Retrofit_ApiClient.getClient().create(Retrofit_ApiInterface.class);
Call<R_CatModelResponse> call = apiInterface.getCatResponse(catID);
call.enqueue(new Callback<R_CatModelResponse>() {
#Override
public void onResponse(Call<R_CatModelResponse> call, Response<R_CatModelResponse> response) {
List<R_CatModel> models = response.body().getCat_posts();
mAdapter = new CategoryAdapter(context, cat_recyclerView, models);
cat_recyclerView.setAdapter(mAdapter);
Toast.makeText(Category_page.this, "Response", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<R_CatModelResponse> call, Throwable t) {
Toast.makeText(Category_page.this, "Error", Toast.LENGTH_SHORT).show();
}
});
I send category_id with below code from one adapter :
mContext.startActivity(new Intent(v.getContext(), Category_page.class)
.putExtra("categoryTitle", model.getTitle())
.putExtra("categoryID", model.getId()));
and receive this data with below code :
// Receive Data
bundle = getIntent().getExtras();
catID = bundle.getInt("categoryID");
But Error message (Toast) instead of category posts!
show error toast from :
#Override
public void onFailure(Call<R_CatModelResponse> call, Throwable t) {
Toast.makeText(Category_page.this, "Error", Toast.LENGTH_SHORT).show();
}
Update :
This is the error I get, :
E/CatResponseError: Error : com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 48 path $.category
Update #2 :
Added my POJO class :
public class R_CatModelResponse {
#SerializedName("status")
public String Cat_status;
#SerializedName("count")
public int Cat_count;
#SerializedName("pages")
public int Cat_pages;
#SerializedName("category")
public List<Retrofit_ColoniesModel> category;
#SerializedName("posts")
public List<R_CatModel> Cat_posts;
public String getCat_status() {
return Cat_status;
}
public void setCat_status(String cat_status) {
Cat_status = cat_status;
}
public int getCat_count() {
return Cat_count;
}
public void setCat_count(int cat_count) {
Cat_count = cat_count;
}
public int getCat_pages() {
return Cat_pages;
}
public void setCat_pages(int cat_pages) {
Cat_pages = cat_pages;
}
public List<Retrofit_ColoniesModel> getCategory() {
return category;
}
public void setCategory(List<Retrofit_ColoniesModel> category) {
this.category = category;
}
public List<R_CatModel> getCat_posts() {
return Cat_posts;
}
public void setCat_posts(List<R_CatModel> cat_posts) {
Cat_posts = cat_posts;
}
}
How can I fix this?
Please help me. Thanks in advance.
See this pattern which make your life easier:D, based on that use following structure:
Your data model should be:
public class Model {
String status;
int count;
int page;
Category category;
List<Post> posts;
// implement rest of thing
public class Category{
int id;
String slug;
String title;
String description;
int parent;
int post_count;
}
public class Post {
int id;
String type;
String slug;
//..rest of thing
}
}
Your service interface should be:
public interface IService {
#GET("/tafrihgah/?json=get_category_posts")
Call<Model> getCategoryPost(
#Query("id") String id
//...other query if you need should added like below
#Query("categorySlug") String categorySlug,
#Query("tag") String tag,
);
}
And your ServiceHelper contains following method:
public Call<CategoryModel> getAllCategory() {
return service.getCateogryPost();
}
And your error cause your POJO is not fitted to server Model. Double check your Model and make sure Object instead of List/Array;
In your case instead of List<Retrofit_ColoniesModel> category use Retrofit_ColoniesModel category;
I have been able to create an expanded view using the following library: https://github.com/bignerdranch/expandable-recycler-view
Now that I have this, I have created a checkbox in each of my child views. I am able to check and uncheck and expand and retract easy. However the next part is to keep track of all the selections made and put it in an object.
For instance I want the recipe for Tacos that have the ingredients of beef, cheese, lettuce. But I choose to only want the cheese, and lettuce. Now these new selection of ingredients for my Taco I want to hold that as an object.
So what I have done is in my activity I have created a prepare selection method that will be called from my viewholder onClick when a checkbox is selected.
At first I was just trying to get a simple counter and display that just to know that its working. However I get a null pointer error when I click on the checkboxes.
Activity
public class CreateMyTeamActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
private RecyclerView mRecyclerView;
private CustomRecyclerAdapterCreateTeam adapter;
private RecipeAdapter mAdapter;
List<Recipe> recipes = new ArrayList<>();
ArrayList<Integer> selection_list = new ArrayList<>();
int count = 0;
Context context;
private static final String TAG = "MyActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_my_team);
context = this;
mRecyclerView = (RecyclerView) findViewById(R.id.recycleView);
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(linearLayoutManager);
Ingredient beef = new Ingredient("beef");
Ingredient cheese = new Ingredient("cheese");
Ingredient salsa = new Ingredient("salsa");
Ingredient tortilla = new Ingredient("tortilla");
Ingredient ketchup = new Ingredient("ketchup");
Ingredient bun = new Ingredient("bun");
Recipe taco = new Recipe("taco", Arrays.asList(beef, cheese, salsa, tortilla));
Recipe quesadilla = new Recipe("quesadilla", Arrays.asList(cheese, tortilla));
Recipe burger = new Recipe("burger", Arrays.asList(beef, cheese, ketchup, bun));
recipes = Arrays.asList(taco, quesadilla, burger);
mAdapter = new RecipeAdapter(this, recipes);
mAdapter.setExpandCollapseListener(new ExpandableRecyclerAdapter.ExpandCollapseListener() {
#Override
public void onListItemExpanded(int position) {
Recipe expandedRecipe = recipes.get(position);
Toast.makeText(CreateMyTeamActivity.this,
expandedRecipe.getName(),
Toast.LENGTH_SHORT)
.show();
}
#Override
public void onListItemCollapsed(int position) {
Recipe collapsedRecipe = recipes.get(position);
Toast.makeText(CreateMyTeamActivity.this,
"Collapse",
Toast.LENGTH_SHORT)
.show();
}
});
mRecyclerView.setAdapter(mAdapter);
}
-------------Right here is my prepareSelection Method
public void prepareSelection (View view, int position ){
if (((CheckBox)view).isChecked()){
selection_list.add(recipes.indexOf(position));
count = count+1;
Toast.makeText(CreateMyTeamActivity.this,
count,
Toast.LENGTH_SHORT)
.show();
}
}
}
Ingredient View holder
public class IngredientViewHolder extends ChildViewHolder implements View.OnClickListener{
private TextView mIngredientTextView;
private CheckBox button;
CreateMyTeamActivity createMyTeamActivity;
public IngredientViewHolder(View itemView) {
super(itemView);
mIngredientTextView = (TextView) itemView.findViewById(R.id.teamNameChild);
button = (CheckBox)itemView.findViewById(R.id.checkBoxChild);
button.setOnClickListener(this);
}
public void bind(Ingredient ingredient) {
mIngredientTextView.setText(ingredient.getName());
}
#Override
public void onClick(View v) {
Toast.makeText(itemView.getContext(),mIngredientTextView.getText(),Toast.LENGTH_SHORT ).show();
createMyTeamActivity.prepareSelection(v,getAdapterPosition() );
}
}
Ingredient.java
public class Ingredient {
private String mName;
public Ingredient(String name) {
mName = name;
}
public String getName() {
return mName;
}
}