Reputation: 39
I have currently got it so, when the user presses FAB, a cardview is added to the recyclerview. Inside each cardview is a spinner, eddittext, textview and checkbox.
The spinners are populated by items in one column of a csv. When the user selects an item from the spinner, the coressponding number to the item from the other column in the same csv, shows up in the textview in the same cardview.
So then my app looks like this, the numbers being the textviews.
Question I am wondering if it is possible so that when the the user selects an item from the spinner and the number shows up in the textview, if its possible for the cardviews to automatically sort in order of the number in each cardview? So following the picture above, if it were to be ordered it would be like?
Potato Chips - 0
Coffee - 1
Chocolate - 6
Ice Cream - 14
ProductAdapter.java
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {
private Map<Integer, Integer> mSpinnerSelectedItem = new HashMap<Integer, Integer>();
private Map<String, String> numberItemValues = new HashMap<>();
private List<Product> productList;
private Activity create;
//TODO CODE FOR CSV FILE
InputStream inputStream = null;
List<String> mSpinnerItems = null;
CSVFile csvFile = null;
//TODO END OF CODE FOR CSV FILE
public ProductAdapter(Activity activity) {
create = activity;
}
public ProductAdapter(Activity activity, List<Product> productList, Map<String, String> numberList) {
numberItemValues = numberList;
create = activity;
this.productList = productList;
}
@Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//inflating and returning our view holder
LayoutInflater inflater = LayoutInflater.from(create);
View view = inflater.inflate(R.layout.layout_products, null);
return new ProductViewHolder(view);
}
@Override
public void onBindViewHolder(final ProductViewHolder holder, final int position) {
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(create, R.layout.item_spinner_layout,
Product.getSpinnerItemsList());
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.spinner.setAdapter(spinnerArrayAdapter);
holder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int mPosition, long id) {
mSpinnerSelectedItem.put(position, mPosition);
TextView mTextView = view.findViewById(R.id.mSpinnerText);
String currentItem = holder.spinner.getItemAtPosition(mPosition).toString();
Set<String> set = numberItemValues.keySet(); for(String key : set) {String value = numberItemValues.get(key);
Log.e("DATA ", "key = " + key + " value = " + value); }
String aisleNumber = numberItemValues.get(currentItem);
holder.textView5.setText(aisleNumber);
Log.e("SELECTION TEST", " Selected map item = " + aisleNumber );
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//binding the data with the viewholder views
if (mSpinnerSelectedItem.containsKey(position)) {
holder.spinner.setSelection(mSpinnerSelectedItem.get(position));
}
holder.getView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(create);
// set title
alertDialogBuilder.setTitle("Delete Item");
// set dialog message
alertDialogBuilder
.setMessage("Are you sure you want to delete this item?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
// current activity
holder.checkBox.setChecked(false);
holder.spinner.setSelection(0);
productList.remove(holder.getAdapterPosition());
notifyItemRemoved(holder.getAdapterPosition());
Toast.makeText(create, "Item removed.", Toast.LENGTH_LONG).show();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
@Override
public int getItemCount() {
return productList.size();
}
public void reset() {
/* holder.checkBox.setChecked(false);
holder.spinner.setSelection(0);*/
productList.clear();
notifyDataSetChanged();
}
class ProductViewHolder extends RecyclerView.ViewHolder {
SearchableSpinner spinner;
EditText editText;
TextView textView5;
CheckBox checkBox;
LinearLayout linearLayout;
View rootView;
public ProductViewHolder(View itemView) {
super(itemView);
spinner = itemView.findViewById(R.id.spinner);
editText = itemView.findViewById(R.id.editText);
textView5 = itemView.findViewById(R.id.textView5);
checkBox = itemView.findViewById(R.id.checkBox);
rootView = itemView.findViewById(R.id.linearLayout);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// makes the set disappear when checkbox is ticked.
if(isChecked){
checkBox.setChecked(false);
spinner.setSelection(0);
productList.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
Toast.makeText(create, "Done!", Toast.LENGTH_LONG).show();
}
}
});
}
public View getView() {
return rootView;
}
}
//TODO CODE FOR CSV FILE
private class CSVFile {
InputStream inputStream;
public CSVFile(InputStream inputStream) {
this.inputStream = inputStream;
}
public List<String> read() {
List<String> resultList = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] row = line.split(",");
numberItemValues.put(row[1], row[0]);
resultList.add(row[1]);
}
} catch (IOException e) {
Log.e("Main", e.getMessage());
} finally {
try {
inputStream.close();
} catch (IOException e) {
Log.e("Main", e.getMessage());
}
}
return resultList;
}
}
}
create.java which is my main activity code for the screen where cardviews are added etc
public class create extends AppCompatActivity {
//a list to store all the products
List<Product> productList;
//the recyclerview
RecyclerView recyclerView;
Product mProduct;
private Map<String, String> numberItemValues = new HashMap<>();
private Map<Integer, Integer> mSpinnerSelectedItem = new HashMap<Integer, Integer>();
// RelativeLayout relativeLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create);
findViewById(R.id.relativeLayout).requestFocus();
findViewById(R.id.relativeLayout).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
InputMethodManager imm = (InputMethodManager) view.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
});
//opens csv
InputStream inputStream = getResources().openRawResource(R.raw.shopitems);
CSVFile csvFile = new CSVFile(inputStream);
final List<String> mSpinnerItems = csvFile.read();
//getting the recyclerview from xml
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//initializing the productlist
productList = new ArrayList<>();
productList.add(new Product(mSpinnerItems, "Test Edit Text",false, "Text String 2"));
final ProductAdapter adapter = new ProductAdapter(this, productList, numberItemValues);
//TODO FAB BUTTON
FloatingActionButton floatingActionButton =
findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
productList.add(mProduct);
if(adapter != null)
adapter.notifyDataSetChanged();
//Handle the empty adapter here
}
});
//setting adapter to recyclerview
recyclerView.setAdapter(adapter);
}
//TODO OVERFLOW MENU
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_delete) {
((ProductAdapter) recyclerView.getAdapter()).reset();
Toast.makeText(create.this,
"Shopping List Deleted.", Toast.LENGTH_LONG).show();
return true;
}
if (id == R.id.action_help) {
// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Help");
builder.setMessage("Click the button in the bottom right corner to add an item. Touch the dropdown menu and begin typing" +
"the item you want. The aisle number will then show. You are also able to enter in the quantity you want, for your reference." +
"If you made a mistake you can always click the surrounding white box to delete the item. Once you have got the item you" +
"can touch the checkbox. If you want to delete your whole list, press the menu button on your device or the 3 dots in the corner and press" +
"delete.");
// add a button
builder.setPositiveButton("OK", null);
// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();
}
return super.onOptionsItemSelected(item);
}
private class CSVFile {
InputStream inputStream;
public CSVFile(InputStream inputStream) {
this.inputStream = inputStream;
}
public List<String> read() {
List<String> resultList = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] row = line.split(",");
//TODO I edited this part so that you'd add the values in our new hash map variable
numberItemValues.put(row[1], row[0]);
resultList.add(row[1]);
}
} catch (IOException e) {
Log.e("Main", e.getMessage());
} finally {
try {
inputStream.close();
} catch (IOException e) {
Log.e("Main", e.getMessage());
}
}
return resultList;
}
}
}
Upvotes: 0
Views: 270
Reputation: 2937
Subscribe to the spinner selection event. When it triggers, you have to reach your collection of data and sort it, after that just notify the adapter adapter.notifyDataSetChanged()
Are you using recyclerview or ?
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view,
int position, long id) {
adapter.sortDataSet();
});
In you adapter:
public void sortDataSet(){
//sort dataSet (arrayList, etc)
notifyDataSetChanged();
}
Sorting the data is easy. There are plenty of different methods, in one you have to override class methods, in other you have to create additional object or include contract for you class. You can find a lot of examples here : h
If you use java8 i would suggest something like that : list.sort((a, b) -> a.field > b.field);
class Product implements Comparable<Product> {
@Override
public int compareTo(Product other) {
return Integer.compare(this.IntField, other.IntField);
}
}
Upvotes: 2