How to filter firebase recycler view? - android

I have an android app linked with my firestore database. I am fetching data from the firestore and displaying the results in a recycler view with the help of firebaseRecyclerView. My app is working perfectly and I'm able to display all the results in my recycler view.
Now I want to add the feature of filtering the already fetched data using a spinner. i.e the user first sees all the results, then uses the spinner to display only the relevant data.
I'm able to manage the case when there are no results from the firestore/recycler view that is empty.
To filter, I think I may have to use the onItemSelected function of the spinner, however, I don't know how I should proceed.
To filter I would be basically comparing two strings.
One from the text selected from the spinner , and one from each Textview of the row of recyclerview.
Please let me know how I should proceed.
Here is my onCreate method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_query);
filter_price_text = findViewById(R.id.filter_price_text);
recyclerView = findViewById(R.id.recyclerView_tProfile);
emptyView = findViewById(R.id.empty_view);
query = db
.collection("tUsers")
.whereEqualTo(testArray[0], true)
.whereEqualTo(testArray[1], true)
.whereEqualTo("pincode", customerPincode)
.whereEqualTo("sector", customerSector); //query is working . ignore what I'm querying for. I have removed unimportant data from onCreate
FirestoreRecyclerOptions<TProfileModel> options = new FirestoreRecyclerOptions.Builder<TProfileModel>().setQuery(query, TProfileModel.class).build();
adapter = new FirestoreRecyclerAdapter<TProfileModel, profileViewHolder>(options) {
#NonNull
#Override
public profileViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.t_profile_row, parent, false);
return new profileViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull profileViewHolder holder, int position, #NonNull final TProfileModel model) { //final added manually to test should remove
holder.t_name.setText(model.getName());
String tsector = "Sector : " + model.getSector();
holder.t_sector.setText(tsector);
String tpin = "Pincode : " + model.getPincode();
holder.t_pincode.setText(tpin);
String trating = "Rating : " + model.getRating();
holder.t_rating.setText(trating);
String tprice = "Avg. Price : " + model.getAvgPriceRange();
holder.t_price.setText(tprice);
ta_price = model.getAvgPriceRange();//will be used for comparing with spinner data
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainQueryActivity.this, ViewTActivity.class);
intent.putExtra("name", model.getName());
intent.putExtra("sector", model.getSector());
intent.putExtra("pincode", model.getPincode());
startActivity(intent);
}
});
}
#Override
public void onDataChanged() {
emptyView.setVisibility(getItemCount() == 0 ? View.VISIBLE : View.GONE);
priceFilter.setVisibility(getItemCount() == 0 ? View.GONE : View.VISIBLE);
filter_price_text.setVisibility(getItemCount() == 0 ? View.GONE : View.VISIBLE);
}
#Override
public void onError(FirebaseFirestoreException e) {
// Called when there is an error getting a query snapshot. You may want to update
// your UI to display an error message to the user.
// ...
}
};
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
priceFilter = findViewById(R.id.priceFilter_spinner);
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(this, R.array.t_price_spin, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
priceFilter.setAdapter(adapter1);
final String spinner_price = priceFilter.getSelectedItem().toString().trim();
priceFilter.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//compare ta_price with spinner_price
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}

Related

Show only certain items in recycleview according to condition

I have a recycleview showing a list of audio files fetched from my audios.json file hosted on my server. i have a model class with a getter method getLanguage() to see the audio language. I would like to show only audio files of users preference in recycle view. Say for example, if user wants only english and russian i would like to show only list of russian and english. How can we achieve this? Right now the entire list is displayed.
public class AudioAdapter extends RecyclerView.Adapter<AudioAdapter.HomeDataHolder> {
int currentPlayingPosition = -1;
Context context;
ItemClickListener itemClickListener;
List<Output> wikiList;
public AudioAdapter(List<Output> wikiList, Context context) {
this.wikiList = wikiList;
this.context = context;
}
#NonNull
#Override
public HomeDataHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.audio_row_layout,viewGroup,false);
HomeDataHolder mh = new HomeDataHolder(view);
return mh;
}
#Override
public void onBindViewHolder(#NonNull final HomeDataHolder homeDataHolder, int i) {
String desc = wikiList.get(i).getLanguage() + " • " + wikiList.get(i).getType();
homeDataHolder.tvTitle.setText(wikiList.get(i).getTitle());
homeDataHolder.tvotherinfo.setText(desc);
homeDataHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (itemClickListener != null)
itemClickListener.onClick(view,homeDataHolder.getAdapterPosition());
}
});
homeDataHolder.rippleLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (itemClickListener != null)
itemClickListener.onClick(view,homeDataHolder.getAdapterPosition());
}
});
}
#Override
public int getItemCount() {
return wikiList.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public void setClickListener(ItemClickListener itemClickListener) { // Method for setting clicklistner interface
this.itemClickListener = itemClickListener;
}
public class HomeDataHolder extends RecyclerView.ViewHolder {
TextView tvTitle,tvotherinfo;
MaterialRippleLayout rippleLayout;
public HomeDataHolder(View v) {
super(v);
this.tvTitle = v.findViewById(R.id.title);
this.tvotherinfo = v.findViewById(R.id.audioDesc);
this.rippleLayout = v.findViewById(R.id.ripple);
}
}
}
The general idea for this should be:
you have one list with all items
you have filter rules selected by the user
You filter items from number 1, to see which ones match the constraints and store this in another list.
Then the recycler view only shows the items of the list from number 3.
This means that recycler view's getItemCount would return the size of the filtered list, not the whole list.
Instead of passing the wikiList as it is, filter it then send it:
Lets say that you filled up the wikiList, before passing it to the adapter, filter it like this:
In the activity that you initialize the adapter in:
public class YourActivity extends ............{
........
........
//your filled list
private List<Output> wikiList;
//filtered list
private List<Output> filteredList= new ArrayList<Output>();
//filters
private List<String> filters = new ArrayList<String>();
//lets say the user chooses the languages "english" and "russian" after a button click or anything (you can add as many as you want)
filters.add("english");
filters.add("russian");
//now filter the original list
for(int i = 0 ; i<wikiList.size() ; i++){
Output item = wikiList.get(i);
if(filters.contains(item.getLanguage())){
filteredList.add(item);
}
}
//now create your adapter and pass the filteredList instead of the wikiList
AudioAdapter adapter = new AudioAdapter(filteredList , this);
//set the adapter to your recyclerview........
......
.....
......
}
I use above "english" and "russian" for language. I don't know how they are set in your response, maybe you use "en" for "english" so be careful.

Changing Spinner list content after item is selected Android

Is there a way to change the displayed list inside of the Spinner after selection. I have 2 Strings, English and Finnish and I want to first change their language when one is selected, secondly change their order when the other is selected.
private void initLanguageSpinner() {
List<String> spinnerLocale = new ArrayList<>();
if ((currentdocumentLocale.toString().startsWith("deviceNameFi") || currentdocumentLocale.getLanguage().equals("fi"))) {
spinnerLocale.add(getLocalizedResources(context, currentdocumentLocale).getString(R.string.finnish_language));
spinnerLocale.add(getLocalizedResources(context, currentdocumentLocale).getString(R.string.english_language));
} else {
spinnerLocale.add(getLocalizedResources(context, currentdocumentLocale).getString(R.string.english_language));
spinnerLocale.add(getLocalizedResources(context, currentdocumentLocale).getString(R.string.finnish_language));
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), R.layout.document_spinner_item, spinnerLocale);
adapter.setDropDownViewResource(R.layout.document_spinner_dropdown_item);
customerSelectedLanguageSpinner.setAdapter(adapter);
customerSelectedLanguageSpinner.setSelection(0, false);
customerSelectedLanguageSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (customerSelectedLanguageSpinner.getSelectedItem().toString().equals(getLocalizedResources(context, currentdocumentLocale).getString(R.string.finnish_language))) {
onLocaleChangedFi();
initLanguageSpinner();
} else if (customerSelectedLanguageSpinner.getSelectedItem().toString().equals(getLocalizedResources(context, currentdocumentLocale).getString(R.string.english_language))) {
onLocaleChangedEng();
initLanguageSpinner();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
By doing this it basically does what I need, but it also goes into an endless loop since the onItemSelected is always called after initialization, even when I do the .setSelection(0, false). Is there a way to do what I need?
EDIT
So I tried creating a new adapter and then notifying it of changes.
private ArrayAdapter<String> spinnerAdapter;
private void initLanguageSpinner() {
List<String> spinnerLocale = new ArrayList<>();
if ((currentdocumentLocale.toString().startsWith("deviceNameFi") || currentdocumentLocale.getLanguage().equals("fi"))) {
spinnerLocale.add(getLocalizedResources(context, currentdocumentLocale).getString(R.string.finnish_language));
spinnerLocale.add(getLocalizedResources(context, currentdocumentLocale).getString(R.string.english_language));
} else {
spinnerLocale.add(getLocalizedResources(context, currentdocumentLocale).getString(R.string.english_language));
spinnerLocale.add(getLocalizedResources(context, currentdocumentLocale).getString(R.string.finnish_language));
}
spinnerAdapter = new ArrayAdapter<>(getActivity(), R.layout.document_spinner_item, spinnerLocale);
spinnerAdapter.setDropDownViewResource(R.layout.document_spinner_dropdown_item);
customerSelectedLanguageSpinner.setAdapter(spinnerAdapter);
customerSelectedLanguageSpinner.setSelection(0, false);
customerSelectedLanguageSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (customerSelectedLanguageSpinner.getSelectedItem().toString().equals(getLocalizedResources(context, currentdocumentLocale).getString(R.string.finnish_language))) {
setSpinnerAdapter(customerSelectedLanguageSpinner.getSelectedItem().toString());
onLocaleChangedFi();
} else if (customerSelectedLanguageSpinner.getSelectedItem().toString().equals(getLocalizedResources(context, currentdocumentLocale).getString(R.string.english_language))) {
setSpinnerAdapter(customerSelectedLanguageSpinner.getSelectedItem().toString());
onLocaleChangedEng();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void setSpinnerAdapter(String language){
if(language.equals("fi")){
String[] myListFinnish = new String[] { getLocalizedResources(context, currentdocumentLocale).getString(R.string.finnish_language), getLocalizedResources(context, currentdocumentLocale).getString(R.string.english_language)};
spinnerAdapter = new ArrayAdapter<>(getActivity(), R.layout.document_spinner_item, myListFinnish);
} else {
String[] myListEnglish = new String[] { getLocalizedResources(context, currentdocumentLocale).getString(R.string.english_language), getLocalizedResources(context, currentDocumentLocale).getString(R.string.finnish_language)};
spinnerAdapter = new ArrayAdapter<>(getActivity(), R.layout.document_spinner_item, myListEnglish);
}
spinnerAdapter.setDropDownViewResource(R.layout.document_spinner_dropdown_item);
spinnerAdapter.notifyDataSetChanged();
}
This way it does not even change the list strings or order. onLocaleChangedEng(); basically changes the Locale variable in the application.
your code is a dead loop. and if the adapter item data changed,
such as add, remove, clear by adapter you can use notifyDataSetChanged
method.
Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.
adapter.clear()/add(object)/addAll();
adapter.notifyDataSetChanged();
then the view will update but not init.
if the whole data changed, you can also recreate an adapter, and then set data
dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, newStringList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCategory.setAdapter(dataAdapter)
At the same time, you can also clear and addAll, then notifyDataSetChanged
adapter.clear() //remove all data;
adapter.addAll(source);
adapter.notifyDataSetChanged();
//or remove it, then insert it in the first. that is acturl for your conditon
adapter.remove(objcet) //remove special data;
adapter.insert(object,index);
adapter.notifyDataSetChanged();
Secondly, you can also set a Tag to make when init the onItemSelected not called. the code like this:
//define a tag when first it is 0
int check = 0;
//then in the onItemSelected add a check condition
public void onItemSelected(AdapterView<?> parent, View arg1, int pos,long id) {
if(++check> 1) {
//do some things when item selected.
}
}
use notifyDataSetChanged to update data, not every time init spinner. if you only want to remove the init selected effect, use the check tag.

FirestoreRecyclerAdapter - how do I know when data has been retrieved?

I'm retrieving data using a FirestoreRecyclerAdapter, and, on completion, I need to check whether any items have been retrieved or not. I can't figure out how to do this.
I'm calling it from a class called FragmentChartsList, shown below. This should set up the adapter initially, with "name" as the value for mOrder. Later, the Activity which contains this Fragment can call setOrderField() with a different value of mOrder, which the user has selected from a Spinner.
Each time setOrderField() is called, a new adapter instance is created and attached to the recyclerView. At this point I need to check whether the new version of the adapter contains any data, and either show a "no Charts found" message, or show the Charts which were retrieved (obviously if the list is just being sorted, then the number of items remains the same, but I'm going to be expanding this to allow the user to filter the Charts by different criteria, so the number of Charts returned will change).
Currently, setOrderField() calls refreshViewOnNewData(), which should find out how many Charts are being shown; if it's 0, it should show the "no Charts found" message, and if it's >0 it should show the RecyclerView containing the Charts.
At the moment, I'm always getting a value of 0 when I try to count the Charts. I suspect it's because the adapter hasn't finished retrieving them from the database yet, but I can't find anything that allows me to add some kind of "onComplete" listener so that I know it's finished.
Can anyone suggest how I can achieve this?
public abstract class FragmentChartsList extends Fragment {
private FirebaseFirestore mDatabaseRef;
private ChartListAdapter mAdapter;
private Query mChartsQuery;
private RecyclerView mRecycler;
private String mOrder = "name";
private TextView mLoadingList, mEmptyList;
public FragmentChartsList() {}
#Override
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(
R.layout.fragment_charts_list, container, false);
mRecycler = rootView.findViewById(R.id.charts_list);
mRecycler.setHasFixedSize(true);
mLoadingList = rootView.findViewById(R.id.loading_list);
mEmptyList = rootView.findViewById(R.id.empty_list);
// Set up Layout Manager, and set Recycler View to use it
LinearLayoutManager mManager = new LinearLayoutManager(getActivity());
mManager.setReverseLayout(true);
mManager.setStackFromEnd(true);
mRecycler.setLayoutManager(mManager);
// Connect to the database
mDatabaseRef = FirebaseFirestore.getInstance();
setOrderField(mOrder); // Initialised to "name"
return rootView;
}
#Override
public void onStart() {
super.onStart();
mAdapter.startListening();
}
#Override
public void onStop() {
super.onStop();
mAdapter.stopListening();
}
#Override
public void onDestroy() {
super.onDestroy();
mAdapter.stopListening();
}
// HELPER FUNCTIONS
public void setOrderField(String order) {
mOrder = order;
mChartsQuery = getQuery(mDatabaseRef, mOrder);
// Update recycler options
FirestoreRecyclerOptions<Chart> recyclerOptions = new FirestoreRecyclerOptions.Builder<Chart>()
.setQuery(mChartsQuery, Chart.class)
.build();
mAdapter = new ChartListAdapter(recyclerOptions, getActivity());
mAdapter.startListening();
mRecycler.swapAdapter(mAdapter, true);
refreshViewOnNewData();
}
private void refreshViewOnNewData() {
// Hide "loading" text
mLoadingList.setVisibility(View.GONE);
// Check number of charts being shown
//if (mAdapter != null && (mAdapter.getCount() > 0)) {
// If > 0, show Charts
mEmptyList.setVisibility(View.GONE);
mRecycler.setVisibility(View.VISIBLE);
} else {
// If number of Charts = 0
// show "no charts"
mEmptyList.setVisibility(View.VISIBLE);
mRecycler.setVisibility(View.GONE);
}
}
}
The adapter class looks like this:
public class ChartListAdapter extends FirestoreRecyclerAdapter<Chart, ChartViewHolder> {
private Activity mActivity;
private int mCount;
public ChartListAdapter(FirestoreRecyclerOptions<Chart> recyclerOptions, Activity activity) {
super(recyclerOptions);
mActivity = activity;
}
#Override
protected void onBindViewHolder(#NonNull ChartViewHolder holder, int position, #NonNull Chart model) {
final String chartKey = this.getSnapshots().getSnapshot(position).getId();
model.setKey(chartKey);
// Set click listener for the chart
// On click, the user can view the chart
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mActivity, ActivityViewChart.class);
intent.putExtra("ChartKey", chartKey);
mActivity.startActivity(intent);
}
});
// Implement long-click menu
mActivity.registerForContextMenu(holder.itemView);
// Bind Chart to ViewHolder
holder.bindToChart(model);
}
#NonNull
#Override
public ChartViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_chart, parent, false);
return new ChartViewHolder(view);
}
#Override
public void onDataChanged() {
super.onDataChanged();
mCount = getItemCount();
}
public int getCount() {
return mCount;
}
}
Figured this out... I needed to set a listener on the query instead.
So, instead of having the call to refreshViewOnNewData from setOrder above, I now have:
mChartsQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException e) {
if (queryDocumentSnapshots != null) {
mLoadingList.setVisibility(View.GONE);
if(queryDocumentSnapshots.size() > 0) {
mEmptyList.setVisibility(View.GONE);
mRecycler.setVisibility(View.VISIBLE);
}else {
mEmptyList.setVisibility(View.VISIBLE);
mRecycler.setVisibility(View.GONE);
}
}
}
});
}
Also removed mCount from the adapter class, along with getCount and onDataChanged

RecyclerView + FirebaseRecyclerAdapter + Spinner Filter in activity

I have a recyclerview with FirebaseRecyclerAdapter and a spinner.
It show in activity a list of objects retrieve of firabase database.
My question is: Which better way for using filters in recycler view when user select a value in spinner? When selected a value in spinner below, nothing happens... Not update RecyclerView
exemple: When user select 'Brazil' in spinner, call a existent query like
query = databaseReference.child("People").orderByChild("country").equalTo("Brazil").getRef(); //I still dont know if this working.
query = databaseReference.child("People").getRef();
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
spinnerFilter = (Spinner) findViewById(R.id.spinFilter);
//--SPINNER EVENT SELECT--
AdapterView.OnItemSelectedListener selectedListener = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> spinner, View container, int position, long id)
{
if(id == 0)
{
query = databaseReference.child("PeopleList").orderByChild("country").equalTo("Canada").getRef();
}else
if(id == 1)
{
query = databaseReference.child("PeopleList").orderByChild("country").equalTo("Brazil").getRef();
}else
if(id == 2)
{
query = databaseReference.child("PeopleList").orderByChild("country").equalTo("EUA").getRef();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
query = databaseReference.child("PeopleList").getRef();
}
};
spinnerFilter.setOnItemSelectedListener(selectedListener);
//---RECYCLER VIEW----
if (mRecyclerView != null) {
mRecyclerView.setHasFixedSize(true);
}
gLayoutManager= new GridLayoutManager(this, 2);
mRecyclerView.setLayoutManager(gLayoutManager);
FirebaseRecyclerAdapter<People, PeopleListViewHolder> adapter = new FirebaseRecyclerAdapter<People, PeopleListViewHolder>
(
People.class,
R.layout.layout_people_item,
PeopleListViewHolder.class,
query
)
{
#Override
protected void populateViewHolder(PeopleListViewHolder viewHolder, People model, int position)
{
viewHolder.tvName.setText(model.getName());
Picasso.with(PeopleListActivity.this).load(model.getUrlThumbnail()).into(viewHolder.thumbnail);
}
};
mRecyclerView.setAdapter(adapter);
I check a lot links here but none success:
https://stackoverflow.com/questions/39076702/filtering-data-before-populating-view-from-firebaserecycleradapter?rq=1
https://github.com/firebase/FirebaseUI-Android/issues/15
https://groups.google.com/forum/#!topic/firebase-talk/O1kJ4VLUg10
https://github.com/firebase/FirebaseUI-Android/issues/15
Thanks very much if can help me.

How to access listview items generated by arrayadapter

I have tied my application to Firebase database and after being able to display them I also want to be able to select them and access their textview values. However .getValue() does not work for views. I know that my code is very messy and my selector is only working one way, but can you help me to find out what is going on. I will add a screenshot to make things more clear. At the moment when clicking on one of the items int num = Integer.parseInt(text) gives an error and the app will crash because the value I get from view is "Android.widget...", not what I want to get.
Screenshot pic:
Orders.java
public class Orders extends ActionBarActivity {
public final static String TOTAL_SUM = "com.nordscript.checkmate.SUM";
// Declare the UI components
private ListView foodList;
// Declare an ArrayAdapter that we use to join the data set and the ListView
// is the way of type safe, means you only can pass Strings to this array
//Anyway ArrayAdapter supports only TextView
private ArrayAdapter arrayAdapter;
private Firebase ref;
private Orders activ;
private ArrayList<String> dishes;
public int total;
#Override
protected void onCreate(Bundle savedInstanceState) {
activ = this;
dishes = new ArrayList<String>(20);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_orders);
// Initialize the UI components
foodList = (ListView)findViewById(R.id.listView1);
// Create a reference to a Firebase location
ref = new Firebase("https://xxxxxxxxxx.firebaseio-demo.com/Restaurants/Restaurant 2/Tables/Table 2/Orders");
// Read data and react to changes
ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot snapshot, String previousChildName) {
Map s = snapshot.getValue(Map.class);
dishes.add(snapshot.getName() + " " + ((Map)snapshot.getValue(Map.class)).get("Price"));
Log.i("Test", dishes.toString());
arrayAdapter = new ArrayAdapter(activ, android.R.layout.simple_list_item_1, dishes.toArray());
// By using setAdapter method, you plugged the ListView with adapter
foodList.setAdapter(arrayAdapter);
}
#Override public void onChildChanged(DataSnapshot snapshot, String previousChildName) { }
#Override public void onChildRemoved(DataSnapshot snapshot) {
Map s = snapshot.getValue(Map.class);
dishes.remove(snapshot.getName() + " " + ((Map)snapshot.getValue(Map.class)).get("Price"));
Log.i("Test", dishes.toString());
arrayAdapter = new ArrayAdapter(activ, android.R.layout.simple_list_item_1, dishes.toArray());
// By using setAdapter method, you plugged the ListView with adapter
foodList.setAdapter(arrayAdapter);
}
#Override public void onChildMoved(DataSnapshot snapshot, String previousChildName) { }
#Override
public void onCancelled(FirebaseError arg0) { }
});
foodList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setBackgroundColor(Color.GREEN);
String text = view.toString();
text.replaceAll("[^\\d.]", "");
int num = Integer.parseInt(text);
total += num;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.orders, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void toPayment(View view) {
Intent pay = new Intent(this, PaymentMethod.class);
pay.putExtra(TOTAL_SUM, total);
startActivity(pay);
}
}
What i understand from your question : Suppose when you click on 3rd item i.e "pudding 8", you want this value "pudding 8"(textview value). right??
If that so than you just have to get values from your ArrayList which you pass to the adapter on first place with the help of position attribute inside your setOnItemClickListener like this :
foodList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setBackgroundColor(Color.GREEN);
String text = dishes.get(position);
// do what you want to do with this value.
}
});
Change your onClickListener() like that:
foodList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setBackgroundColor(Color.GREEN);
String text = (String)parent.getItemAtPosition(position);
text.replaceAll("[^\\d.]", "");
int num = Integer.parseInt(text);
total += num;
}
});
Or you can use SimpleAdapter for displaying string and integer values separately using two textviews in a separate xml layout. Using that you can get values on onclick() in a better way.
You need to gettext of that particular view, view.getText().toString();
foodList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setBackgroundColor(Color.GREEN);
String text = view.getText().toString();
text.replaceAll("[^\\d.]", "");
int num = Integer.parseInt(text);
total += num;
}
});
It may help you, but it is bad way:
foodList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = (String) arrayAdapter.getItem(position);
String[] split = item.split(" ");
int num = Integer.parseInt(split[1]);
total += num;
}
});
But it is very urge...
As for me, you need to extends Adapter, to collect into it your custom items, and after clicking gets it and takes integer value you need.
I know this might become a little too late but, hope this
helps someone who was looking for similar solution to Custom ArrayAdapter with multiple values.
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ListItems item = (ListItems) parent.getItemAtPosition(position);
System.out.println("Item: "+item.getName());
}
});

Categories

Resources