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();
Related
I'm developing an android app which has a custom listview with a checkbox. I want to pass all the checked items from one activity to another. how should I pass them? and where should I manage the checkbox (to get all the checked items) in the custom adapter or the activity?
Note: I retrieve all the data from my server using json response.
Here's my Model :
public class Groups {
public String name;
public boolean selected= false;
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;
}
public Groups() {
}
}
My Adapter:
public class AdapterMainActivity extends BaseAdapter{
Activity activity;
private LayoutInflater inflater;
List<Groups> groupsList;
public AdapterMainActivity(Activity activity, List<Groups> groupses) {
this.activity = activity;
this.groupsList = groupses;
}
#Override
public int getCount() {
return groupsList.size();
}
#Override
public Object getItem(int position) {
return groupsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_list, null);
TextView name = (TextView) convertView.findViewById(R.id.textViewName);
final CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
final Groups groups = groupsList.get(position);
name.setText(groupsList.get(position).getName());
checkBox.setChecked(groups.selected);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
groups.selected = isChecked;
MainActivity.getInstance().updateArrayList(groupsList);
}
});
}
return convertView;
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
ListView listViewGroups;
Button buttonSentToActivity;
List<Groups> groupsList;
List<Groups> resultGroupList;
ArrayList<Boolean> areChecked;
List<String> finalArray;
private AdapterMainActivity adapterMainActivity;
static MainActivity yourActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
yourActivity = this;
groupsList= new ArrayList<Groups>();
resultGroupList= new ArrayList<Groups>();
ReadGroup(37);
adapterMainActivity = new AdapterMainActivity(this, groupsList);
listViewGroups = (ListView) findViewById(R.id.listViewGroups);
listViewGroups.setAdapter(adapterMainActivity);
buttonSentToActivity = (Button) findViewById(R.id.buttonSendTo2Activity);
buttonSentToActivity.setOnClickListener(buttonSentToActivityListener);
Log.e("Group list size ", String.valueOf(groupsList.size()));
finalArray = new ArrayList<>();
for (int i = 0; i < resultGroupList.size(); i++) {
if (resultGroupList.get(i).selected) {
finalArray.add(resultGroupList.get(i).getName());
Log.e("final array size", String.valueOf(finalArray.size()));
}
}
}
public void ReadGroup(long cid) {
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response.toString());
JSONArray readArray = jsonObject.getJSONArray("groups");
for (int i = 0; i < readArray.length(); i++) {
Log.e("i is: ", String.valueOf(i));
JSONObject jssonRow = readArray.getJSONObject(i);
String groupName = jssonRow.getString("name");
Groups groups = new Groups();
groups.setName(groupName);
Log.e("NAME is: ", groupName);
groupsList.add(groups);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapterMainActivity.notifyDataSetChanged();
}
};
Log.e("Client id is: ", String.valueOf(cid));
ReadGroupRequesr readGroupRequest = new ReadGroupRequesr(cid, responseListener);
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(readGroupRequest);
Log.e("out of the loop", "");
}
public static MainActivity getInstance() {
return yourActivity;
}
public void updateArrayList(List<Groups> arrayList) {
this.resultGroupList = arrayList;
}
View.OnClickListener buttonSentToActivityListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
//Bundle b= new Bundle();
//b.putStringArrayList("arrayList", (ArrayList<String>) finalArray);
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putStringArrayListExtra("arrayList", (ArrayList<String>) finalArray);
//intent.putExtras(b);
Log.e("final array size", String.valueOf(finalArray.size()));
startActivity(intent);
}
};
}
At the very first, manage your checkboxes :
In your activity class add a boolean array or arraylist having size same as your list array size and initialize it with all value as false initially :
String[] titlesArray;
ArrayList<Boolean> arrChecked;
// initialize arrChecked boolean array and add checkbox value as false initially for each item of listview
arrChecked = new ArrayList<Boolean>();
for (int i = 0; i < titles.size(); i++) {
arrChecked.add(false);
}
Now replace your adapter class with this :
class VivzAdapter extends ArrayAdapter<String> implements OnCheckedChangeListener {
Context context;
int[] images;
String[] titlesArray, descrptionArray;
List<Integer> positions = new ArrayList<Integer>();
ArrayList<Boolean> arrChecked;
VivzAdapter(Context context, String[] titles, int[] images, String[] description, ArrayList<Boolean> arrChecked) {
super(context, R.layout.single_row, R.id.textView1, titles);
this.context = context;
this.images = images;
this.titlesArray = titles;
this.descrptionArray = description;
this.arrChecked = arrChecked;
}
class MyViewHolder {
ImageView myImage;
TextView myTitle;
TextView myDescription;
CheckBox box;
MyViewHolder(View v) {
myImage = (ImageView) v.findViewById(R.id.imageView1);
myTitle = (TextView) v.findViewById(R.id.textView1);
myDescription = (TextView) v.findViewById(R.id.textView2);
box = (CheckBox) v.findViewById(R.id.checkBox1);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MyViewHolder holder = null;
if (row == null) {
// 1.Âștime
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//row contem RelativeLayout(root) em single_row.xml
row = inflater.inflate(R.layout.single_row, parent, false);
holder = new MyViewHolder(row);
row.setTag(holder);
//Log.d("VIVZ", "Creating a new Row");
} else {
//reciclamos aqui, qeremos usar antigo objecto holder
holder = (MyViewHolder) row.getTag();
//Log.d("VIVZ", "Recycling stuff");
}
holder.myImage.setImageResource(images[position]);
holder.myTitle.setText(titlesArray[position]);
holder.myDescription.setText(descrptionArray[position]);
//set position as id
holder.box.setId(position);
//set onClickListener of checkbox rather than onCheckedChangeListener
holder.box.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int id = v.getId();
if (arrChecked.get(id)) {
//if checked, make it unchecked
arrChecked.set(id, false);
} else {
//if unchecked, make it checked
arrChecked.set(id, true);
}
}
});
//set the value of each checkbox from arrChecked boolean array
holder.box.setChecked(arrChecked.get(position));
return row;
}
}
After that, implement click listener of send button say btnSend button (I am considering that you are sending your data from one activity to another activity on click of send button) :
btnSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<String> arrTempList = new ArrayList();
for(int i=0; i<titles.size(); i++){
if(arrChecked.get(i) == true){
arrTempList.add(titles[i]);
}
}
// here you can send your arrTempList which is having checked items only
}
});
Here's the solution for this Question:
My adapter:
public class ChooseContactsAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
public ArrayList<Contacts> contactsList;
public CheckBox checkBoxAdapter;
public ChooseContactsAdapter(Activity activity, ArrayList<Contacts> group) {
this.activity = activity;
this.contactsList = group;
}
#Override
public int getCount() {
return contactsList.size();
}
#Override
public Object getItem(int position) {
return contactsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_choose_contacts_sms,
null);
final TextView fNAme = (TextView) convertView.findViewById(R.id.textViewCustomSMSSelectContactFName);
TextView LName = (TextView) convertView.findViewById(R.id.textViewCustomSMSSelectContactLName);
checkBoxAdapter = (CheckBox) convertView.findViewById(R.id.checkBoxSelectContact);
checkBoxAdapter.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
CheckBox cb = (CheckBox) view;
Contacts contacts = (Contacts) cb.getTag();
contacts.setSelected(cb.isChecked());
Toast.makeText(activity.getApplicationContext(),
"Clicked on Checkbox: " + cb.getText() +
" is " + cb.isChecked(),
Toast.LENGTH_LONG).show();
}
});
final Contacts contacts = contactsList.get(position);
fNAme.setText(contacts.getContactFName());
LName.setText(contacts.getContactLName());
checkBoxAdapter.setChecked(contacts.isSelected());
checkBoxAdapter.setTag(contacts);
}
return convertView;
}
}
In my activity I have button to go from 1 activity to the 2 activity:
private View.OnClickListener buttonSubmitGroupListener =new View.OnClickListener() {
#Override
public void onClick(View view) {
List <Integer> contactsIDArray= new ArrayList<Integer>();
List<Contacts> arrayOfContacts= chooseContactsAdapter.contactsList;
for(int i=0; i< arrayOfContacts.size(); i++){
Contacts contacts= arrayOfContacts.get(i);
if(contacts.isSelected()==true){
contactsIDArray.add(contacts.getContactID());
}
}
for (int i = 0; i < contactsIDArray.size(); i++) {
Log.e("Id Array size ", String.valueOf(contactsIDArray.size()));
Log.e("Selected id ", String.valueOf(contactsIDArray.get(i)));
}
intent = new Intent(getApplicationContext(), SendSMSActivity.class);
Bundle b = new Bundle();
b.putIntegerArrayList("checkedContacts", (ArrayList<Integer>) contactsIDArray);
intent.putExtras(b);
startActivity(intent);
}
};
Second Activity add this code:
Bundle b = getIntent().getExtras();
List<Integer> result = new ArrayList<Integer>();
result = b.getIntegerArrayList("checkedContacts");
I want to save the positions of selected checkboxes on button click in database and close the app. And using these positions, restore the selected states of checkboxes when I open the app. Can anyone help me in this?
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);
pref = getSharedPreferences("MYPref", Context.MODE_PRIVATE);
str1 = pref.getString("key","");
List<String> list = Arrays.asList(str1.split(","));
System.out.println(list);
displayListView();
checkButtonClick();
}
private void displayListView()
{
//HERE I WANT TO RETRIEVE THE POSITIONS TO SET EARLIER SELECTED CHECKOX AGAIN SELECTED
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");
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());
// HERE I WANT TO SAVE POSITIONS
}
}
Toast.makeText(getApplicationContext(),
responseText, Toast.LENGTH_LONG).show();
}
});
}
}
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);
}
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;
}
}
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;
}
}
Is your data going to be huge? if Yes, use SQLlite. If only like what you stated, only for loading up app parameters, Share preference is better. Try below functions.
public static <T> T readPreference(Class<T> clazz, String key) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(Application.getInstance());
if (clazz.equals(String.class)) {
return (T) preferences.getString(key, "");
} else if (clazz.equals(Integer.class)) {
return (T) (Integer) preferences.getInt(key, 0);
} else if (clazz.equals(Boolean.class)) {
return (T) (Boolean) preferences.getBoolean(key, false);
} else if (clazz.equals(Float.class)) {
return (T) (Float) preferences.getFloat(key, -0.0f);
}
return null;
}
public static void writePreference(String key, Object value) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(Application.getInstance());
SharedPreferences.Editor edit = preferences.edit();
if (value instanceof Integer) {
edit.putInt(key, (Integer) value);
} else if (value instanceof Boolean) {
edit.putBoolean(key, (Boolean) value);
} else if (value instanceof Float) {
edit.putFloat(key, (Float) value);
} else if (value instanceof Long) {
edit.putLong(key, (Long) value);
} else if (value instanceof String) {
edit.putString(key, (String) value);
}
edit.apply();
}
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.
i have an issue when i try to delete multiple checked items from my listView. If i start deleting from down to up items are removed from my list, but there is a problem when i do it from up to down or if random items are checked. The problem is the checked items are not deleted, but the unchecked items are deleted.
public class MainActivity extends ActionBarActivity {
private EditText etn,etl,etd;
private Button add;
private Button rmv;
private ListView listView;
private ArrayList<Data> list;
private MyCustomAdapter dataAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
listView = (ListView) findViewById(R.id.listView1);
list = new ArrayList<Data>();
add = (Button) findViewById(R.id.btn_add);
etn = (EditText) findViewById(R.id.edit_name);
eta = (EditText) findViewById(R.id.edit_lastname);
etd = (EditText) findViewById(R.id.edit_document);
rmv = (Button) findViewById(R.id.btn_delete);
displayView();
}
public class Data {
long document;
String name;
String lastname;
boolean selected = false;
public Data(long document, String name, String lastname, boolean selected){
this.document=document;
this.name=nom;
this.lastname=lastname;
this.selected = selected;
}
public String getName(){
return name;
}
public String getLastName(){
return lastname;
}
public long getDocument(){
return document;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
public void displayView(){
String name = etn.getText().toString();
String lastname= eta.getText().toString();
long document = Integer.valueOf(etd.getText().toString());
Data edata = new Data(document,name,lastname,false);
list.add(edata);
dataAdapter = new MyCustomAdapter(this,
R.layout.list_info, list);
listView.setAdapter(dataAdapter);
}
public void delete(View view){
deleteListItem();
}
private void deleteListItem(){
if(list.isEmpty()){
Toast.makeText(getApplicationContext(),
"No items to delete.",
Toast.LENGTH_LONG).show();
return;
}
int itemCount = listView.getCount();
for(int i=itemCount - 1 ; i>=0; i--){
Data aux = list.get(i);
if(aux.isSelected()){
dataAdapter.remove(aux);
}
}
dataAdapter.notifyDataSetChanged();
}
private class MyCustomAdapter extends ArrayAdapter<Data> {
private ArrayList<Data> list;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Data> list) {
super(context, textViewResourceId, list);
this.list = new ArrayList<Data>();
this.list.addAll(list);
}
private class ViewHolder {
TextView name;
TextView lname;
TextView doc;
CheckBox ck;
}
#Override
public View getView(int position, View convertView, ViewGroupparent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.list_info, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.ck = (CheckBox) convertView.findViewById(R.id.checkBox1);
holder.lname = (TextViewconvertView.findViewById(R.id.lastname);
holder.doc = (TextView)convertView.findViewById(R.id.document);
convertView.setTag(holder);
holder.ck.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v ;
Data edata = (Data) cb.getTag();
Toast.makeText(getApplicationContext(),
"Checkbox: " + cb.getText() +
" is " + cb.isChecked(),
Toast.LENGTH_LONG).show();
edata.setSelected(cb.isChecked());
}
});
}
else {
holder = (ViewHolder) convertView.getTag();
}
Data aux = list.get(position);
long document = aux.getDocument();
holder.doc.setText("Doc:" + Long.toString(document));
holder.name.setText (" " + "Name:" + aux.getName()+ " ");
holder.lname.setText("Last name:" + aux.getLastName());
holder.ck.setTag(aux);
holder.ck.setChecked(aux.isSelected());
return convertView;
}
}
I think problem resides in this block :
int itemCount = listView.getCount();
for(int i=itemCount - 1 ; i>=0; i--){
Data aux = list.get(i);
if(aux.isSelected()){
dataAdapter.remove(aux);
}
}
Try like this :
int itemCount = listView.getCount();
for(int i=itemCount - 1 ; i>=0; i--){
Data aux = dataAdapter.getItem(i);
if(aux.isSelected()){
dataAdapter.remove(aux);
}
}
Note : I am not sure, Please try and let me know the result .:)
Hello I am new in android
I have some dificulty to add element in daynamic listview.
When I click on TextView(tv) it should be add element at the end of the ArrayList but when i scroll down to the listview it crashed with indexoutofbound exception.
public class PosterList extends Activity
{
MyCustomAdapter dataAdapter = null;
ArrayList<Country> countryList = new ArrayList<Country>();
TextView tv;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.posterlist);
//Click on textview to add element in contrylist
tv = (TextView) findViewById(R.id.myFilter);
tv.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Country country = new Country("df","df","df","m");
countryList.add(country);
dataAdapter.notifyDataSetChanged();
}
});
displayListView();
}
private void displayListView()
{
//Parse my JSON and store it in to different arrays
for(int k=0;k<len;k++)
{
Country country = new Country(subcategory[k],caseid[k],time[k],newpost[k]);
countryList.add(country);
}
dataAdapter = new MyCustomAdapter(this,R.layout.country_info, countryList);
ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
Country country = (Country) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
country.getContinent(), Toast.LENGTH_SHORT).show();
}
});
}
private class MyCustomAdapter extends ArrayAdapter<Country>
{
private ArrayList<Country> originalList;
private ArrayList<Country> countryList;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Country> countryList) {
super(context, textViewResourceId, countryList);
this.countryList = new ArrayList<Country>();
this.countryList.addAll(countryList);
this.originalList = new ArrayList<Country>();
this.originalList.addAll(countryList);
}
private class ViewHolder
{
TextView code;
TextView name;
TextView continent;
TextView region;
}
#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)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.country_info, null);
holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.code);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.continent = (TextView) convertView.findViewById(R.id.continent);
holder.region = (TextView) convertView.findViewById(R.id.region);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
Country country = countryList.get(position);
holder.code.setText(country.getCode());
holder.name.setText(country.getName());
holder.continent.setText(country.getContinent());
holder.region.setText(country.getRegion());
return convertView;
}
}
}
Here is my Country class,can anybody help me out what is wrong with this code?
`enter code here`public class Country {
String code = null;
String name = null;
String continent = null;
String region = null;
public Country(String code, String name, String continent, String region) {
super();
this.code = code;
this.name = name;
this.continent = continent;
this.region = region;
}
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 String getContinent() {
return continent;
}
public void setContinent(String continent) {
this.continent = continent;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
#Override
public String toString() {
return code + " " + name + " "
+ continent + " " + region;
}
Get rid of these fields in your adapter
private ArrayList<Country> originalList;
private ArrayList<Country> countryList;
You are modifying the countryList that is being passed to the super call in your adapter but you are reading from the countryList that is stored as a field inside of your adapter which never gets modified when you add a new country!
You are creating a copy of your original countrylist.. but you never modify the copy after creating it