Multi-selection expanded recyclerview listview keep track of selection - android

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

Related

New user is part of a group it was never added to

I'm currently working on an app in which users can create groups and add members to groups. Today I created a new user to test the app. When I logged in this new user I checked to see if it was a part of any groups, which I didn't expect it to be seeing as it was new. And it wasn't. But then when I logged in my usual user and clicked groups I saw the name of the test user. Why does it appear that this user is a part of a group it was never added to?
It should be noted that when looking through my firebase this test user doesn't appear to have been invited either. I'm using firestore recycler adapter to fetch data in a recyclerView.
Below is the code for my adapter responsible for adding members to a specific group.
FirestoreMemberAdapter.java:
public class FirestoreMemberAdapter extends FirestoreRecyclerAdapter<MemberModel, FirestoreMemberAdapter.MemberViewHolder> {
private static final String TAG = FirestoreMemberAdapter.class.getSimpleName();
private Context context;
private String projectId;
private String projectName;
public FirestoreMemberAdapter(#NonNull FirestoreRecyclerOptions<MemberModel> options, Context context, String projectId, String projectName) {
super(options);
this.context = context;
this.projectName = projectName;
this.projectId = projectId;
}
#Override
protected void onBindViewHolder(#NonNull MemberViewHolder holder, int position, #NonNull final MemberModel model) {
holder.mTextView.setText(model.getName());
if (model.getProfile_image() == null) {
Picasso.get().load(R.drawable.profile_image).into(holder.mImageview);
} else {
Picasso.get().load(model.getProfile_image()).into(holder.mImageview);
}
holder.mLinearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: Clicked on FirestoreMemberAdapter ");
Intent intent = new Intent(context, ProfileMemberPage.class);
intent.putExtra(StringCreator.PROJECT_TITLE, projectName);
intent.putExtra(StringCreator.PROJECT_ID, projectId);
intent.putExtra(StringCreator.NAME, model.getName());
intent.putExtra(StringCreator.EMAIL, model.getEmail());
intent.putExtra(StringCreator.USER_ID, model.getUser_id());
intent.putExtra(StringCreator.USER_INFORMATION, model.getUser_information());
context.startActivity(intent);
}
});
}
#NonNull
#Override
public MemberViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_projectmembers, parent, false);
return new MemberViewHolder(view);
}
public class MemberViewHolder extends RecyclerView.ViewHolder {
private LinearLayout mLinearLayout;
private TextView mTextView;
private ImageView mImageview;
public MemberViewHolder(#NonNull View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.memberTitle);
mLinearLayout = itemView.findViewById(R.id.layout_members);
mImageview = itemView.findViewById(R.id.memberImage);
}
}
}
Here is the activity in wihch the adapter is used.
projectClicked.java:
//widgets
private RecyclerView recyclerViewMembers;
private TextView projectName;
private Button cameraBtn;
private FloatingActionButton addUserBtn;
//Firebase
private FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
private Query query;
private FirestoreRecyclerOptions<MemberModel> options;
private FirestoreMemberAdapter adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_project_clicked);
projectName = findViewById(R.id.projectName);
addUserBtn = findViewById(R.id.addUserBtn);
cameraBtn = findViewById(R.id.cameraBtn);
initRecyclerView();
addUserBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent newIntent = new Intent(projectClicked.this, UserToProject.class);
Bundle projectBundle = getIntent().getExtras();
if (projectBundle != null) {
newIntent.putExtras(projectBundle);
}
startActivity(newIntent);
}
});
}
private void initRecyclerView() {
Log.d(TAG, "InitRecyclerView: init recyclerview");
if (getIntent().hasExtra(StringCreator.PROJECT_TITLE) && getIntent().hasExtra(StringCreator.PROJECT_ID)) {
final String pName = getIntent().getStringExtra(StringCreator.PROJECT_TITLE);
final String pID = getIntent().getStringExtra(StringCreator.PROJECT_ID);
projectName.setText(pName);
recyclerViewMembers = findViewById(R.id.recyclerView_members);
query = firebaseFirestore.collection("users");
options = new FirestoreRecyclerOptions.Builder<MemberModel>().setQuery(query, MemberModel.class).build();
adapter = new FirestoreMemberAdapter(options, projectClicked.this, pID, pName);
recyclerViewMembers.setHasFixedSize(true);
recyclerViewMembers.setAdapter(adapter);
recyclerViewMembers.setLayoutManager(new LinearLayoutManager(projectClicked.this));
}
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
Hope this makes sense, please reach out if it doesn't. Thank you in advance.
As #McSlinPlay mentioned, the reason could be pointed out to your code in projectClicked.java where you created your query and all the users (including the test user) are part of this collection:
query = firebaseFirestore.collection("users");

View Model loading previously searched data(through retrofit call) instead of newly searched

I am bit confused how I can send the new query to retrofit call through the view model.
My Activity is as follows:
public class SearchActivity extends AppCompatActivity {
RecyclerViewAdapter adapter;
Button filter_button;
RecyclerView recyclerView;
EditText currentSearch;
ImageButton imageButton;
List<Hits> mHits = new ArrayList<>();
String category;
String order;
String query;
String editor_choice;
String type;
ViewModel model;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
filter_button = findViewById(R.id.button_filter);
imageButton = findViewById(R.id.imageButton_search);
currentSearch = findViewById(R.id.et_currentsearch);
recyclerView = findViewById(R.id.recyclerview);
// getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_arrow_back_black_24dp);
final Intent intent = getIntent();
category = intent.getStringExtra("category");
order = intent.getStringExtra("order");
query = intent.getStringExtra("searchQuery");
editor_choice = intent.getStringExtra("editor");
type = intent.getStringExtra("type");
currentSearch.setText(query);
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
recyclerView.setHasFixedSize(true);
adapter = new RecyclerViewAdapter(this, mHits);
recyclerView.setAdapter(adapter);
model = ViewModelProviders.of(this, new MyViewModelFactory(this.getApplication()
, category, type, editor_choice, order, query)).get(ViewModel.class);
model.getList().observe(this, new Observer<List<Hits>>() {
#Override
public void onChanged(List<Hits> hits) {
adapter = new RecyclerViewAdapter(SearchActivity.this, hits);
recyclerView.setAdapter(adapter);
}
});
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
newSearch();
}
});
filter_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(SearchActivity.this, MainActivity.class);
intent1.putExtra("query", currentSearch.getText().toString().trim());
startActivity(intent1);
}
});
}
This is the method i am using :
void newSearch() {
String newSearch = currentSearch.getText().toString();
Log.d("___", "new Search : " + newSearch);
ViewModel model1 = ViewModelProviders.of(this, new MyViewModelFactory(this.getApplication()
, category, "photo", "false", "popular", newSearch)).get(ViewModel.class);
model1.getList().observe(this, new Observer<List<Hits>>() {
#Override
public void onChanged(List<Hits> hits) {
adapter = new RecyclerViewAdapter(SearchActivity.this, hits);
recyclerView.setAdapter(adapter);
}
});
}
}
The newSearch in Log is showing the required query but the recyler view is still showing the previously fetched.
My ViewModelFactory Class :
public class MyViewModelFactory extends
ViewModelProvider.AndroidViewModelFactory {
private Application context;
private String category;
private String image_type;
private String editor_choice;
private String orderBy;
private String query;
public MyViewModelFactory(#NonNull Application application,String category, String image_type,
String editor, String orderBy, String query) {
super(application);
this.category = category;
this.image_type = image_type;
this.editor_choice = editor;
this.orderBy = orderBy;
this.query = query;
this.context=application;
}
#NonNull
#Override
public <T extends ViewModel> T create(#NonNull Class<T> modelClass) {
return (T) new com.example.picsearch.ViewModel(context,category,image_type
,editor_choice,orderBy,query);
}
}
I am new in programming please tell me how I can use the currentSearch text as query for the new Retrofit call.

How to view RecyclerView items sorted by ID?

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

Attaching a spinner widget to recycler view(Android)

I want to add multiple spinners to my recycler view, I am using parse as my backend, I have created one but this doesn't give me expected results.And I also have no idea how to do onclick if my items get listed inside a spinner Below Is My code
public class Online3 extends AppCompatActivity {
List<String> categories1, categories2, categories3, categories4, categories13, categories12, categories5, categories6;
String objectId;
private List<Array_G_S> list = new ArrayList<>();
RecyclerView recyclerView;
ArrayAdap adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_online3);
Intent intent = getIntent();
objectId = intent.getStringExtra("objId");
String txt = intent.getStringExtra("imageText");
if (objectId != null) {
Log.i("sand", objectId);
} else {
Log.i("sand", txt);
}
new RemoteTask().execute();
}
private class RemoteTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
ParseQuery<ParseObject> query = new ParseQuery<>("OnlineShopping");
query.whereEqualTo("objectId", objectId);
List<ParseObject> object1 = null;
try {
object1 = query.find();
for (final ParseObject country : object1) {
if (country != null) {
ParseRelation<ParseObject> p = country.getRelation("arrayRelation");
ParseQuery p2 = p.getQuery();
List<ParseObject> oc = p2.find();
for (ParseObject country2 : oc) {
if (country2 != null) {
categories1 = country2.getList("eType");
Array_G_S gs = new Array_G_S();
gs.setStringList(categories1);
list.add(gs);
}
}
}
// Locate images in flag column
}
} catch (com.parse.ParseException e1) {
e1.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
recyclerView = (RecyclerView) findViewById(R.id.arrayRecy);
recyclerView.setNestedScrollingEnabled(false); // Smooth Scrolling
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
adapter = new ArrayAdap(getApplicationContext(), list);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
}
}
Below is my Adapter Class
public class ArrayAdap extends RecyclerView.Adapter<ArrayAdap.MyViewHolder> {
private Context context;
private List<Array_G_S> list = null;
ArrayAdapter<Array_G_S> dataAdapter;
public ArrayAdap(Context context, List<Array_G_S> list) {
this.context = context;
this.list = list;
}
#Override
public ArrayAdap.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.spinner, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(ArrayAdap.MyViewHolder holder, int position) {
Array_G_S gs = list.get(position);
dataAdapter = new ArrayAdapter<String>(context,android.R.layout.simple_spinner_item,gs.getStringList());
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.spinner.setAdapter(dataAdapter);
}
#Override
public int getItemCount() {
return list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
Spinner spinner;
public MyViewHolder(View v) {
super(v);
spinner = (Spinner) v.findViewById(R.id.spin);
}
}
And this is the screenshot of what I am getting
EDIT
I have edited my code above
Ok i have solved this issue by putting Getter_Setter list directly to adapter .
Now my issue is how to solve Onclick on selected items
EDIT
This is only creating a single spinner, i need multiple spinner ie acccording to my list

Sort RecyclerView

I'm using recyclerview to show my list of ground machines. Also I have a check box widget. When check box is checked, I want to sort my list by brand of machine. In my adapter I have a method setMachine(List listMachines); which has a reference to my current list of machines. Also my sort method works fine, but when I checked my check box my list is not sorted, worst it's disappeared, and my current list of machines is zero. Can someone help me to understand why that is happening:
My RecyclerView Adapter:
public class ListMachineAdapter extends RecyclerView.Adapter<ListMachineAdapter.ViewHolder> {
private List<Machine> listOfMachines;
private ClickMachineItemListener selectMachine;
private View.OnClickListener showToast = new View.OnClickListener() {
#Override
public void onClick(View v) {
ViewHolder vh = (ViewHolder) v.getTag();
int position = vh.getItemPosition();
selectMachine.onClick(position);
}
};
public ListMachineAdapter(List<Machine> listOfMachines) {
this.listOfMachines = listOfMachines;
}
#Override
public ListMachineAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_list_machine, parent, false);
view.setOnClickListener(showToast);
return new ViewHolder(view, viewType);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Machine machine = listOfMachines.get(position);
holder.setPosition(position);
holder.brandMachine.setText(machine.getTypeBrand());
holder.typeMachine.setText(machine.getTypeMachine());
}
#Override
public int getItemCount() {
return listOfMachines.size();
}
public void setMachine(List<Machine> listMachines){
this.listOfMachines = listMachines; // size = 0 ??
}
public void setSelectMachine(ClickMachineItemListener selectMachine){
this.selectMachine = selectMachine;
}
Also I using Singleton to store my sort method:
public class MachineManager {
private static MachineManager instance;
private List<Machine> listOfGroundMachines;
private MachineManager() {
listOfGroundMachines = new ArrayList<>();
}
public static MachineManager getInstance() {
return instance = (instance == null) ? new MachineManager() : instance;
}
public List<Machine> sortByTypeBrand() {
Collections.sort(listOfGroundMachines, new Comparator<Machine>() {
#Override
public int compare(Machine lhs, Machine rhs) {
return lhs.getTypeBrand().compareToIgnoreCase(rhs.getTypeBrand());
}
});
return listOfGroundMachines;
}
}
And this is my Activity:
public class ListGroundMachineActivity extends Activity {
private CheckBox sortByTypeMachine, sortByTypeEngine, sortByTypeBrand, sortByYear;
private List<Machine> listOfGroundMachines;
private ListMachineAdapter adapter;
private MachineManager manager;
private ClickMachineItemListener click = new ClickMachineItemListener() {
#Override
public void onClick(int position) {
Machine machine = listOfGroundMachines.get(position);
Intent intent = new Intent(ListGroundMachineActivity.this, MachineDetailsActivity.class);
intent.putExtra(Constants.TYPE, machine.getTypeMachine());
intent.putExtra(Constants.BRAND, machine.getTypeBrand());
intent.putExtra(Constants.YEAR, machine.getYear());
intent.putExtra(Constants.ENGINE, machine.getTypeEngine());
Toast.makeText(ListGroundMachineActivity.this, machine.getTypeBrand(), Toast.LENGTH_SHORT).show();
startActivity(intent);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_ground_machine);
manager = MachineManager.getInstance();
listOfGroundMachines = populateGroundListMachine();
Log.i("TAG", "List size is " + listOfGroundMachines.size());
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.list_ground_machine);
adapter = new ListMachineAdapter(listOfGroundMachines);
sortByTypeMachine = (CheckBox) findViewById(R.id.sort_by_type_ground_machine);
adapter.setSelectMachine(click);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this)
.color(R.color.teal).build());
recyclerView.setAdapter(adapter);
sortByTypeMachine.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
adapter.setMachine(manager.sortByTypeBrand());
adapter.notifyDataSetChanged();
Log.i("TAG 1", "List size is " + manager.sortByTypeBrand());
}
});
}
private List<Machine> populateGroundListMachine() {
List<Machine> listOfGroundMachineOne = new ArrayList<>();
MachineDB machineDb = new MachineDB(this);
SQLiteDatabase sqLiteDatabase = machineDb.getReadableDatabase();
Cursor cursor = sqLiteDatabase.query(MachineDB.TABLE_GROUND_MACHINE, null, null, null, null, null, null);
while (cursor.moveToNext()) {
String typeBrand = cursor.getString(cursor.getColumnIndex(Constants.BRAND));
String typeMachine = cursor.getString(cursor.getColumnIndex(Constants.TYPE));
String typeEngine = cursor.getString(cursor.getColumnIndex(Constants.ENGINE));
String year = cursor.getString(cursor.getColumnIndex(Constants.YEAR));
Machine machine = new Machine(typeBrand, typeMachine, typeEngine, year);
listOfGroundMachineOne.add(machine);
}
sqLiteDatabase.close();
return listOfGroundMachineOne;
}
Your listOfGroundMachines in MachineManager is only an empty arraylist:
private MachineManager() {
listOfGroundMachines = new ArrayList<>();
}
You need to create setter for that and call the setter after this code:
manager = MachineManager.getInstance();
listOfGroundMachines = populateGroundListMachine();
// here
The MachineManager listOfGroundMachines is an empty list.
You call listOfGroundMachines = populateGroundListMachine(); in your Activity class.
The list being populated with the machines is a member of ListGroundMachineActivity and not of MachineManager.

Categories

Resources