First data in the listview should be checked by default - java

I have a requirement that when I am entering zip code and pressing the enter key on the emulator/tablet i am getting list of operator names in the ListView. Inside Listview I am using checkedtextview to populate the data using my custom array adapter.
The listview should be checked at a time one operator name only. Whenever the data is populated to the listview the first operator name should be checked by default.
Is there any way to find out the solution.
I am using the custom array adapter like this
private class OperatorListAdapter extends ArrayAdapter<String> {
private HashMap<Integer, Boolean> selectOperatorStatusMap = new HashMap<Integer, Boolean>();
public OperatorListAdapter(Context context, int resource, List<String> objects) {
super(context, resource, objects);
selectOperatorStatusMap.put(0, true);
for (int i = 1; i < objects.size(); i++) {
selectOperatorStatusMap.put(i, false);
}
}
public void toggleChecked(int position) {
if (selectOperatorStatusMap.get(position)) {
selectOperatorStatusMap.put(position, false);
} else {
selectOperatorStatusMap.put(position, true);
}
notifyDataSetChanged();
}
public void unChecked(int position) {
for (int i = 0; i < selectOperatorStatusMap.size(); i++) {
if(i!=position){
checkedTextView.setChecked(false);
checkedTextView.setCheckMarkDrawable(R.drawable.uncheck);
}
}
}
public List<Integer> getCheckedItemPositions() {
List<Integer> checkedItemPositions = new ArrayList<Integer>();
for (int i = 0; i < selectOperatorStatusMap.size(); i++) {
if (selectOperatorStatusMap.get(i)) {
(checkedItemPositions).add(i);
}
}
return checkedItemPositions;
}
public List<String> getCheckedItems() {
List<String> checkedItems = new ArrayList<String>();
for (int i = 0; i < selectOperatorStatusMap.size(); i++) {
if (selectOperatorStatusMap.get(i)) {
(checkedItems).add(operatorList.get(i));
}
}
return checkedItems;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = getActivity().getLayoutInflater();
row = inflater.inflate(R.layout.provider_list, parent, false);
}
checkedTextView = (CheckedTextView) row.findViewById(R.id.list_text);
checkedTextView.setText(operatorList.get(0));
Log.i(TAG, "OperatorListAdapter:"+operatorList.get(0));
Boolean checked = selectOperatorStatusMap.get(position);
if (checked != null) {
checkedTextView.setChecked(true);
}
return row;
}
}

Yes. in getView instead of
if (checked != null) {
checkedTextView.setChecked(true);
}
Use:
if (position == 0) {
checkedTextView.setChecked(true);
}
else{
checkedTextView.setChecked(false)
}

Related

How to make expandable cardview childlist in recycle view by reusing the same layout

I want to make view by adding child list on android using cardview in recycleview.
i have made class to store these item and make arraylist on each parent of object if the object have child item, so i can differentiate if the list has child or not.
But i have difficulties to render the same layout to make the child list below the parent list. I am pragmatically make the layout one by one but it will be difficult to make that. So i want to render the same layout to my adapter when i want to make a child list whenever the object/class has arraylist of child list in that object.
this is my adapter right now
public class NotificationListAdapter extends BaseListAdapter<NotificationData, NotificationListAdapter.CustomViewHolder> {
private List<NotificationData> notificationData;
private ArrayList<Integer> indexForHide;
public NotificationListAdapter(Context context) {
super(context);
}
#Override
public void addAll(List<NotificationData> items) {
super.addAll(items);
this.notificationData = items;
}
void setChildNotif(){
ArrayList<NotificationData> childDataItems;
List<NotificationData> notificationDataChild = new ArrayList<NotificationData>();
notificationDataChild.addAll(notificationData);
indexForHide = new ArrayList<Integer>();
for (int i = 0; i < notificationData.size(); i++) {
childDataItems = new ArrayList<>();
if (notificationDataChild.size() == 1) {
notificationData.get(i).setChildNotification(childDataItems);
break;
}
for (int j = i; j < notificationDataChild.size(); j++){
if(i==j){
continue;
}else if (notificationDataChild.size() == 1) {
notificationData.get(i).setChildNotification(childDataItems);
break;
}else{
if(notificationDataChild.get(j).getRfqId()!=0){
if(notificationDataChild.get(j).getRfqId()==notificationData.get(i).getRfqId()){
childDataItems.add(notificationDataChild.get(j));
indexForHide.add(j);
}
}
if(!notificationDataChild.get(j).getInvoiceNumber().equalsIgnoreCase("")) {
if (notificationDataChild.get(j).getInvoiceNumber().equalsIgnoreCase(notificationData.get(i).getInvoiceNumber())) {
childDataItems.add(notificationDataChild.get(j));
indexForHide.add(j);
}
}
}
}
notificationData.get(i).setChildNotification(childDataItems);
Log.d("sizeNotif", i+" :"+notificationData.get(i).getChildNotification().size());
}
Log.d("sizeNotification", " :"+notificationData.size());
Log.d("sizeNotificationDummy", " :"+notificationData.size());
Log.d("isiHideAdapter", Arrays.toString(indexForHide.toArray()));
Log.d("isiHideAdapterSize", indexForHide.size()+"");
}
#Override
protected int getItemResourceLayout(int viewType) {
return R.layout.item_notification_list;
}
int position;
#Override
public int getItemViewType(int position) {
this.position = position;
return position;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
setChildNotif();
return new CustomViewHolder(getView(parent, viewType), onItemClickListener);
}
public class CustomViewHolder extends BaseViewHolder<NotificationData> {
private TextView tvNotifTitle, tvNotifBody, tvNotifStatus, tvNotifTime, tvSignUnread, tvHeaderTitle;
private CardView formContent;
private LinearLayout linearLayout_childItems;
private ImageView expandList;
public CustomViewHolder(View itemView, OnItemClickListener onItemClickListener) {
super(itemView, onItemClickListener);
tvNotifTitle = itemView.findViewById(R.id.tvNotifTitle);
tvNotifBody = itemView.findViewById(R.id.tvNotifBody);
// tvNotifStatus = itemView.findViewById(R.id.tvNotifStatus);
tvNotifTime = itemView.findViewById(R.id.tvNotificationTime);
formContent = itemView.findViewById(R.id.formContent);
tvSignUnread = itemView.findViewById(R.id.tvSignUnread);
tvHeaderTitle = itemView.findViewById(R.id.tvHeaderNotifList);
linearLayout_childItems = itemView.findViewById(R.id.ll_child_items);
expandList = itemView.findViewById(R.id.arrow_expand_notif_list);
//SET CHILD
int intMaxNoOfChild = 0;
for (int index = 0; index < notificationData.size(); index++) {
int intMaxSizeTemp = notificationData.get(index).getChildNotification().size();
if (intMaxSizeTemp > intMaxNoOfChild) intMaxNoOfChild = intMaxSizeTemp;
}
linearLayout_childItems.removeAllViews();
for (int indexView = 0; indexView < intMaxNoOfChild; indexView++) {
TextView textView = new TextView(context);
textView.setId(indexView);
textView.setPadding(20, 20, 0, 20);
textView.setGravity(Gravity.LEFT);
textView.setTextSize(14);
textView.setTextColor(ContextCompat.getColor(context, R.color.colorText));
textView.setBackground(ContextCompat.getDrawable(context, R.drawable.bg_sub_notif_text));
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.leftMargin = 16;
textView.setOnClickListener(this);
linearLayout_childItems.addView(textView, layoutParams);
}
}
#Override
public void bind(NotificationData item) {
String title = splitString(item.getTitle());
tvNotifTitle.setText(title);
tvNotifBody.setText(item.getContent());
String txtTime = item.getCreatedAtDisplay().replaceAll("WIB", "");
tvNotifTime.setText(txtTime);
if (position == 0) {
((ViewGroup.MarginLayoutParams) formContent.getLayoutParams()).topMargin = dpToPx(12);
}
((ViewGroup.MarginLayoutParams) formContent.getLayoutParams()).bottomMargin = dpToPx(12);
if (position == getItemCount() - 1) {
((ViewGroup.MarginLayoutParams) formContent.getLayoutParams()).bottomMargin = dpToPx(80);
}
if(item.getIsRead()==1){
formContent.setCardBackgroundColor(context.getResources().getColor(R.color.gray1));
formContent.setCardElevation(5);
formContent.setRadius(15);
tvSignUnread.setVisibility(View.GONE);
}else if(item.getIsRead()==0){
}
//setHeader
Calendar calendar;
SimpleDateFormat dateFormat;
calendar = Calendar.getInstance();
dateFormat = new SimpleDateFormat("yyyy-MM-dd") ;
String date, yesterdayDate, dateDisplayData, dateData;
date = dateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE, -1);
yesterdayDate = dateFormat.format(calendar.getTime());
String[] arrDateDisplayData = item.getCreatedAtDisplay().split(",", 5);
dateDisplayData = arrDateDisplayData[0];
String[] arrDateData = item.getCreatedAt().split(" ", 5);
dateData = arrDateData[0];
Log.d("datenow", date);
Log.d("dateyesterday", yesterdayDate);
Log.d("dateDisplayData", dateDisplayData);
Log.d("dateData", dateData);
if(dateData.equalsIgnoreCase(date)){
tvHeaderTitle.setText("Hari ini");
}else if(dateData.equalsIgnoreCase(yesterdayDate)){
tvHeaderTitle.setText("Kemarin");
}else{
tvHeaderTitle.setText(dateDisplayData);
// tvHeaderTitle.setVisibility(View.GONE);
}
if (getAdapterPosition() > 0) {
String[] timePrev = notificationData.get(getAdapterPosition() - 1).getCreatedAt().split(" ");
if (dateData.equalsIgnoreCase(timePrev[0])) {
tvHeaderTitle.setVisibility(View.GONE);
}
}
if(indexForHide.contains(getAdapterPosition())){
formContent.setVisibility(View.GONE);
}
//SET CHILD
NotificationData dummyParentDataItem = notificationData.get(position);
int noOfChildTextViews = linearLayout_childItems.getChildCount();
for (int index = 0; index < noOfChildTextViews; index++) {
TextView currentTextView = (TextView) linearLayout_childItems.getChildAt(index);
currentTextView.setVisibility(View.VISIBLE);
}
int noOfChild = 0;
if(dummyParentDataItem.getChildNotification()==null){
noOfChild = 0;
}else{
noOfChild = dummyParentDataItem.getChildNotification().size();
}
if (noOfChild < noOfChildTextViews) {
for (int index = noOfChild; index < noOfChildTextViews; index++) {
TextView currentTextView = (TextView) linearLayout_childItems.getChildAt(index);
// currentTextView.setVisibility(View.GONE);
}
}
for (int textViewIndex = 0; textViewIndex < noOfChild; textViewIndex++) {
TextView currentTextView = (TextView) linearLayout_childItems.getChildAt(textViewIndex);
currentTextView.setText(dummyParentDataItem.getChildNotification().get(textViewIndex).getTitle());
/*currentTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext, "" + ((TextView) view).getText().toString(), Toast.LENGTH_SHORT).show();
}
});*/
}
if (noOfChild > 0) {
expandList.setVisibility(View.VISIBLE);
expandList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (linearLayout_childItems.getVisibility() == View.VISIBLE) {
linearLayout_childItems.setVisibility(View.GONE);
// Toast.makeText(context, "expand", Toast.LENGTH_SHORT).show();
expandList.setImageResource(R.drawable.ic_arrow_up_blue);
}
else {
linearLayout_childItems.setVisibility(View.VISIBLE);
expandList.setImageResource(R.drawable.ic_arrow_down_blue);
}
}
});
}else {
linearLayout_childItems.setVisibility(View.GONE);
}
}
public int dpToPx(int dp) {
Resources r = context.getResources();
int px = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dp, r.getDisplayMetrics()
);
return px;
}
public String splitString(String tempString){
StringBuilder finalString = new StringBuilder(tempString);
int i = 0;
while ((i = finalString.indexOf(" ", i + 20)) != -1) {
finalString.replace(i, i + 1, "\n");
}
return finalString.toString();
}
}
}
please help me to render my layout whenever i want to make a child list under my parent list so i can simplify my code above and not making the child layout programatically

How and where exactly need to change to accept normal character search from the accented content without changing the UI android

I am using search filtered list. The list contains accented characters.
If I type Cam, it should support and accept Càm but it's not working. I am clueless where exactly I need to give to work in Adapter class.
Here is the code.
public class MainActivity extends AppCompatActivity {
private HighlightArrayAdapter mHighlightArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Listview sample data
String products[] = {"Càmdoón", "córean", "Lamià", "dell", "HTC One X", "HTC Wildfire S", "HTC Sense", "HTC Sensàtion XE",
"iPhone 4S", "Samsóng Galàxy Note 800",
"Samsung Galàxy S3", "MacBook Air", "Màc Mini", "MàcBook Pro"};
ListView listView = (ListView) findViewById(R.id.listview);
EditText editText = (EditText) findViewById(R.id.inputSearch);
// Adding items to listview
mHighlightArrayAdapter = new HighlightArrayAdapter(this, R.layout.list_item, R.id.product_name, products);
listView.setAdapter(mHighlightArrayAdapter);
// Enabling Search Filter
editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
mHighlightArrayAdapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
}
});
}
}
//HighlightArrayAdapter.
public class HighlightArrayAdapter extends ArrayAdapter<String> {
private final LayoutInflater mInflater;
private final Context mContext;
private final int mResource;
private List<String> mObjects;
private int mFieldId = 0;
private ArrayList<String> mOriginalValues;
private ArrayFilter mFilter;
private final Object mLock = new Object();
private String mSearchText; // this var for highlight
Pattern mPattern;
public HighlightArrayAdapter(Context context, int resource, int textViewResourceId, String[] objects) {
super(context, resource, textViewResourceId, objects);
mContext = context;
mInflater = LayoutInflater.from(context);
mResource = resource;
mObjects = Arrays.asList(objects);
mFieldId = textViewResourceId;
}
#Override
public Context getContext() {
return mContext;
}
#Override
public int getCount() {
return mObjects.size();
}
#Override
public String getItem(int position) {
return mObjects.get(position);
}
#Override
public int getPosition(String item) {
return mObjects.indexOf(item);
}
#Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new ArrayFilter();
}
return mFilter;
}
private class ArrayFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence prefix) {
FilterResults results = new FilterResults();
if (mOriginalValues == null) {
synchronized (mLock) {
mOriginalValues = new ArrayList<>(mObjects);
}
}
if (prefix == null || prefix.length() == 0) {
mSearchText = "";
ArrayList<String> list;
synchronized (mLock) {
list = new ArrayList<>(mOriginalValues);
}
results.values = list;
results.count = list.size();
} else {
String prefixString = prefix.toString().toLowerCase();
mSearchText = prefixString;
ArrayList<String> values;
synchronized (mLock) {
values = new ArrayList<>(mOriginalValues);
}
final int count = values.size();
final ArrayList<String> newValues = new ArrayList<>();
for (int i = 0; i < count; i++) {
final String value = values.get(i);
final String valueText = value.toLowerCase();
// First match against the whole, non-splitted value
if (valueText.startsWith(prefixString) || valueText.contains(prefixString)) {
newValues.add(value);
} else {
final String[] words = valueText.split(" ");
final int wordCount = words.length;
// Start at index 0, in case valueText starts with space(s)
for (int k = 0; k < wordCount; k++) {
if (words[k].startsWith(prefixString) || words[k].contains(prefixString)) {
newValues.add(value);
break;
}
}
}
}
results.values = newValues;
results.count = newValues.size();
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
//noinspection unchecked
mObjects = (List<String>) results.values;
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
TextView text;
if (convertView == null) {
view = mInflater.inflate(mResource, parent, false);
} else {
view = convertView;
}
try {
if (mFieldId == 0) {
// If no custom field is assigned, assume the whole resource is a TextView
text = (TextView) view;
} else {
// Otherwise, find the TextView field within the layout
text = (TextView) view.findViewById(mFieldId);
}
} catch (ClassCastException e) {
Log.e("ArrayAdapter", "You must supply a resource ID for a TextView");
throw new IllegalStateException(
"ArrayAdapter requires the resource ID to be a TextView", e);
}
// HIGHLIGHT...
String fullText = getItem(position);
if (mSearchText != null && !mSearchText.isEmpty()) {
int startPos = fullText.toLowerCase(Locale.US).indexOf(mSearchText.toLowerCase(Locale.US));
int endPos = startPos + mSearchText.length();
if (startPos != -1) {
//Spannable spannable = new SpannableString(removeAccents(fullText)); // i used removeAccents but not worked.
Spannable spannable = new SpannableString(fullText);
ColorStateList blueColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{Color.BLUE});
TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, blueColor, null);
spannable.setSpan(highlightSpan, startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
text.setText(spannable);
} else {
text.setText(fullText);
}
} else {
text.setText(fullText);
}
return view;
}
/* public static String removeAccents(String text) {
return text == null ? null : Normalizer.normalize(text, Normalizer.Form.NFD)
.replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
}*/
/*private SpannableStringBuilder createHighlightedString(String nodeText, int highlightColor) {
SpannableStringBuilder returnValue = new SpannableStringBuilder(nodeText);
String lowercaseNodeText = nodeText.toLowerCase();
Matcher matcher = mSearchText.matcher(lowercaseNodeText);
while (matcher.find()) {
returnValue.setSpan(new ForegroundColorSpan(highlightColor), matcher.start(0),
matcher.end(0), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
}
return returnValue;
}*/
}
Here is the screenshot.
Scenario 1: (This is working)
Scenario 2: ( This is not working when I type normal character of a):
Scenario 3: (This is working when I type accented character):
So how to make Scenario 2 to work when I give normal character search in word to support the accented character list to accept.
I used InCombiningDiacriticalMarks but it's not working i am clueless where exactly need to give.
Kindly help me please in adapter class.
You should match your filtered list to a diactritics-less String.
public static String removeDiacritics(String input) {
String out = "" + input;
out = out.replaceAll(" ", "");
out = out.replaceAll("[èéêë]", "e");
out = out.replaceAll("[ûù]", "u");
out = out.replaceAll("[ïî]", "i");
out = out.replaceAll("[àâ]", "a");
out = out.replaceAll("Ô", "o");
out = out.replaceAll("[ÈÉÊË]", "E");
out = out.replaceAll("[ÛÙ]", "U");
out = out.replaceAll("[ÏÎ]", "I");
out = out.replaceAll("[ÀÂ]", "A");
out = out.replaceAll("Ô", "O");
out = out.replaceAll("-", "");
return out;
}
This way you will not be matching "Cam" with "Càm" anymore, but "Cam" with "Cam". You should also transform your strings to lower (or upper) case to be Upper-case permissive.
hope it helps!

Simple Adapter, Invalid index when filtering

I'm populating a listview with data from a database, it includes Images as well as text. So I can't actually filter the data then pass it to the listview. I have to filter the listview it's self. I have populated the listview using a simple adapter and images load. The problem is when filtering the list view it crashes.(See logcat).
Code I'm using:
Custom Simple Adapter to handle the images
public class ExtendedSimpleAdapter extends SimpleAdapter{
List<HashMap<String, String>> map;
String[] from;
int layout;
int[] to;
Context context;
LayoutInflater mInflater;
public ExtendedSimpleAdapter(Context context, ArrayList<HashMap<String, String>> data,
int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
layout = resource;
map = data;
this.from = from;
this.to = to;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
return this.createViewFromResource(position, convertView, parent, layout);
}
private View createViewFromResource(int position, View convertView,
ViewGroup parent, int resource) {
View v;
if (convertView == null) {
v = mInflater.inflate(resource, parent, false);
} else {
v = convertView;
}
this.bindView(position, v);
return v;
}
private void bindView(int position, View view) {
final Map dataSet = map.get(position);
if (dataSet == null) {
return;
}
final ViewBinder binder = super.getViewBinder();
final int count = to.length;
for (int i = 0; i < count; i++) {
final View v = view.findViewById(to[i]);
if (v != null) {
final Object data = dataSet.get(from[i]);
String text = data == null ? "" : data.toString();
if (text == null) {
text = "";
}
boolean bound = false;
if (binder != null) {
bound = binder.setViewValue(v, data, text);
}
if (!bound) {
if (v instanceof Checkable) {
if (data instanceof Boolean) {
((Checkable) v).setChecked((Boolean) data);
} else if (v instanceof TextView) {
// Note: keep the instanceof TextView check at the bottom of these
// ifs since a lot of views are TextViews (e.g. CheckBoxes).
setViewText((TextView) v, text);
} else {
throw new IllegalStateException(v.getClass().getName() +
" should be bound to a Boolean, not a " +
(data == null ? "<unknown type>" : data.getClass()));
}
} else if (v instanceof TextView) {
// Note: keep the instanceof TextView check at the bottom of these
// ifs since a lot of views are TextViews (e.g. CheckBoxes).
setViewText((TextView) v, text);
} else if (v instanceof ImageView) {
if (data instanceof Integer) {
setViewImage((ImageView) v, (Integer) data);
} else if (data instanceof String) {
setViewImage((ImageView) v, (String) data);
} else {
setViewImage((ImageView) v, text);
}
} else {
throw new IllegalStateException(v.getClass().getName() + " is not a " +
" view that can be bounds by this SimpleAdapter");
}
}
}
}
}
#Override
public int getCount() {
return super.getCount();
}
public void setViewImage(ImageView v, String bmp) {
v.setImageBitmap(ImageTools.decodeBase64(bmp));
}
}
Calling that class:
adapter = new ExtendedSimpleAdapter(
getActivity(), doctorsList,
R.layout.listview_item_layout_doctor,
new String[]{KEY_ID, KEY_NAME, KEY_SPECIALTY, KEY_RATING, KEY_ACCOUNT, KEY_ACTIVE, KEY_IMAGE},
new int[]{R.id.id, R.id.fname, R.id.Specialty, R.id.Rating, R.id.Account, R.id.Active, R.id.doctorImage});
Logcat:
java.lang.IndexOutOfBoundsException: Invalid index 2, size is 2
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at my.app.adapters.ExtendedSimpleAdapter.bindView(ExtendedSimpleAdapter.java:61)
at my.app.adapters.ExtendedSimpleAdapter.createViewFromResource(ExtendedSimpleAdapter.java:54)
at my.app.adapters.ExtendedSimpleAdapter.getView(ExtendedSimpleAdapter.java:41)
I fixed it by implementing a custom filter:
private class CustomFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence prefix) {
FilterResults results = new FilterResults();
if (mUnfilteredData == null) {
mUnfilteredData = new ArrayList<HashMap<String, String>>(map);
}
if (prefix == null || prefix.length() == 0) {
List<HashMap<String, String>> list = mUnfilteredData;
results.values = list;
results.count = list.size();
} else {
String prefixString = prefix.toString().toLowerCase();
List<HashMap<String, String>> unfilteredValues = mUnfilteredData;
int count = unfilteredValues.size();
ArrayList<Map<String, ?>> newValues = new ArrayList<Map<String, ?>>(count);
for (int i = 0; i < count; i++) {
Map<String, ?> h = unfilteredValues.get(i);
if (h != null) {
int len = to.length;
for (int j=0; j<len; j++) {
String str = (String)h.get(from[j]);
String[] words = str.split(" ");
int wordCount = words.length;
for (int k = 0; k < wordCount; k++) {
String word = words[k];
if (word.toLowerCase().contains(prefixString)) {
newValues.add(h);
break;
}
}
}
}
}
results.values = newValues;
results.count = newValues.size();
}
return results;
}
#SuppressWarnings("unchecked")
protected void publishResults(CharSequence constraint, FilterResults results) {
//Remove duplicates
map.addAll((java.util.Collection<? extends HashMap<String, String>>) results.values);
HashSet hs = new HashSet();
hs.addAll(map);
map.clear();
map.addAll(hs);
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
Add this to the adapter:
#Override
public Filter getFilter() {
if(filter != null) return filter;
else return filter = new CustomFilter();
}

Searching and deleting rows in Custom ListView

I'm trying to create a ListView for a Friends list. It has a search functiton in which tthe user can search for a particular freind and then delete them as a friend, message them and so forth.
However, I'm having trouble removing them. I don't think I understand the positioning, or finding out the correct position on where the users freind is in the list.
I want to make sure that in all cases, the user is removed from the correct position. For instance, if the user uses the search function and only one user is returned. Then I don't want the user to be removed at position 0 (one user), I want it to be removed at the correct position so that when the user goes back to the full list. Position 0 in the list isn't accidentaly removed.
Could someone review the code? and show a slight indication as to where I am going wrong with this?
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
res = getResources();
searchField = (EditText) findViewById(R.id.EditText01);
lv = (ListView) findViewById(android.R.id.list);
//button = (Button)findViewById(R.id.btnFriendList);
lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
//button.setFocusable(false);
list = new ArrayList<Friend>();
nameBlock = res.getStringArray(R.array.names);
descBlock = res.getStringArray(R.array.descriptions);
names = new ArrayList<String>();
for(int i = 0; i < nameBlock.length; i++) {
names.add((String)nameBlock[i]);
}
descr = new ArrayList<String>();
for(int i = 0; i < descBlock.length; i++) {
descr.add((String)descBlock[i]);
}
images = new ArrayList<Integer>();
for(int i = 0; i < imageBlock.length; i++) {
images.add((Integer)imageBlock[i]);
}
//imageBlock = res.getIntArray(R.array.images);
int size = nameBlock.length;
for(int i = 0 ; i < size; i++) {
Log.d("FREINDADD", "Freind Added" + i);
list.add(new Friend(i, names.get(i), descr.get(i), images.get(i)));
//friendList2.add(new Friend(i, names.get(i), descr.get(i), images.get(i)));
}
Log.i("Application", "Application started succesfully...");
adapter = new CustomAdapter(this);
setListAdapter(adapter);
Log.i("VIRTU", "Count" + adapter.getCount());
//adapter.getCount();
searchField.addTextChangedListener(new TextWatcher()
{
#Override public void afterTextChanged(Editable s) {}
#Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override public void onTextChanged(CharSequence s, int start, int before, int count)
{
list.clear();
textlength = searchField.getText().length();
for (int i = 0; i < names.size(); i++)
{
if (textlength <= names.get(i).length())
{
if(names.get(i).toLowerCase().contains(searchField.getText().toString().toLowerCase().trim())) {
Log.i("VirtuFriendList", "List recyling in process... ");
list.add(new Friend(i, names.get(i), descr.get(i), images.get(i)));
}
}
}
AppendList(list);
}
});
}
public void AppendList(ArrayList<Friend> list) {
setListAdapter(new CustomAdapter(this));
}
class CustomAdapter extends BaseAdapter {
private Context context;
public CustomAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return list.size();
}
class ViewHolder {
TextView userName;
TextView userDesc;
ImageView userImage;
Button userButton;
ViewHolder(View view) {
userImage = (ImageView)view.findViewById(R.id.imageview);
userName = (TextView)view.findViewById(R.id.title);
userDesc = (TextView)view.findViewById(R.id.mutualTitle);
userButton = (Button)view.findViewById(R.id.btn);
}
}
ViewHolder holder;
View row;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
row = convertView;
if(row == null)
{
// If it is visible to the user, deploy the row(s) - allocated in local memory
LayoutInflater inflater = (LayoutInflater)context .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.search_list_item, parent, false);
holder = new ViewHolder(row);
row.setTag(holder);
Log.d("VIRTU", "Row deployed...");
}
else
{
// Recycle the row if it is not visible to to the user - store in local memory
holder = (ViewHolder)row.getTag();
Log.d("VIRTU", "Row recycled...");
}
Friend temp = list.get(position);
// Set the resources for each component in the list
holder.userImage.setImageResource(temp.getImage());
holder.userName.setText(temp.getName());
holder.userDesc.setText(temp.getDesc());
((Button)row.findViewById(R.id.btn)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu pop = new PopupMenu(getApplicationContext(), v);
MenuInflater inflater = pop.getMenuInflater();
inflater.inflate(R.menu.firned_popup_action,pop.getMenu());
pop.show();
pop.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
int choice = item.getItemId();
switch(choice) {
case R.id.message:
break;
case R.id.unfollow:
break;
case R.id.unfriend:
int position = (Integer)row.getTag();
list.remove(position);
names.remove(position);
images.remove(position);
descr.remove(position);
adapter = new CustomAdapter(context);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
break;
case R.id.cancel:
}
return false;
}
});
}
});
return row;
}
}
}
I think as your structure stands, you will continue to have this problem. My suggestion would be to assign a FriendID (or something similar) to each friend, and when you are building your list, instead of just passing userImage, userName, userDesc and userButton, pass along friendID as well.
For example, I have five friends, and here is their information:
userImage userName userDesc userButton friendID
x Jordyn x x 0
x Sam x x 1
x Connor x x 2
x Paul x x 3
x Raphael x x 4
But my search for (pretending you can search by one letter) those with 'o' in their name returns,
userImage userName userDesc userButton friendID
x Jordyn x x 0
x Connor x x 2
That way, when you delete the 1th row, it actually removes friendID = 2 from your friend list instead of the 1th row from your original friend list, which would've been Sam, which was not your intention.
Hope that helps!
EDIT:
1: add a hidden TextView to your rows called FriendID in your layout file (let me know if you need help with that).
Now, ViewHolder will look like this:
class ViewHolder {
TextView userName;
TextView userDesc;
ImageView userImage;
Button userButton;
TextView friendID;
ViewHolder(View view) {
userImage = (ImageView)view.findViewById(R.id.imageview);
userName = (TextView)view.findViewById(R.id.title);
userDesc = (TextView)view.findViewById(R.id.mutualTitle);
userButton = (Button)view.findViewById(R.id.btn);
friendID = (TextView)view.findViewById(R.id.friendID);
}
}
2: add an arraylist for the friendIDs:
...
descr = new ArrayList<String>();
for(int i = 0; i < descBlock.length; i++) {
descr.add((String)descBlock[i]);
}
images = new ArrayList<Integer>();
for(int i = 0; i < imageBlock.length; i++) {
images.add((Integer)imageBlock[i]);
}
friendIDs = new ArrayList<Integer>();
for(int i = 0; i < friendIDsBlock.length; i++) {
images.add((Integer)friendIdsBlock[i]);
}
...
3: searchField.addTextChangedListener will now look like:
int size = nameBlock.length;
for(int i = 0 ; i < size; i++) {
Log.d("FREINDADD", "Freind Added" + i);
list.add(new Friend(i, names.get(i), descr.get(i), images.get(i)));
//friendList2.add(new Friend(i, names.get(i), descr.get(i), images.get(i), friendIds.get(i)));
}
Log.i("Application", "Application started succesfully...");
4: Now, when you unfriend someone, make sure to get the FriendID at the selected row as opposed to the row index. Then, remove the friend from the search list with the given FriendID as well as the friend from the general friend list with the given FriendID.
You'll have to forgive me, I don't have an IDE in front of me at the moment but I think that about covers it!

Get the ID of checkbox from custom adapter in android?

I have a Custom ArrayList as follows.
public class sendivitesadapter extends ArrayAdapter<Item>{
private Context context;
private ArrayList<Item> items;
private qrusers qrusers;
private LayoutInflater vi;
public sendivitesadapter(Context context,ArrayList<Item> items) {
super(context, 0,items);
this.context= context;
this.qrusers =(qrusers) context;
this.items = items;
vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return super.getCount();
}
#Override
public Item getItem(int position) {
// TODO Auto-generated method stub
return super.getItem(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final Item i = items.get(position);
if (i != null) {
if(i.isSection()){
SectionItem si = (SectionItem)i;
v = vi.inflate(R.layout.checkboxlist, null);
v.setOnClickListener(null);
v.setOnLongClickListener(null);
v.setLongClickable(false);
final TextView sectionView = (TextView) v.findViewById(R.id.list_item_section_text);
sectionView.setText(si.getTitle());
}else{
sendItem ei = (sendItem)i;
v = vi.inflate(R.layout.checkboxlist, null);
final TextView title = (TextView)v.findViewById(R.id.contactname);
final TextView subtitle = (TextView)v.findViewById(R.id.companyname);
final CheckBox checkBox=(CheckBox)v.findViewById(R.id.checboxlist);
if (title != null)
title.setText(ei.contactname);
if(subtitle != null)
subtitle.setText(ei.companyname);
}
}
return v;
}
and it looks like following image.
My java file is as follows.
#Override
protected void onPostExecute(String result) {
JSONArray jarray;
try {
jarray= new JSONArray(result);
name= new String[jarray.length()];
company=new String[jarray.length()];
for (int i=0;i<jarray.length();i++){
JSONObject jobj = jarray.getJSONObject(i);
name[i]= jobj.getString("Name");
company[i]=jobj.getString("Company");
items.add(new sendItem(name[i], company[i], checkBox));
adapter = new sendivitesadapter(qrusers.this,items);
listView.setAdapter(adapter);
Now I get the names from webservice which I am diplaying it in a listview as shown above.
With every name I get a USerID. So my question is whenever the user checks the checkbox in any sequence and click on add user I want the UserID of the checked checkboxes in array. How can I achieve this?
Sounds like it's a good candidate for View.setTag(). You could set the tag on each CheckBox to the id of the user [when you create it, or assign the Name and Company values]. Then in an OnClick or OnChecked type event, you can call view.getTag() to retrieve the id of the currently checked box.
You need to use OnCheckedChangeListener to get the cheched CheckBox ID. This SO will help you- How to handle onCheckedChangeListener for a RadioGroup in a custom ListView adapter . You need to modify the onCheckedChangeListener according to your need.
In your adapter set the position in check box like
checkBox.setTag(position);
And as i think you have to add checked user on click of Add User button. So on click of that button write following code.
public void onClick(View v) {
// TODO Auto-generated method stub
String categoryArray = "";
String[] categoryId;
if(v == AddUser){
int count = 0;
for(int i = 0; i < listViewRightSlideMenu.getChildCount(); i ++){
RelativeLayout relativeLayout = (RelativeLayout)listViewRightSlideMenu.getChildAt(i);
CheckBox ch = (CheckBox) relativeLayout.findViewById(R.id.checkBoxCategory); //use same id of check box which you used in adapter
if(ch.isChecked()){
count++;
categoryArray = categoryArray+ch.getTag()+",";
}
}
if(categoryArray.length() > 0) {
categoryArray = categoryArray.substring(0, categoryArray.length() - 1);
String[] array = categoryArray.split(",");
categoryId = new String[array.length];
for(int i = 0; i< array.length; i++) {
categoryId[i] = listCategory.get(Integer.valueOf(array[i])).getId();
}
for(int i = 0; i < categoryId.length; i++){
String a = categoryId[i];
System.out.println("category id is: "+a);
}
System.out.println("array position: "+categoryId);
}
}

Categories