Android getting unchecked checkbox in checklist after search in edittext - android

I have checklist with search functionality(used edittext). When I use it to search it shows filtered items so that I can make the selection that I want, it works properly. However, the checked items become unchecked when the search functionality reloads the list. I want the items selected before the search to remain selected. How can I fix this?
Here is my code:
public class Lab extends Fragment {
Button mViewBtn,msaveBtn;
EditText mReviewdateEdt,mInputSearch;
TextView mMostprecrdTxv,mViewmoreTxv;
View android;
// final Context context = getActivity();
MyCustomAdapter dataAdapter = null;
ListView listView;
DatabaseHandler db;
SQLiteDatabase db1;
Pharmacy mPharmacyFrag;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
android = inflater.inflate(R.layout.lab_frag, container, false);
db=new DatabaseHandler(getActivity());
getIds();
displayListView();
viewAlertDialog();
saveAlertdialog();
return android;
}
private void getIds() {
// TODO Auto-generated method stub
mViewBtn = (Button)android.findViewById(R.id.view);
msaveBtn = (Button)android.findViewById(R.id.save);
mInputSearch = (EditText)android.findViewById(R.id.inputSearch);
listView = (ListView)android.findViewById(R.id.list);
}
ArrayList<States> stateList = new ArrayList<States>();
ArrayList<States> text_sort = new ArrayList<States>();
private void displayListView()
{
stateList = new ArrayList<States>();
States _states = new States("17 KETOSTERIODS","",false);
stateList.add(_states);
_states = new States("17-ALPHA HYDROXY PROGESTERON","",false);
stateList.add(_states);
_states = new States("24 HRS URINE ALBUMIN","",false);
stateList.add(_states);
_states = new States("24HRS URINARYCORTISOL/CREATININE RATIO","",false);
stateList.add(_states);
_states = new States("24HRS URINE PROTEIN","",false);
stateList.add(_states);
_states = new States("2D ECHO","",false);
stateList.add(_states);
_states = new States("2D ECHO&DOPPLER STUDY","",false);
stateList.add(_states);
_states = new States("5-HYDROXY INDOLE ACETIC ACID","",false);
stateList.add(_states);
_states = new States("ABSOLUTE EOSINOPHIL COUNT","",false);
stateList.add(_states);
_states = new States("ABSOLUTE NEUTROPHILIC COUNT","",false);
stateList.add(_states);
dataAdapter = new MyCustomAdapter(getActivity().getBaseContext(),R.layout.state_info, stateList);
listView.setAdapter(dataAdapter);
mInputSearch.addTextChangedListener(new TextWatcher()
{
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3)
{
int textlength = mInputSearch.getText().length();
text_sort.clear();
for (int i = 0; i < stateList.size(); i++)
{
System.out.println("firstlooop"+mInputSearch.getText().toString());
System.out.println("names"+stateList.get(i).getCode());
if (stateList.get(i).getCode().toLowerCase().contains(mInputSearch.getText().toString())||stateList.get(i).getCode().toUpperCase().contains(mInputSearch.getText().toString()))
{
States _states = new States(stateList.get(i).getCode(),"",false);
text_sort.add(_states);
System.out.println("Gdafdhujgkgj");
}
}
System.out.println("text_sort"+text_sort.size());
dataAdapter = new MyCustomAdapter(getActivity(),R.layout.state_info, text_sort);
listView.setAdapter(dataAdapter);
dataAdapter.notifyDataSetChanged();
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
private class MyCustomAdapter extends ArrayAdapter<States>
{
private LayoutInflater vi;
private ArrayList<States> stateList;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<States> stateList)
{
super(context, textViewResourceId, stateList);
this.stateList = new ArrayList<States>();
this.stateList.addAll(stateList);
vi = (LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
}
private class ViewHolder
{
TextView code;
CheckBox name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null)
{
convertView = vi.inflate(R.layout.state_info, null);
holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.code);
holder.name =(CheckBox)convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
holder.name.setOnClickListener( new View.OnClickListener()
{
public void onClick(View v)
{
CheckBox cb = (CheckBox) v;
States _state = (States) cb.getTag();
_state.setSelected(cb.isChecked());
}
});
}
else
{
holder = (ViewHolder) convertView.getTag();
}
States state = stateList.get(position);
holder.code.setText( state.getCode());
holder.name.setText(state.getName());
holder.name.setChecked(state.isSelected());
holder.name.setTag(state);
return convertView;
}
}
private void viewAlertDialog()
{
mViewBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
StringBuffer responseText = new StringBuffer();
ArrayList<States> stateList = dataAdapter.stateList;
for(int i=0;i<stateList.size();i++)
{
States state = stateList.get(i);
if(state.isSelected())
{
responseText.append("\n\n" + state.getCode());
}
}
final TextView myView = new TextView(getActivity());
myView.setText("Selected Tests are : \n"+responseText);
myView.setTextSize(14);
alertDialogBuilder.setCustomTitle(myView);
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setNegativeButton("Close",new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface arg0, int arg1)
{
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
}
private void saveAlertdialog()
{
// TODO Auto-generated method stub
msaveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setMessage("Lab Orders Saved");
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setNegativeButton("PHARMACY",newDialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface arg0, int arg1) {
int newFragmentNumber = 1;
((Tabswipe) getActivity()).setDisplayedFragment(newFragmentNumber);
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
StringBuffer responseText = new StringBuffer();
ArrayList<States> stateList = dataAdapter.stateList;
for(int i=0;i<stateList.size();i++)
{
States state = stateList.get(i);
if(state.isSelected())
{
responseText.append("\n" + state.getCode());
}
}
db1=db.getWritableDatabase();
ContentValues values=new ContentValues();
values.put("LabTests",String.valueOf(responseText));
db1.insert("Labtests", null, values);
Cursor cursor=db1.rawQuery("select * from Labtests", null);
if(cursor!=null)
{
if(cursor.moveToFirst())
{
do
{
String tests=cursor.getString(cursor.getColumnIndex("LabTests"));
}while(cursor.moveToNext());
}
}
}
});
}
}
public class States {
String code = null;
String name = null;
boolean selected = false;
public States(String code, String name, boolean selected)
{
super();
this.code = code;
this.name = name;
this.selected = selected;
}
public String getCode()
{
return code;
}
public void setCode(String code)
{
this.code = code;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public boolean isSelected()
{
return selected;
}
public void setSelected(boolean selected)
{
this.selected = selected;
}
}

ListView recycles the views every time its associated edit text's value is changed. That's why the Check-boxes does not retain their states.
To accomplish your task:
Store the checked items in an array.
When you click any checkbox in the listview, change the value of that particular item in the array.
Inside your getView method, check or uncheck the Check-boxes by reading the values from the array.
That way your checkboxes will retain their states. I hope this is clear.

Related

Compare list String values with array list [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I have listview with text in check box in every row. I am saving the selected values in a list on button click and then close the app when i open the app i am checking if all the values of list are there in the listview or not. If yes, then I want to set the checkboxes of those values as selected. How to to do this? Can any one help me?
public class MainActivity extends AppCompatActivity {
MyCustomAdapter dataAdapter = null;
String str, str1;
SharedPreferences pref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
displayListView();
checkButtonClick();
}
private void displayListView()
{
//Array list of countries
ArrayList<States> stateList = new ArrayList<States>();
States _states = new States("AP","Andhra Pradesh",false);
stateList.add(_states);
_states = new States("DL","Delhi",false);
stateList.add(_states);
_states = new States("GA","Goa",false);
stateList.add(_states);
_states = new States("JK","Jammu & Kashmir",false);
stateList.add(_states);
_states = new States("KA","Karnataka",false);
stateList.add(_states);
_states = new States("KL","Kerala",false);
stateList.add(_states);
_states = new States("RJ","Rajasthan",false);
stateList.add(_states);
_states = new States("WB","West Bengal",false);
stateList.add(_states);
dataAdapter = new MyCustomAdapter(this,R.layout.state_info, stateList);
ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(dataAdapter);
}
private void checkButtonClick()
{
Button myButton = (Button) findViewById(R.id.findSelected);
myButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
StringBuffer responseText = new StringBuffer();
responseText.append("The following were selected...\n");
StringBuilder sb = new StringBuilder();
ArrayList<States> stateList = dataAdapter.stateList;
for(int i=0;i<stateList.size();i++)
{
States state = stateList.get(i);
if(state.isSelected())
{
responseText.append("\n" + state.getName());
sb.append(state.getName());
sb.append(",");
if (sb.length() > 0 ) {
str = sb.substring(0, sb.length()-1);
}
}
}
Toast.makeText(getApplicationContext(),
responseText, Toast.LENGTH_LONG).show();
System.out.println(str);
pref.edit().putString("key", str).apply();
}
});
}
}
public class MyCustomAdapter extends ArrayAdapter<States> {
public ArrayList<States> stateList;
public MyCustomAdapter(Context context, int textViewResourceId, ArrayList<States> stateList)
{
super(context, textViewResourceId, stateList);
this.stateList = new ArrayList<States>();
this.stateList.addAll(stateList);
this.getSelectedList();
}
private class ViewHolder
{
TextView code;
CheckBox name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null)
{
LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.state_info, null);
holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.code);
holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
holder.name.setOnClickListener( new View.OnClickListener()
{
public void onClick(View v)
{
CheckBox cb = (CheckBox) v;
States _state = (States) cb.getTag();
/* Toast.makeText(getApplicationContext(), "Clicked on Checkbox: " + cb.getText() + " is " + cb.isChecked(),
Toast.LENGTH_LONG).show();*/
_state.setSelected(cb.isChecked());
}
});
}
else
{
holder = (ViewHolder) convertView.getTag();
}
States state = stateList.get(position);
holder.code.setText(" (" + state.getCode() + ")");
holder.name.setText(state.getName());
holder.name.setChecked(state.isSelected());
holder.name.setTag(state);
return convertView;
}
private void getSelectedList(){
pref = get Context().getSharedPreferences("MYPref", Context.MODE_PRIVATE);
String text = pref.getString("key","");
List<String> selectedList = Arrays.asList(text.split(","));
for(States state: this.stateList){
if(selectedList.contains(state.getName())){
state.setSelected(true);
}
}
}
}
public class States {
String code = null;
String name = null;
boolean selected = false;
public States(String code, String name, boolean selected) {
this.code = code;
this.name = name;
this.selected = selected;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
I understand your problem. Let's make a small change in your adapter.
public class MyCustomAdapter extends ArrayAdapter<States> {
public ArrayList<States> stateList;
public MyCustomAdapter(Context context, int textViewResourceId, ArrayList<States> stateList)
{
super(context, textViewResourceId, stateList);
this.stateList = new ArrayList<States>();
this.stateList.addAll(stateList);
this.getSelectedList();
}
private void getSelectedList()
{
pref = context.getSharedPreferences("MYPref", Context.MODE_PRIVATE);
String text = pref.getString("key","");
List<String> selectedList = Arrays.asList(text.split(","));
for (State state: this.stateList) {
if (selectedList.contains(state.getName())) {
state.setSelected(true);
}
}
}
...
}
for (int i = 0; i < stateList.size(); i++) {
States state = stateList.get(i);
if (list.contains(state.getName()))
state.setSelected(true);
}
Delete these lines
if (sb.length() > 0 ) {
str = sb.substring(0, sb.length()-1);
}
in checkButtonClick.
str = sb.toString();
pref.edit().putString("key", str).apply();

Deleting listview item from database

I am deleting the title 2 list item item
But the last title gets deleted that is the title 8 gets deleted
When I then go back to the previous screen and reopen the list. The correct that is the 2nd item title 2 had been deleted.
Here is the DataAdapter
public class DataAdapter extends BaseAdapter {
String a[];
Context ctx;
View.OnClickListener onClickListener;
MyDBHandler dbHelper;
AlertDialog alertDialog;
ArrayList<Calendars> arrayList;
public DataAdapter(Context reminderList, ArrayList<Calendars> arrayList, MyDBHandler dbHelper) {
this.ctx = reminderList;
this.arrayList = arrayList;
this.dbHelper = dbHelper;
}
public void Swap(ArrayList<Calendars> arrayList) {
this.arrayList.clear();
this.arrayList.addAll(arrayList);
this.notifyDataSetChanged();
Log.e("arraylist", arrayList.toString());
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflate = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflate.inflate(R.layout.activity_view_record, parent, false);
final ViewHolder holder = new ViewHolder();
holder.dateTextView = (TextView) convertView.findViewById(R.id.datelist);
holder.timeTextView = (TextView) convertView.findViewById(R.id.timelist);
holder.titleTextView = (TextView) convertView.findViewById(R.id.titlelist);
holder.idTextview = (TextView) convertView.findViewById(R.id.idlist);
holder.deleteButton = (Button) convertView.findViewById(R.id.deletelist);
holder.dateTextView.setText(arrayList.get(position).get_reminderdate());
holder.timeTextView.setText(arrayList.get(position).get_remindertime());
holder.titleTextView.setText(arrayList.get(position).get_remindertitle());
holder.idTextview.setText(arrayList.get(position).get_id() + "");
holder.deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder adb = new AlertDialog.Builder(v.getRootView().getContext());
adb.setTitle("Delete");
adb.setMessage("Are you sure you want to delete this reminder?");
//final int positionToRemove = view.getId();
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dbHelper.remove(arrayList.get(position).get_id());
Log.e("position", position + "");
arrayList.remove(position);
arrayList = dbHelper.databaseToArrayList();
notifyDataSetInvalidated();
notifyDataSetChanged();
//Swap(dbHelper.databaseToArrayList());
}
});
adb.show();
}
});
}
return convertView;
}
class ViewHolder {
TextView titleTextView, dateTextView, timeTextView, idTextview;
Button deleteButton;
}
}
Here is the ListActivity
public class ReminderList extends ActionBarActivity {
Calendars calendars;
Button deleteButton;
private MyDBHandler dbHelper;
private ListView listView;
private ArrayList<Calendars> arrayList;
private SimpleCursorAdapter adapter;
int pos;
DataAdapter dataAdapter;
final String[] from = new String[]{MyDBHandler.COLUMN_REMINDER_TITLE,
MyDBHandler.COLUMN_REMINDER_DATE, MyDBHandler.COLUMN_REMINDER_TIME, MyDBHandler.COLUMN_ID,
MyDBHandler.COLUMN_REMINDER_DESCRIPTION, MyDBHandler.COLUMN_REMINDER_SNOOZE, MyDBHandler.COLUMN_REMINDER_REPEAT, MyDBHandler.COLUMN_ID};
final int[] to = new int[]{R.id.titlelist, R.id.datelist, R.id.timelist, R.id.idlist,
R.id.descriptionlist, R.id.snoozelist, R.id.repeatlist, R.id.deletelist};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reminder_list);
deleteButton = (Button) findViewById(R.id.deletelist);
// adapter=new DataAdapter(ReminderList.this,from);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onStart() {
arrayList = new ArrayList<Calendars>();
dbHelper = new MyDBHandler(this);
Cursor cursor = dbHelper.fetch();
arrayList = dbHelper.databaseToArrayList();
listView = (ListView) findViewById(R.id.list_view);
listView.setEmptyView(findViewById(R.id.empty));
dataAdapter = new DataAdapter(this, arrayList, dbHelper);
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long viewId) {
String title = arrayList.get(position).get_remindertitle();
Log.d("title", title);
String date = arrayList.get(position).get_reminderdate();
String time = arrayList.get(position).get_remindertime();
String id = arrayList.get(position).get_id() + "";
String description = arrayList.get(position).get_reminderdescription();
String snooze = arrayList.get(position).get_remindersnooze();
String repeat = arrayList.get(position).get_reminderrepeat();
Intent modify_intent = new Intent(getApplicationContext(), AlarmActivity.class);
modify_intent.putExtra("id", id);
modify_intent.putExtra("title", title);
modify_intent.putExtra("time", time);
modify_intent.putExtra("date", date);
modify_intent.putExtra("description", description);
modify_intent.putExtra("snooze", snooze);
modify_intent.putExtra("repeat", repeat);
startActivity(modify_intent);
dataAdapter.notifyDataSetChanged();
listView.invalidateViews();
}
});
super.onStart();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
NavUtils.navigateUpFromSameTask(this);
return true;
}
case R.id.add_record: {
Intent add_mem = new Intent(this, AlarmActivity.class);
startActivity(add_mem);
}
default:
return super.onOptionsItemSelected(item);
}
}
}
DatabasetoArraylist function
public ArrayList<Calendars> databaseToArrayList() {
ArrayList<Calendars> arrayList = new ArrayList();
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_REMINDER;
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex("_reminderdate")) != null) {
Calendars calendars = new Calendars();
calendars.set_id(c.getInt(c.getColumnIndex(COLUMN_ID)));
calendars.set_reminderdate(c.getString(c.getColumnIndex(COLUMN_REMINDER_DATE)));
calendars.set_remindertime(c.getString(c.getColumnIndex(COLUMN_REMINDER_TIME)));
calendars.set_remindertitle(c.getString(c.getColumnIndex(COLUMN_REMINDER_TITLE)));
calendars.set_reminderdescription(c.getString(c.getColumnIndex(COLUMN_REMINDER_DESCRIPTION)));
calendars.set_reminderrepeat(c.getString(c.getColumnIndex(COLUMN_REMINDER_REPEAT)));
calendars.set_remindersnooze(c.getString(c.getColumnIndex(COLUMN_REMINDER_SNOOZE)));
arrayList.add(calendars);
}
c.moveToNext();
}
c.close();
db.close();
return arrayList;
}
Change your getView() method of adapter by below code:
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
final Calendars calendars = arrayList.get(position);
if (convertView == null)
{
LayoutInflater inflate = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflate.inflate(R.layout.activity_view_record, parent, false);
holder = new ViewHolder();
holder.dateTextView = (TextView) convertView.findViewById(R.id.datelist);
holder.timeTextView = (TextView) convertView.findViewById(R.id.timelist);
holder.titleTextView = (TextView) convertView.findViewById(R.id.titlelist);
holder.idTextview = (TextView) convertView.findViewById(R.id.idlist);
holder.deleteButton = (Button) convertView.findViewById(R.id.deletelist);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.dateTextView.setText(calendars.get_reminderdate());
holder.timeTextView.setText(calendars.get_remindertime());
holder.titleTextView.setText(calendars.get_remindertitle());
holder.idTextview.setText(calendars.get_id() + "");
holder.deleteButton.setTag(calendars);
holder.deleteButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
AlertDialog.Builder adb = new AlertDialog.Builder(v.getRootView().getContext());
adb.setTitle("Delete");
adb.setMessage("Are you sure you want to delete this reminder?");
//final int positionToRemove = view.getId();
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
final selectedCalendar = (Calendars) holder.deleteButton.getTag();
dbHelper.remove(selectedCalendar.get_id());
arrayList = dbHelper.databaseToArrayList();
notifyDataSetInvalidated();
notifyDataSetChanged();
//Swap(dbHelper.databaseToArrayList());
}
});
adb.show();
}
});
}
return convertView;
}

android filter listview with edittext item come from database

i have a listview . in which item come from database listview has also checkbox . listview work fine . now i put a edittext on listview i wana filter my listview i try a lot . i do some thing like this.i use custom adapter.
this is my list data code
public class DataListActivity extends Activity {
ListView listView;
SQLiteDatabase sqLiteDatabase;
FoodDbHelper foodDbHelper;
Cursor cursor;
ListDataAdapter listDataAdapter;
private Button button1;
ListDataAdapter dataAdapter = null;
Button button;
DataProvider dataProvider;
ArrayList<HashMap<String, String>> namessList;
EditText inputSearch;
String search_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.data_list_layout);
inputSearch = (EditText)findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changes the Text
listDataAdapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(DataListActivity.this, button1);
//Inflating the Popup using xml file
popup.getMenuInflater()
.inflate(R.menu.popup_menu, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
AlertDialog.Builder a_builder = new AlertDialog.Builder(DataListActivity.this);
a_builder.setMessage("Do You Want To Close This App !!!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(getApplicationContext(), MainMenu.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("EXIT", true);
startActivity(intent);
//finish();
}
})
.setNegativeButton("No" , new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = a_builder.create();
alert.setTitle("Alert !!!");
alert.show();
// Toast.makeText(
// MainMenu.this,
// "You Clicked : " + item.getTitle(),
// Toast.LENGTH_SHORT
// ).show();
return true;
}
});
popup.show(); //showing popup menu
}
});
listView = (ListView) findViewById(R.id.list_View);
listDataAdapter = new ListDataAdapter(getApplicationContext(),
R.layout.row_layout) {
#Override
protected void showCheckedButton(int position, boolean value) {
// TODO Auto-generated method stub
final DataProvider item = (DataProvider) listDataAdapter
.getItem(position);
Log.i("", "");
item.setSelected(value);
Button myButton = (Button) findViewById(R.id.findSelected);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringBuffer responseText = new StringBuffer();
responseText
.append("The following dishes were selected...\n");
ArrayList<DataProvider> list = listDataAdapter
.getSelectedIndexes();
int sum = 0;
for (int i = 0; i < list.size(); i++) {
DataProvider dataProvider = list.get(i);
sum = sum + dataProvider.getCalorie();
responseText.append("\n" + dataProvider.getName()
+ " : " + dataProvider.getCalorie()
+ " kcal"
);
}
Toast.makeText(getApplicationContext(), ""+responseText+"\n"+"................................."
+"\n"+"Total Calories In Your Menu Is : " +sum,
Toast.LENGTH_LONG).show();
}
});
}
};
listView.setAdapter(listDataAdapter);
foodDbHelper = new FoodDbHelper(getApplicationContext());
sqLiteDatabase = foodDbHelper.getReadableDatabase();
cursor = foodDbHelper.getInformations(sqLiteDatabase);
if (cursor.moveToFirst()) {
do {
String name, quantity, fat, protein, sugar, carbohydrates;
boolean selected = false;
String names = null;
Integer calorie;
name = cursor.getString(0);
quantity = cursor.getString(1);
calorie = Integer.valueOf(cursor.getString(2));
fat = cursor.getString(3);
protein = cursor.getString(4);
sugar = cursor.getString(5);
carbohydrates = cursor.getString(6);
DataProvider dataProvider = new DataProvider(name, quantity,
calorie, fat, protein, sugar, carbohydrates, names, selected);
listDataAdapter.add(dataProvider);
} while (cursor.moveToNext());
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(getApplicationContext(),
"dish name is : " + name, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),
Detail.class);
}
});
}
public void gobackk(View view) {
Intent intent = new Intent(this, MainMenu.class);
startActivity(intent);
}
}
this is custom adapter code
public abstract class ListDataAdapter extends ArrayAdapter {
List list = new ArrayList();
boolean index[];
public ListDataAdapter(Context context, int resource) {
super(context, resource);
index = new boolean[list.size()];
}
static class LayoutHandler {
TextView name, quantity, calorie, fat, protein, sugar, carbohydrates;
CheckBox names;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
index = new boolean[list.size()];
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout, parent, false);
layoutHandler = new LayoutHandler();
layoutHandler.name = (TextView) row
.findViewById(R.id.text_dish_name);
layoutHandler.quantity = (TextView) row
.findViewById(R.id.text_dish_quantity);
layoutHandler.calorie = (TextView) row
.findViewById(R.id.text_dish_calorie);
layoutHandler.fat = (TextView) row.findViewById(R.id.text_dish_fat);
layoutHandler.protein = (TextView) row
.findViewById(R.id.text_dish_protein);
layoutHandler.sugar = (TextView) row
.findViewById(R.id.text_dish_sugar);
layoutHandler.carbohydrates = (TextView) row
.findViewById(R.id.text_dish_carbohydrates);
layoutHandler.names = (CheckBox) row.findViewById(R.id.checkBox1);
row.setTag(layoutHandler);
} else {
layoutHandler = (LayoutHandler) row.getTag();
}
DataProvider dataProvider = (DataProvider) this.getItem(position);
layoutHandler.name.setText(dataProvider.getName());
layoutHandler.quantity.setText(dataProvider.getQuantity());
layoutHandler.calorie
.setText(String.valueOf(dataProvider.getCalorie()));
layoutHandler.fat.setText(dataProvider.getFat());
layoutHandler.protein.setText(dataProvider.getProtein());
layoutHandler.sugar.setText(dataProvider.getSugar());
layoutHandler.carbohydrates.setText(dataProvider.getCarbohydrates());
//layoutHandler.names.setChecked(dataProvider.isSelected());
layoutHandler.names.setTag(position);
layoutHandler.names.setChecked(index[position]);
layoutHandler.names
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
int pos = (Integer) buttonView.getTag();
index[pos] = isChecked;
showCheckedButton(position, isChecked);
}
});
return row;
}
public ArrayList<DataProvider> getSelectedIndexes() {
int size = list.size();
ArrayList<DataProvider> selectedItems = new ArrayList<DataProvider>();
for (int i = 0; i < size; i++) {
DataProvider cItem = (DataProvider) list.get(i);
if (index[i]) {
selectedItems.add(cItem);
}
}
return selectedItems;
}
protected abstract void showCheckedButton(int position, boolean value);
}

android listview item filter with edittext issue

i have a listview which show list of item .item come from database.i used custom adapter.which work fine now i add edittext on the top of my listview i want to filter my list.for exmple when i type word "A" in edittext list filter and show me the only name which start from A.i try to do this but i fail.i am new in android development so please help me to solve my problem.
this is my datalist code
public class DataListActivity extends Activity {
ListView listView;
SQLiteDatabase sqLiteDatabase;
FoodDbHelper foodDbHelper;
Cursor cursor;
ListDataAdapter listDataAdapter;
private Button button1;
ListDataAdapter dataAdapter = null;
Button button;
DataProvider dataProvider;
ArrayList<HashMap<String, String>> namessList;
EditText inputSearch;
String search_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.data_list_layout);
inputSearch = (EditText)findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changes the Text
listDataAdapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
listView = (ListView) findViewById(R.id.list_View);
listDataAdapter = new ListDataAdapter(getApplicationContext(),
R.layout.row_layout) {
#Override
protected void showCheckedButton(int position, boolean value) {
// TODO Auto-generated method stub
DataProvider item = (DataProvider) listDataAdapter
.getItem(position);
Log.i("", "");
item.setSelected(value);
Button myButton = (Button) findViewById(R.id.findSelected);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringBuffer responseText = new StringBuffer();
responseText
.append("The following dishes were selected...\n");
ArrayList<DataProvider> list = listDataAdapter
.getSelectedIndexes();
int sum = 0;
for (int i = 0; i < list.size(); i++) {
DataProvider dataProvider = list.get(i);
sum = sum + dataProvider.getCalorie();
responseText.append("\n" + dataProvider.getName()
+ " : " + dataProvider.getCalorie()
+ " kcal"
);
}
Toast.makeText(getApplicationContext(), ""+responseText+"\n"+"................................."
+"\n"+"Total Calories In Your Menu Is : " +sum,
Toast.LENGTH_LONG).show();
}
});
}
};
listView.setAdapter(listDataAdapter);
foodDbHelper = new FoodDbHelper(getApplicationContext());
sqLiteDatabase = foodDbHelper.getReadableDatabase();
cursor = foodDbHelper.getInformations(sqLiteDatabase);
if (cursor.moveToFirst()) {
do {
String name, quantity, fat, protein, sugar, carbohydrates;
boolean selected = false;
String names = null;
Integer calorie;
name = cursor.getString(0);
quantity = cursor.getString(1);
calorie = Integer.valueOf(cursor.getString(2));
fat = cursor.getString(3);
protein = cursor.getString(4);
sugar = cursor.getString(5);
carbohydrates = cursor.getString(6);
DataProvider dataProvider = new DataProvider(name, quantity,
calorie, fat, protein, sugar, carbohydrates, names, selected);
listDataAdapter.add(dataProvider);
} while (cursor.moveToNext());
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"dish name is : " + dataprovider.getName(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),
Detail.class);
startActivity(intent);
}
});
}
public void gobackk(View view) {
Intent intent = new Intent(this, MainMenu.class);
startActivity(intent);
}
}
this is my custom adapter code
public abstract class ListDataAdapter extends ArrayAdapter {
List list = new ArrayList();
boolean index[];
public ListDataAdapter(Context context, int resource) {
super(context, resource);
index = new boolean[list.size()];
}
static class LayoutHandler {
TextView name, quantity, calorie, fat, protein, sugar, carbohydrates;
CheckBox names;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
index = new boolean[list.size()];
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout, parent, false);
layoutHandler = new LayoutHandler();
layoutHandler.name = (TextView) row
.findViewById(R.id.text_dish_name);
layoutHandler.quantity = (TextView) row
.findViewById(R.id.text_dish_quantity);
layoutHandler.calorie = (TextView) row
.findViewById(R.id.text_dish_calorie);
layoutHandler.fat = (TextView) row.findViewById(R.id.text_dish_fat);
layoutHandler.protein = (TextView) row
.findViewById(R.id.text_dish_protein);
layoutHandler.sugar = (TextView) row
.findViewById(R.id.text_dish_sugar);
layoutHandler.carbohydrates = (TextView) row
.findViewById(R.id.text_dish_carbohydrates);
layoutHandler.names = (CheckBox) row.findViewById(R.id.checkBox1);
row.setTag(layoutHandler);
} else {
layoutHandler = (LayoutHandler) row.getTag();
}
DataProvider dataProvider = (DataProvider) this.getItem(position);
layoutHandler.name.setText(dataProvider.getName());
layoutHandler.quantity.setText(dataProvider.getQuantity());
layoutHandler.calorie
.setText(String.valueOf(dataProvider.getCalorie()));
layoutHandler.fat.setText(dataProvider.getFat());
layoutHandler.protein.setText(dataProvider.getProtein());
layoutHandler.sugar.setText(dataProvider.getSugar());
layoutHandler.carbohydrates.setText(dataProvider.getCarbohydrates());
//layoutHandler.names.setChecked(dataProvider.isSelected());
layoutHandler.names.setTag(position);
layoutHandler.names.setChecked(index[position]);
layoutHandler.names
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
int pos = (Integer) buttonView.getTag();
index[pos] = isChecked;
showCheckedButton(position, isChecked);
}
});
return row;
}
public ArrayList<DataProvider> getSelectedIndexes() {
int size = list.size();
ArrayList<DataProvider> selectedItems = new ArrayList<DataProvider>();
for (int i = 0; i < size; i++) {
DataProvider cItem = (DataProvider) list.get(i);
if (index[i]) {
selectedItems.add(cItem);
}
}
return selectedItems;
}
protected abstract void showCheckedButton(int position, boolean value);
}

Listview having ediitext

I have a sectioned Listview having some edittexts. If I click on that edittext for the first time, the softkeyboard works fine. And if I hide that keyboard and click on another edittext the keyboard is appearing but refreshing several times. Also at that time I can't write anything on that ediitext. Anyone please help
This is my adapter class
public class ListAdapter_baradmin extends BaseAdapter{
Context ctx;
LayoutInflater lInflater;
public ArrayList myItems = new ArrayList();
public static String[] str_Id = new String[datalength];
public static String[] str_Idoriginal = new String[datalength];
public static String[] str_Desc = new String[datalength];
public static String[] str_UOM = new String[datalength];
public static String[] str_Parlevel = new String[datalength];
public static String[] str_Openingstock = new String[datalength];
public static String[] str_Reg = new String[datalength];
public static String[] str_Intertransfer = new String[datalength];
public static String[] str_Closingstock = new String[datalength];
public static String[] str_Remark = new String[datalength];
SeparatedListAdapter separatedListAdapter;
ArrayList<String> Data_id = new ArrayList<String>();
ArrayList<String> Data_name = new ArrayList<String>();
ArrayList<String> Data_parlevel = new ArrayList<String>();
ArrayList<String> Data_uom = new ArrayList<String>();
public ListAdapter_baradmin(Context context
,ArrayList<String> Items_id
,ArrayList<String> Items_desc
,ArrayList<String> Items_perunitcost
,ArrayList<String> Items_uom
,ArrayList<String> Items_idoriginal) {
ctx = context;
Data_id .addAll(Items_id);
Data_name .addAll(Items_desc);
Data_parlevel .addAll(Items_perunitcost);
Data_uom .addAll(Items_uom);
for(int i=0;i<Items_id.size();i++){
str_Id[i] = Items_id.get(i);
str_Idoriginal[i] = Items_idoriginal.get(i);
str_Desc[i] = Items_desc.get(i);
str_UOM[i] = Items_uom.get(i);
str_Parlevel[i] = Items_perunitcost.get(i);
str_Openingstock[i] = "";
str_Reg[i] = "";
str_Intertransfer[i] = "";
str_Closingstock[i] = "";
str_Remark[i] = "";
//System.out.println("str_Idoriginal "+str_Idoriginal[i]);
}
lInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
notifyDataSetChanged();
}
#Override
public int getCount() {
return Data_id.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
/*if (convertView == null) {
convertView = (View) lInflater.inflate(R.layout.baradmin_row, parent, false);
}*/
if (convertView == null) {
holder = new ViewHolder();
//convertView = (View)lInflater.inflate(R.layout.baradmin_row, null);
convertView = (View) lInflater.inflate(R.layout.baradmin_row, parent, false);
//holder = new ViewHolder();
holder.editText_id = (EditText) convertView.findViewById(R.id.edittext_slno_baradmin);
holder.editText_desc = (EditText) convertView.findViewById(R.id.edittext_desc_baradmin);
holder.editText_uom = (EditText) convertView.findViewById(R.id.edittext_uom_baradmin);
holder.editText_parlevel = (EditText) convertView.findViewById(R.id.edittext_parlevel_baradmin);
holder.edittext_openingstock_baradmin = (EditText) convertView.findViewById(R.id.edittext_openingstock_baradmin);
holder.edittext_reg_baradmin = (EditText) convertView.findViewById(R.id.edittext_reg_baradmin);
holder.edittext_intertransfer_baradmin = (EditText) convertView.findViewById(R.id.edittext_intertransfer_baradmin);
holder.edittext_closingstock_baradmin = (EditText) convertView.findViewById(R.id.edittext_closingstock_baradmin);
holder.edittext_remark_baradmin = (EditText) convertView.findViewById(R.id.edittext_remark_baradmin);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
holder.editText_id .setText(position+1+"");
holder.editText_desc .setText(Data_name.get(position));
holder.editText_uom .setText(Data_uom.get(position));
holder.editText_parlevel .setText(Data_parlevel.get(position));
holder.edittext_openingstock_baradmin.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus){
//final int position = v.getId();
final EditText Caption = (EditText) v;
str_Openingstock[position] = holder.edittext_openingstock_baradmin.getText().toString();
}
}
});
holder.edittext_reg_baradmin.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus){
str_Reg[position] = holder.edittext_reg_baradmin.getText().toString();
}
}
});
holder.edittext_intertransfer_baradmin.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus){
str_Intertransfer[position] = holder.edittext_intertransfer_baradmin.getText().toString();
}
}
});
holder.edittext_closingstock_baradmin.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus){
str_Closingstock[position] = holder.edittext_closingstock_baradmin.getText().toString();
//strings[position] = holder.edittext_openingstock_baradmin.getText().toString();
}
}
});
holder.edittext_remark_baradmin.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus){
//final int position = v.getId();
final EditText Caption = (EditText) v;
str_Remark[position] = holder.edittext_remark_baradmin.getText().toString();
}
}
});
} catch (Exception e) {
// TODO: handle exception
}
return convertView;
}
class ViewHolder {
EditText editText_id, editText_desc, editText_uom, editText_parlevel,
edittext_openingstock_baradmin, edittext_reg_baradmin, edittext_intertransfer_baradmin,
edittext_closingstock_baradmin, edittext_remark_baradmin;
}
class ListItem {
String caption;
}
}
and in logcat i can see
02-12 14:51:04.164: I/Editor(18219): setup window support handles
have you tried setting this property in your listview
android:descendantFocusability="beforeDescendants"
I will suggest you to listen activity onfocusChange rather then listening every editbox this might remove flicker (rather executing all editbox onfcoucs change methods its been capture once.)
#Override
public void onFocusChange(View v, boolean hasFocus) {
switch(v.getId()){
case r.id.editText_id:
break;
}
}

Categories

Resources