I made a dictionary app but I search a word for example water,water does not show first line.I want to filter water or w suggestion word.Whats wrong my code?
Thnks
#Override
public boolean onQueryTextChange(String newText) {
newText = newText.toLowerCase();
final ArrayList<DictObjectModel> filteredList = new ArrayList<DictObjectModel>();
for (int i = 0; i < wordcombimelist.size(); i++) {
final String text = wordcombimelist.get(i).toLowerCase();
if (text.contains(newText) && (text.equals(newText)) ) {
filteredList.add(new DictObjectModel(wordcombimelist.get(i),meancombimelist.get(i)));
}
}
adapter = new CustomAdapter(filteredList);
recyclerView.setAdapter(adapter);
return true;
}
First of all you shouldn't be creating new Adapter each time you want to filter your list. You should implement add and remove methods in your CustomAdapter.
Here you can find instruction about filtering the RecyclerView.
Related
I have a list of timezones that gets added to a recycler view. However, my main list in the activity checks properly but when I use the search and the list condenses and I click the checkbox it will not show the checkmark. However, in debug, the value is set to true when clicked and it will still add it into the recycler view properly.
I have tried looking online but there was no solution for this specific problem.
#Override
public void onBindViewHolder(#NonNull final TimezoneViewHolder holder, final int position) {
// Initialize tools
final Timezone_Item currentTimezoneItem = timezoneList.get(position);
int pos = currentTimezoneItem.getId();
final int tzID = --pos;
holder.mChkboxSelect.setText(currentTimezoneItem.getValue());
holder.mUTCCode.setText(currentTimezoneItem.getName());
// This is the solution for... Clicking the checkbox once would select multiple timezones. Not with this.
if(selectedTimezones.get(position)){
holder.mChkboxSelect.setChecked(true);
currentTimezoneItem.setIsSelected(true);
}else{
holder.mChkboxSelect.setChecked(false);
currentTimezoneItem.setIsSelected(false);
}
// Manually activate the clicks in checkbox
holder.mChkboxSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(currentTimezoneItem.getIsSelected()){
currentTimezoneItem.setIsSelected(false);
holder.mChkboxSelect.setChecked(false);
}else {
currentTimezoneItem.setIsSelected(true);
holder.mChkboxSelect.setChecked(true);
}
if(TimezonePickerActivity.isSearching){
selectedTimezones.put(currentTimezoneItem.getId() - 1, currentTimezoneItem.getIsSelected());
}else {
selectedTimezones.put(tzID, currentTimezoneItem.getIsSelected());
}
notifyDataSetChanged();
}
});
}
This is my Search filter...
private Filter SearchFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence searchText) {
List<Timezone_Item> filteredList = new ArrayList<>();
if (searchText == null || searchText.length() == 0) {
TimezonePickerActivity.isSearching = false;
filteredList.addAll(timezoneListFull);
} else {
String filterPattern = searchText.toString().toLowerCase().trim();
TimezonePickerActivity.isSearching = true;
for (Timezone_Item item : timezoneListFull) {
if (item.getName().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = filteredList;
return filterResults;
}
#Override
protected void publishResults(CharSequence searchText, FilterResults results) {
timezoneList.clear();
timezoneList.addAll((List) results.values);
notifyDataSetChanged();
}
};
This is my code to add the selected timezone into the recycler view
fabAddTimezone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { SparseBooleanArray selectedTimezones = Timezone_RVAdapter.selectedTimezones;
// Filter out false values
for (int i = 0; i < selectedTimezones.size(); i++) {
if(!selectedTimezones.valueAt(i)){
selectedTimezones.removeAt(i);
selectedTimezones.delete(i);
}
}
// Take filtered values and find its index to grab text and UTC code
for (int i = 0; i < selectedTimezones.size(); i++) {
// Get the position(Key) which is actually the Timezone_Item ID
int position = selectedTimezones.keyAt(i);
// Create new clock item to add into list
Clock_Item clockItem = new Clock_Item(
Timezone_RVAdapter.timezoneListFull.get(position).getName(),
Timezone_RVAdapter.timezoneListFull.get(position).getValue()
);
// Add clock to a list
mClockList.add(clockItem);
}
// Save clock list
sharedPrefs.SaveClockList(mClockList);
// Go back to main menu. Clock list should automatically load once activity boots
finish();
}
});
There is a possibility that the below block is always true
if(currentTimezoneItem.getIsSelected()){
currentTimezoneItem.setIsSelected(false);
//Calling the below statement is irrelevant inside onClick of itself
//because when inside here checkbox can never be checked
holder.mChkboxSelect.setChecked(false);
}
remove or comment out every line statement calling .setChecked on mChkboxSelect and allow android handle the state. You can control the state of a checkbox but not inside it's onClick event because clicking on a checkbox automatically changes the state.
I'm attempting to restore a list of checkboxes's 'ischecked' state however the boxes are never checked for some reason.
I'm sure I'm overlooking something small.
Any suggestions are appreciated.
Source:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_notification_settings_list_new_message);
pref = getApplicationContext().getSharedPreferences("PREFS", 0);
final int selection = pref.getInt("ChatRepeatPosition", 0);
ButterKnife.bind(this);
getSupportActionBar().setTitle("Repeat Notification In");
list = (ListView) findViewById(R.id.simpleListView);
dataAdapter = new ArrayAdapter<String>(this, R.layout.repeat,
R.id.repeat_tv, text);
list.setAdapter(dataAdapter);
list.setChoiceMode(ListView.CHOICE_MODE_NONE);
if (list != null && selection != 0) {
for (int i = 0; i < list.getCount(); i++) {
CheckBox cb = new CheckBox(this);
cb.setId(i);
if (i == selection) {
cb.setChecked(true);
} else {
CheckBox cbb = new CheckBox(this);
cbb.setChecked(false);
}
}
}
Full Source:
https://pastebin.com/tAMTam3X
Edit:
The first 'answer' shown below is not what I'm attempting on accomplish. I fully understand how to restore the state of a single checkbox. I'm having trouble iterating through my list of checkboxes to restore the state of all of them (I am able to iterate through the list in list.setOnItemClickListener because I can get the view - but I'm not sure how to iterate through the list in oncreate)
checkbox list image
The problem is that you're creating new CheckBox objects and not doing anything with them:
for (int i = 0; i < list.getCount(); i++) {
CheckBox cb = new CheckBox(this);
cb.setId(i);
if (i == selection) {
cb.setChecked(true);
} else {
CheckBox cbb = new CheckBox(this);
cbb.setChecked(false);
}
}
This loops through the size of the list, initializes CheckBoxs, sets the checked state on those CheckBoxs and then ... well, that's it. They are in no way associated with the ListView, so how would its state get updated?
What you want to do is use the setItemChecked method, something like this:
final int selection = pref.getInt("ChatRepeatPosition", 0);
list = (ListView) findViewById(R.id.simpleListView);
list.setItemChecked(selection, true);
And you can delete the for loop that literally does nothing.
If you want to read more than one saved selection, then you would need to read from a database or file since preferences are limited to key / value pairs. But the concept would be the same: read the list of selections, iterated through the list, set the item checked on the list view.
Hope that helps!
try this.. in the on create add your checkbox and initialize it.
cb1 = (CheckBox) findViewById(R.id.yourxmlid);
then add a shared pref to check the state of the check box
sharedpreferences = PreferenceManager.getDefaultSharedPreferences(this);
editor = sharedpreferences.edit();
boolean checkedFlag1 = sharedpreferences.getBoolean("checkboxstate", false);
cb1.setChecked(checkedFlag1);
then finally in your onCheckListener add a shared pref to check the box
cb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (cb1.isChecked()) {
editor.putBoolean("checkboxstate", true);
editor.commit();
Log.i("Checkbox ", "Activated");
}else{
editor.putBoolean("checkboxstate", false);
editor.commit();
Log.i("Checkbox: ","Deactivated");
}
}
});
I'm trying to perform a search on my recycler adapter when onQueryTextChange
as shown below.
newText = newText.toLowerCase();
List<HymnDataModel> search_list = new ArrayList<>();
for(HymnDataModel hymnDataModel : hymnDataList){
String hymn_title = hymnDataModel.getHymnTitle().toLowerCase();
String hymn_subTitle = hymnDataModel.getHymnSubTitle().toLowerCase();
if (hymn_title.contains(newText) || hymn_subTitle.contains(newText)){
search_list.add(hymnDataModel);
}
}
And i filter the Adapter using the setFilter.
adapterRV.setFilter(search_list);
This is the setFilter function in my Adapter
public void setFilter(List<HymnDataModel> search_list) {
mHymnsList = new ArrayList<>();
mHymnsList.addAll(search_list);
//notify to reload
notifyDataSetChanged();
}
The search works just fine, onQueryTextChange
, but after filtering the Adapter and displaying on the RecyclerView, when i click on the filtered/searched item on my recyclerview, it doesn't open that particular item, instead, it opens another item that's not on the filtered list.
Try this instead.Assign search_list to the existing array List.
public void setFilter(List<HymnDataModel> search_list) {
mHymnsList = search_list;
//notify to reload
notifyDataSetChanged();
}
You are appending Filtered data item's in your Arraylist that's why your adapter display item that's not on the filtered list. try this clear your Arraylist before adding Filtered item in your Arraylist
Try this
public void setFilter(List<HymnDataModel> search_list) {
mHymnsList.clear();
mHymnsList.addAll(search_list);
or
mHymnsList = search_list;
//notify to reload
notifyDataSetChanged();
}
ListView lv = ((AlertDialog) dialog).getListView();
SparseBooleanArray checkedItems = lv.getCheckedItemPositions();
if (checkedItems != null) {
for (int i = 0; i < checkedItems.size(); i++) {
//if (checkedItems.valueAt(i)) {
if (checkedItems.get(i)) {
lv.getChildAt(checkedItems.keyAt(i)).setEnabled(false);
String item = lv.getAdapter().getItem(
checkedItems.keyAt(i)).toString();
Log.i("TAG", item);
}
}
}
I am getting all the pre-checked checkbox on load of alert dialog in android. Now, I want to disable the pre-checked checkbox using :
lv.getChildAt(checkedItems.keyAt(i)).setEnabled(false);
But it is not working any idea how to disable is appreciated.
SparseBooleanArray checkedItems = lv.getCheckedItemPositions();
It means just 'checked item'. Your code access just a value in each check boxes. How about access into listview and operate the access?
I think you should access into listview directly.
AlertDialog.Builder builder = new AlertDialog.Builder(A);
builder.setMultiChoiceItems(items, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
AlertDialog dialog = (AlertDialog) dialog;
ListView v = dialog.getListView();
int i = 0;
for (int i = 0; i < items. length; i++) {
v.setItemChecked(i, false); // true if you want to check all
i++;
}
}
});
Maybe for someone it will be useful.
((CheckedTextView)lv.getChildAt(i)).setChecked(isChecked);
I apologize if I worded this poorly but for the sake of clarity I will explain as best I can. I'm using MPAndroidChart to draw a line graph and I followed this tutorial to get it up and running https://www.numetriclabz.com/android-line-chart-using-mpandroidchart-tutorial/#Defining_X-axis_labels. I've made some adjustments to suit my needs and so on.
On button click, I call a method that adds another entry using the value of the edit text field, at the position that i increment each button press so the code is something like entries.add(new Entry(editTextValue, numEntries));This does what I want it to do while I'm looking at the current activity screen, with the previous value remaining, and the next value being added. However, once i leave that activity and return to it, only the last value remains. My understanding is that I need to have a for loop that will iterate over each element in arraylist when I call the drawGraph method that I'm using, but I haven't had any luck with this. I've tried to use for(Entry e: entries) and use e in place of numEntries, but the data type is not compatible. Any help is greatly appreciated!
EDIT: `public class testActivity extends AppCompatActivity {
int counter = 0;
public ArrayList entries = new ArrayList<>();
public static int lifetimeNums;
public static int nums = 0;
public static int numEntries;
public static String entryLabel = Integer.toString(numEntries);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
reDrawGraph();
}
// Graphing method
public void reDrawGraph(){
LineChart chart = (LineChart) findViewById(R.id.chart);
XAxis xAxis = chart.getXAxis();
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
chart.getAxisLeft().setAxisMaxValue(100);
chart.getXAxis().setAxisMaxValue(100);
//Creating list of entries
LineDataSet dataset = new LineDataSet(entries, "# of Calls");
// creating labels
ArrayList<String> labels = new ArrayList<String>();
for (int i = 0; i < 10 + numEntries; i++) {
labels.add(Integer.toString(i));
}
LineData data = new LineData(labels, dataset);
entries.add(new Entry(testActivity.nums, numEntries));
chart.animateXY(1000,1000);
chart.notifyDataSetChanged();
chart.invalidate();
chart.setData(data); // set the data and list of lables into chart
}
public void counterClicked(View view){
try {
EditText inputText = (EditText) findViewById(R.id.edit_text_val);
int localNums = Integer.parseInt(inputText.getText().toString());
if (counter < 3) {
nums += localNums;
counter++;
numEntries++;
Toast.makeText(this, "Total Entries" + entries.get(0),
Toast.LENGTH_SHORT).show();
reDrawGraph();
inputText.getText().clear();
}
if (counter == 3){
lifetimeNums++;
numEntries++;
Intent intent = new Intent(this, SelectionActivity.class);
startActivity(intent);
}
}catch (Exception e) {
Toast.makeText(this, "Please enter a value",
Toast.LENGTH_SHORT).show();
}`