I am trying to implement a search option for listview which also has a checkbox in each row.
I am getting the friends list from Google plus account and showing them in the listview
using customAdapter.
The friend's name, image and id are stored in hashmap.
The problem for e.g.
I select first and second item and then type a text in the search box - the results are shown with the first item and second item being checked automatically.
Or another example:
When I select an item in search results and now clear the search text the checkbox gets cleared too.
How do I fix this issue?
Friends.java
ArrayList<HashMap<String, String>> friendList;
ArrayList<HashMap<String, String>> searchResults;
static boolean[] isChecked;
static boolean[] isSearchChecked;
private EditText searchText;
static int listPerson = 1;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
setContentView(R.layout.activityfriends);
res = this.getResources();
searchText = (EditText) findViewById(R.id.searchText);
searchText.setOnClickListener(this);
friendList = new ArrayList<HashMap<String, String>>();
searchResults = new ArrayList<HashMap<String, String>>();
list = (ListView)findViewById(R.id.friend_list);
searchText.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable s)
{
}
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
listofperson = 2;
searchResults.clear();
if (friendList.size() > 0 )
{
for (HashMap<String, String> map : friendList)
{
if(map.get(KEY_DISPLAY_NAME).toLowerCase().contains(s.toString().toLowerCase()))
{
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put(KEY_ID, map.get(KEY_ID));
hashMap.put(KEY_DISPLAY_NAME, map.get(KEY_DISPLAY_NAME));
hashMap.put(KEY_IMAGEPROFILE_URL, map.get(KEY_IMAGEPROFILE_URL));
searchResults.add(hashMap);
isSearchChecked = new boolean[searchResults.size()];
for (int i = 0; i < isSearchChecked.length; i++)
{
isSearchChecked[i] = false;
}
}
}
adapter= new FriendsAdapter(Friends.this, searchResults);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
});
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener()
{
private CheckBox cb;
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
if (listPerson == 1)
{
String person_ID = friendList.get(position).get(KEY_ID);
String person_DISPLAY_NAME = friendList.get(position).get(KEY_DISPLAY_NAME);
cb = (CheckBox) view.findViewById(R.id.checkBox);
//cb.setChecked(true);
cb.performClick();
if (cb.isChecked())
{
//add to be database
}
else if (!cb.isChecked())
{
//remove from database
}
}
else
{
String SearchResult_person_ID = searchResults.get(position).get(KEY_ID);
String SearchRResult_person_DISPLAY_NAME = searchResults.get(position).get(KEY_DISPLAY_NAME);
cb = (CheckBox) view.findViewById(R.id.checkBox);
//cb.setChecked(true);
cb.performClick();
if (cb.isChecked())
{
//add to database
}
else if (!cb.isChecked())
{
//remove from database
}
}
}
});
}
OnResult of Gplus client I have the following line of code:
PersonBuffer personBuffer = peopleData.getPersonBuffer();
try
{
friendsCount = personBuffer.getCount();
for (int i = 0; i < friendsCount; i++)
{
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_ID, personBuffer.get(i).getId());
map.put(KEY_DISPLAY_NAME, personBuffer.get(i).getDisplayName());
map.put(KEY_IMAGEPROFILE_URL, personBuffer.get(i).getImage().getUrl());
friendList.add(map);
}
}
finally
{
personBuffer.close();
}
if (friendCount > 0)
{
isChecked = new boolean[peopleCount];
for (int i = 0; i < isChecked.length; i++)
{
isChecked[i] = false;
}
adapter = new FriendsAdapter(this, friendList);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
FriendsAdapter.java
public class FriendsAdapter extends BaseAdapter
{
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
public FriendsAdapter(Activity a, ArrayList<HashMap<String, String>> d)
{
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount()
{
return data.size();
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LinearLayout view = (LinearLayout) convertView;
if (view == null)
{
view = (LinearLayout) inflater.inflate(R.layout.friend_list_row, null);
}
HashMap<String, String> listFriends = new HashMap<String, String>();
listFriends = data.get(position);
TextView friendsname = (TextView) view.findViewById(R.id.friendsName); // title
friendsname.setText(listFriends.get(Friends.KEY_DISPLAY_NAME));
ImageView thumb_image = (ImageView)view.findViewById(R.id.list_image); // thumb image
imageLoader.DisplayImage(listFriends.get(Friends.KEY_IMAGEPROFILE_URL), thumb_image);
CheckBox cBox = (CheckBox) view.findViewById(R.id.checkBox);
cBox.setOnCheckedChangeListener(null);
cBox.setChecked(InviteFriends.isChecked[position]);
cBox.setTag(Integer.valueOf(position));
cBox.setOnCheckedChangeListener(mListener);
return view;
}
OnCheckedChangeListener mListener = new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked)
{
Friends.isChecked[(Integer)buttonView.getTag()] = isChecked;
}
};
Related
I'm in learning about add view programmatically. But, I'm in confusing now.
I have data, there are idpatient, idheader. Patient can have more than one ID header. When I input idpatient, it will add listview (with custom adapter) programmatically. The number of listview is same with the number of ID header.
I want to set in each listview with data patient group by ID header..
So far, I add search view when loop adding listview, but when I input one ID header to seacrh view, all of listview will view the same data according to ID header in search view..
I'm sorry for the long explanation. Can anybody help me to solve this problem?
Thanks in advance
This is My Adapter :
/**
* Created by RKI on 11/9/2016.
*/
public class AdapterHistory extends BaseAdapter implements Filterable, View.OnClickListener {
private Activity activity;
LayoutInflater inflater;
HistoryHeaderActivity main;
public int count = 0;
Context context;
public ModelHistory product;
ArrayList<ModelHistory> mStringFilterList;
ModelHistory tempValues = null;
ValueFilter valueFilter;
public Cart cart;
public AdapterHistory(HistoryHeaderActivity main, ArrayList<ModelHistory> arraylist) {
this.main = main;
this.main.historyModel = arraylist;
mStringFilterList = arraylist;
}
#Override
public int getCount() {
return main.historyModel.size();
}
#Override
public Object getItem(int position) {
return main.historyModel.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
int pos = position;
final Cart carts = CartHelper.getCart();
View vi = convertView;
ViewHolderItem holder = new ViewHolderItem();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) main.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = inflater.inflate(R.layout.list_history, null);
holder.h_id = (TextView) vi.findViewById(R.id.id_header_);
holder.h_type = (TextView) vi.findViewById(R.id.servicetype_);
holder.h_qty = (TextView) vi.findViewById(R.id.qty_);
holder.h_ps_id = (TextView) vi.findViewById(R.id.patient_id);
holder.h_ps_name = (TextView) vi.findViewById(R.id.patient_);
holder.h_dokid = (TextView) vi.findViewById(R.id.doctor_id_);
holder.h_dokname = (TextView) vi.findViewById(R.id.doctor_);
holder.h_item = (TextView) vi.findViewById(R.id.item_);
holder.h_date = (TextView) vi.findViewById(R.id.date_);
holder.checkToCart = (CheckBox) vi.findViewById(R.id.checkBox);
holder.checkToCart.setTag(position);
holder.checkToCart.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag(); // Here we get the position that we have set for the checkbox using setTag.
tempValues.setSelected(isChecked);
}
});
vi.setTag(holder);
vi.setTag(R.id.checkBox, holder.checkToCart);
} else {
holder = (ViewHolderItem) vi.getTag();
}
if (main.historyModel.size() <= 0) {
holder.h_date.setText("No Data");
} else {
/*** Get each Model object from Arraylist ****/
tempValues = null;
tempValues = (ModelHistory) main.historyModel.get(position);
holder.h_id.setText(tempValues.getH_id());
holder.h_type.setText(tempValues.getH_service());
holder.h_qty.setText(tempValues.getH_qty());
holder.h_ps_name.setText(tempValues.getH_p_name());
holder.h_ps_id.setText(tempValues.getH_p_id());
holder.h_dokid.setText(tempValues.getH_d_id());
holder.h_dokname.setText(tempValues.getH_d_name());
holder.h_item.setText(tempValues.getH_item());
holder.h_date.setText(tempValues.getH_date());
holder.checkToCart.setTag(position);
holder.checkToCart.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
main.historyModel.get(position).setSelected(buttonView.isChecked());
}
});
holder.checkToCart.setChecked(main.historyModel.get(position).isSelected());
for (pos = 1; pos <= 1; pos++) {
main.u_pname = tempValues.getH_p_name();
main.u_pid = tempValues.getH_p_id();
main.u_service = tempValues.getH_service();
main.up_iddetail = tempValues.getH_id();
}
}
return vi;
}
#Override
public void onClick(View v) {
}
public static class ViewHolderItem {
TextView h_id, h_type, h_ps_id, h_ps_name, h_dokid, h_dokname, h_item, h_qty, h_date;
CheckBox checkToCart;
}
private List<TransactionsItem> getCartItems(Cart cart) {
List<TransactionsItem> cartItems = new ArrayList<>();
Map<Saleable, Integer> itemMap = cart.getItemWithQuantity();
for (Map.Entry<Saleable, Integer> entry : itemMap.entrySet()) {
TransactionsItem cartItem = new TransactionsItem();
cartItem.setProduct((ModelInventory) entry.getKey());
cartItem.setQuantity(entry.getValue());
cartItems.add(cartItem);
}
return cartItems;
}
#Override
public Filter getFilter() {
if (valueFilter == null) {
valueFilter = new ValueFilter();
}
return valueFilter;
}
private class ValueFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
List<ModelHistory> filterList = new ArrayList<ModelHistory>();
for (int i = 0; i < mStringFilterList.size(); i++) {
if ((mStringFilterList.get(i).getH_id().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
ModelHistory country = new ModelHistory(
mStringFilterList.get(i).getH_id(),
mStringFilterList.get(i).getH_p_id(),
mStringFilterList.get(i).getH_date(),
mStringFilterList.get(i).getH_p_name(),
mStringFilterList.get(i).getH_d_id(),
mStringFilterList.get(i).getH_d_name(),
mStringFilterList.get(i).getH_item(),
mStringFilterList.get(i).getH_qty(),
mStringFilterList.get(i).getH_service());
filterList.add(country);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = mStringFilterList.size();
results.values = mStringFilterList;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
main.historyModel = (ArrayList<ModelHistory>) results.values;
notifyDataSetChanged();
}
}
}
This is My Activity :
import com.mobileproject.rki.mobile_his_receipt.view.adapter.AdapterHistory;
import org.w3c.dom.*;
import java.io.Serializable;
import java.util.*;
public class HistoryHeaderActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
static final String URL = "http://.../GetDataInv";
static final String KEY_TABLE = "Table"; // parent node
static final String KEY_REG_ID = "Sales_Aptk_ID", KEY_DATE = "Sales_Aptk_Date",
KEY_PATIENT_ID = "Sales_Aptk_Patient_ID", KEY_SERVICE_ID = "Sales_Aptk_Type",
KEY_PATIENT_NAME = "Sales_Aptk_Patient_Name",
KEY_DOCTOR_ID = "Sales_Aptk_Doctor_ID", KEY_DOCTOR_NAME = "Sales_Aptk_Doctor_Name",
KEY_ITEM_ID = "Sales_Aptk_Detail_Item_ID", KEY_DETAIL_UNIT = "Sales_Aptk_Detail_Unit",
KEY_ITEM_QTY = "Sales_Aptk_Detail_Qty";
static final String KEY_ID_HEADER = "Sales_Aptk_ID";
static final String KEY_TABLE_INV = "Table"; // parent node
static final String KEY_ITEM_ID_INV = "Item_ID", KEY_ITEM_NAME = "Item_Name",
KEY_MAX_STOCK = "Item_Max_Stock";
public static final int DIALOG_DOWNLOAD_DATA_PROGRESS = 0, DIALOG_NO_DATA = 1,
DIALOG_DOWNLOAD_FULL_PHOTO_PROGRESS = 2;
Element e;
final Context context = this;
public List<ModelInventory> invModels;
private ProgressDialog mProgressDialog;
public static String id, up_iddetail, up_user, u_pid, u_pname, u_service, xml;
public ArrayList<ModelInventory> invModel = new ArrayList<ModelInventory>();
public ArrayList<ModelHistory> historyModel = new ArrayList<ModelHistory>();
public ArrayList<ModelIDHeader> headerModel = new ArrayList<ModelIDHeader>();
public Cart cart;
private Menu menu;
AdapterHistory hstAdpt, idhstAdpt;
private ProgressDialog progressDialog;
public ModelInventory productInv;
int mPosition, invPosition;
EditText p_id;
ListView listHistory;
XMLParser parser;
LinearLayout lm;
LinearLayout.LayoutParams params;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history_header);
lm = (LinearLayout) findViewById(R.id.linearMain);
params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
p_id = (EditText) findViewById(R.id.patientID);
listHistory = (ListView) findViewById(R.id.listhistory);
hstAdpt = new AdapterHistory(HistoryHeaderActivity.this, historyModel);
listHistory.setAdapter(hstAdpt);
listHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mPosition = position;
invPosition = position;
}
});
SharedPreferences login2 = getSharedPreferences("USERLOGIN", 0);
String doktername = login2.getString("userlogin", "0");
up_user = doktername;
p_id.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
onGetHistory();
}
});
}
/**
* Check Form Input
*
* #return
*/
private boolean isFormValid() {
String aTemp = p_id.getText().toString();
if (aTemp.isEmpty()) {
Toast.makeText(this, "Please Input Patient ID..", Toast.LENGTH_SHORT).show();
return false;
} else {
id = aTemp.toString();
}
return true;
}
protected void dismissDialogWait() {
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
public void onGetHistory() {
listHistory.setAdapter(null);
if (isFormValid()) {
GetDataHistoryTask syncTask = new GetDataHistoryTask();
syncTask.execute(new IntroductingMethod());
GetDataHeaderTask syncTaskHeader = new GetDataHeaderTask();
syncTaskHeader.execute(new IntroductingMethod());
}
}
private class GetDataHistoryTask extends AsyncTask<IntroductingMethod, String, String> {
#Override
protected String doInBackground(IntroductingMethod... params) {
IntroductingMethod REGService = params[0];
return REGService.getHistoryData(id);
}
#Override
protected void onPostExecute(String result) {
dismissDialogWait();
if (result != null) {
try {
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
if (Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
XMLParser parser = new XMLParser();
Document doc = parser.getDomElement(result); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_TABLE);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
ModelHistory add = new ModelHistory();
add.setH_id(parser.getValue(e, KEY_REG_ID));
add.setH_p_name(parser.getValue(e, KEY_PATIENT_NAME));
add.setH_p_id(parser.getValue(e, KEY_PATIENT_ID));
add.setH_service(parser.getValue(e, KEY_SERVICE_ID));
add.setH_date(parser.getValue(e, KEY_DATE));
add.setH_detail_unit(parser.getValue(e, KEY_DETAIL_UNIT));
add.setH_d_id(parser.getValue(e, KEY_DOCTOR_ID));
add.setH_d_name(parser.getValue(e, KEY_DOCTOR_NAME));
add.setH_item(parser.getValue(e, KEY_ITEM_ID));
add.setH_qty(parser.getValue(e, KEY_ITEM_QTY));
historyModel.add(add);
}
ShowAllContentHistory();
} catch (Exception e) {
Toast.makeText(HistoryHeaderActivity.this.getApplicationContext(),
"Koneksi gagal. Silahkan coba kembali.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(HistoryHeaderActivity.this.getApplicationContext(),
"Koneksi gagal. Silahkan coba kembali.", Toast.LENGTH_LONG).show();
}
}
}
private class GetDataHeaderTask extends AsyncTask<IntroductingMethod, String, String> {
#Override
protected String doInBackground(IntroductingMethod... params) {
IntroductingMethod REGService = params[0];
return REGService.getHistoryHeaderData(id);
}
#Override
protected void onPostExecute(String result) {
dismissDialogWait();
if (result != null) {
try {
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
if (Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
XMLParser parser = new XMLParser();
Document doc = parser.getDomElement(result); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_TABLE);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
ModelIDHeader add = new ModelIDHeader();
add.setIdSalesHeader(parser.getValue(e, KEY_ID_HEADER));
headerModel.add(add);
}
if(result.contains("<Sales_Aptk_Patient_ID>"+id+"</Sales_Aptk_Patient_ID>")){
Log.d("NilaiID ", id);
AddNewList();
}
else{
Log.d("Kenapayahh", id);
}
} catch (Exception e) {
Toast.makeText(HistoryHeaderActivity.this.getApplicationContext(),
"Koneksi gagal. Silahkan coba kembali.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(HistoryHeaderActivity.this.getApplicationContext(),
"Koneksi gagal. Silahkan coba kembali.", Toast.LENGTH_LONG).show();
}
}
}
public void AskUpdate(View v) {
if (hstAdpt.getCount() == 0) {
Toast.makeText(HistoryHeaderActivity.this.getApplicationContext(),
"Tidak ada rekaman pasien.", Toast.LENGTH_LONG).show();
} else {
SharedPreferences id_header = getSharedPreferences("IDSALESAPTK", 0);
SharedPreferences.Editor editorID = id_header.edit();
editorID.putString("idsalesaptk", up_iddetail);
editorID.commit();
SharedPreferences sendPref2 = getSharedPreferences("DATAPATIENTNAME", 0);
SharedPreferences.Editor editor2 = sendPref2.edit();
editor2.putString("datapatientname", u_pname);
editor2.commit();
editor2.clear();
SharedPreferences sendPref3 = getSharedPreferences("DATAPATIENTID", 0);
SharedPreferences.Editor editor3 = sendPref3.edit();
editor3.putString("datapatientid", u_pid);
editor3.commit();
editor3.clear();
SharedPreferences regID = getSharedPreferences("DATAREGID", 0);
String reg_ID = regID.getString("dataregid", "0");
SharedPreferences sendPref4 = getSharedPreferences("DATAREGID", 0);
SharedPreferences.Editor editor4 = sendPref4.edit();
editor4.putString("dataregid", reg_ID);
editor4.commit();
editor4.clear();
SharedPreferences sendPref1 = getSharedPreferences("DATASERVICE", 0);
SharedPreferences.Editor editor1 = sendPref1.edit();
editor1.putString("dataservice", u_service);
editor1.commit();
editor1.clear();
new LoadingDataAsync().execute();
}
}
public class LoadingDataAsync extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
updateDetail();
return null;
}
protected void onPostExecute(Void unused) {
dismissDialog(DIALOG_DOWNLOAD_DATA_PROGRESS);
removeDialog(DIALOG_DOWNLOAD_DATA_PROGRESS);
}
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_DATA_PROGRESS);
}
}
public void updateDetail() {
ArrayList<ModelHistory> candidateModelArrayList = new ArrayList<ModelHistory>();
for (ModelHistory model : historyModel) {
if (model.isSelected()) {
candidateModelArrayList.add(model);
}
}
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
if (Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
parser = new XMLParser();
xml = parser.getXmlFromUrl(URL);
Document doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName(KEY_TABLE_INV);
for (int i = 0; i < nl.getLength(); i++) {
e = (Element) nl.item(i);
ModelInventory add = new ModelInventory();
add.setItem_ID(parser.getValue(e, KEY_ITEM_ID_INV));
add.setItem_Name(parser.getValue(e, KEY_ITEM_NAME));
add.setItem_Max_Stock(parser.getValue(e, KEY_MAX_STOCK));
invModel.add(add);
}
invModels = new ArrayList<ModelInventory>();
invModels = invModel;
ArrayAdapter<ModelInventory> adptInv = new ArrayAdapter<ModelInventory>(context, android.R.layout.simple_spinner_dropdown_item, invModels);
ArrayAdapter<ModelHistory> adptChkItem = new ArrayAdapter<ModelHistory>(context, android.R.layout.simple_spinner_dropdown_item, candidateModelArrayList);
if (adptInv.isEmpty()) {
Toast.makeText(HistoryHeaderActivity.this, "Empty Patient", Toast.LENGTH_SHORT).show();
}
cart = CartHelper.getCart();
for (mPosition = 0; mPosition < adptChkItem.getCount(); mPosition++) {
ModelHistory historyItem = (ModelHistory) adptChkItem.getItem(mPosition);
for (int j = mPosition; j < adptInv.getCount(); j++) {
ModelInventory inventoryItem = (ModelInventory) adptInv.getItem(j);
if (candidateModelArrayList.get(mPosition).getH_item().equals(inventoryItem.getItem_ID())) {
if (cart.getProducts().toString().contains(inventoryItem.getItem_Name())) {
} else {
productInv = (ModelInventory) (Serializable) adptInv.getItem(j);
int qty = Integer.parseInt(historyItem.getH_qty());
cart.add(productInv, qty);
}
} else {
}
}
}
Intent i = new Intent(getBaseContext(), CartActivity.class);
i.putExtra("PersonID", "try");
startActivity(i);
}
#Override
protected Dialog onCreateDialog(int id) {
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
hstAdpt.getFilter().filter(newText);
idhstAdpt.getFilter().filter(newText);
return false;
}
public void AddNewList(){
ArrayAdapter<ModelIDHeader> adptIDHeader = new ArrayAdapter<ModelIDHeader>(context, android.R.layout.simple_spinner_dropdown_item, headerModel);
for(int count =0; count< adptIDHeader.getCount(); count++){
idhstAdpt = new AdapterHistory(HistoryHeaderActivity.this, historyModel);
ModelIDHeader idHeader = (ModelIDHeader) adptIDHeader.getItem(count);
Button btn = new Button(this);
btn.setId(count);
btn.setText(idHeader.getIdSalesHeader());
lm.addView(btn);
SearchView search = new SearchView(this);
search.setQuery(idHeader.getIdSalesHeader(), false);
search.setOnQueryTextListener(this);
lm.addView(search);
ListView tv = new ListView(this);
tv.setId(count);
tv.setLayoutParams(params);
tv.setDividerHeight(2);
tv.setAdapter(idhstAdpt);
lm.addView(tv);
}
}
public void ShowAllContentHistory() {
listHistory = (ListView) findViewById(R.id.listhistory);
hstAdpt = new AdapterHistory(HistoryHeaderActivity.this, historyModel);
listHistory.setAdapter(hstAdpt);
listHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_history_actions, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_logout) {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ClearPrefs();
logout();
Intent intent = new Intent(HistoryHeaderActivity.this, LoginActivity.class);
startActivity(intent);
}
})
.setNegativeButton("No", null)
.show();
return true;
}
if (id == R.id.action_home) {
Intent intent = new Intent(HistoryHeaderActivity.this, MainActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(HistoryHeaderActivity.this, MainActivity.class);
startActivity(intent);
}
public void ClearPrefs() {
}
public void logout() {
SharedPreferences preferences5 = getSharedPreferences("IDLOGIN", Context.MODE_PRIVATE);
SharedPreferences.Editor editor5 = preferences5.edit();
editor5.clear();
editor5.commit();
}
}
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");
Check:
I am trying to implement filter on my ListView. But I am facing a very strange kind of problem. If I type letter T in the EditText the ListView is getting filled with names starting from B , J. Please help.
public class MyCustomAdapter extends BaseAdapter implements Filterable {
Context mContext;
private LayoutInflater mInflater;
SparseBooleanArray mSparseBooleanArray;
private ArrayList<Map<String,String>> mAdapData = new ArrayList<Map<String, String>>();
private ArrayList<Map<String,String>> mOriginalData = new ArrayList<Map<String, String>>();
public MyCustomAdapter(Context mContext) {
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mSparseBooleanArray = new SparseBooleanArray();
}
public ArrayList<String> getCheckedItems() {
ArrayList<String> mTempArry = new ArrayList<String>();
for (int i = 0; i < mAdapData.size(); i++) {
if (mSparseBooleanArray.get(i)) {
Map<String, String> map = (Map<String, String>) mAdapData.get(i);
final String numbr = map.get("Phone").toString();
mTempArry.add(numbr);
}
}
return mTempArry;
}
#Override
public int getCount() {
return this.mAdapData.size();
}
public void addItem(String paramString1, String paramString2) {
Map<String, String> NameNumber = new HashMap<String, String>();
NameNumber.put("Name", paramString1);
NameNumber.put("Phone", paramString2);
this.mAdapData.add(NameNumber);
this.mOriginalData.add(NameNumber);
notifyDataSetChanged();
}
#SuppressWarnings("unchecked")
public Object getItem(int paramInt) {
return (ArrayList<Map<String, String>>) this.mAdapData.get(paramInt);
}
#Override
public long getItemId(int paramInt) {
return paramInt;
}
#Override
public View getView(final int paramInt, View paramView, ViewGroup paramViewGroup) {
ViewHolder viewHolder;
if (paramView == null) {
viewHolder = new ViewHolder();
paramView = mInflater.inflate(R.layout.multiplecontactview, null);
viewHolder.tvName = (TextView) paramView.findViewById(R.id.txtContactName);
viewHolder.tvNumber = (TextView) paramView.findViewById(R.id.txtContactNumber);
viewHolder.cb = (CheckBox) paramView.findViewById(R.id.checkBox1);
viewHolder.cb.setTag(paramInt);
viewHolder.cb.setChecked(mSparseBooleanArray.get(paramInt));
viewHolder.cb.setOnCheckedChangeListener(mCheckedChangeListener);
viewHolder.tvName.setTextColor(Color.BLACK);
viewHolder.tvNumber.setTextColor(Color.BLACK);
for (int i = 0; i < mAdapData.size(); i++) {
Map<String, String> map = (Map<String, String>) mAdapData.get(paramInt);
final String name = map.get("Name").toString();
Log.e("Name", name);
final String numbr = map.get("Phone").toString();
Log.e("Number", numbr);
viewHolder.tvName.setText(name);
viewHolder.tvNumber.setText(numbr);
}
paramView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) paramView.getTag();
}
return paramView;
}
OnCheckedChangeListener mCheckedChangeListener = new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked);
}
};
public static class ViewHolder {
TextView tvName;
TextView tvNumber;
CheckBox cb;
}
#Override
public Filter getFilter() {
return new MyContactFilter();
}
#SuppressLint("DefaultLocale")
private class MyContactFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList<Map<String, String>> mFilteredData = new ArrayList<Map<String, String>>();
if (!TextUtils.isEmpty(constraint)) {
for(int i = 0; i < mAdapData.size(); i++) {
Map<String, String> map = (Map<String, String>) mAdapData.get(i);
final String names = map.get("Name").toString();
final String numbr = map.get("Phone").toString();
if(names.toLowerCase().contains(constraint.toString().toLowerCase())) {
Map<String, String> FilNameNumber = new HashMap<String, String>();
FilNameNumber.put("Name", names);
FilNameNumber.put("Phone", numbr);
mFilteredData.add(FilNameNumber);
}
}
results.values = mFilteredData;
results.count = mFilteredData.size();
} else {
synchronized (mOriginalData) {
results.values = mOriginalData;
results.count = mOriginalData.size();
}
}
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence cs, FilterResults fr) {
mAdapData = (ArrayList<Map<String, String>>) fr.values;
notifyDataSetChanged();
}
}
}
Your problems come from the way you setup the getView() method and how you set the checked item in that SparseBooleanArray. I've edited your adapter's code and it should work now. The main changes are in the OnCheckedChangeListener field:
public class MyCustomAdapter extends BaseAdapter implements Filterable {
private Context mContext;
private LayoutInflater mInflater;
private SparseBooleanArray mSparseBooleanArray;
// from where do you get the data?
private ArrayList<Map<String, String>> mAdapData = new ArrayList<Map<String, String>>();
private ArrayList<Map<String, String>> mOriginalData = new ArrayList<Map<String, String>>();
public MyCustomAdapter(Context mContext) {
mInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mSparseBooleanArray = new SparseBooleanArray();
}
public ArrayList<String> getCheckedItems() {
ArrayList<String> mTempArry = new ArrayList<String>();
for (int i = 0; i < mAdapData.size(); i++) {
if (mSparseBooleanArray.get(i)) {
Map<String, String> map = (Map<String, String>) mAdapData
.get(i);
final String numbr = map.get("Phone");
mTempArry.add(numbr);
}
}
return mTempArry;
}
#Override
public int getCount() {
return this.mAdapData.size();
}
public void addItem(String paramString1, String paramString2) {
Map<String, String> NameNumber = new HashMap<String, String>();
NameNumber.put("Name", paramString1);
NameNumber.put("Phone", paramString2);
mAdapData.add(NameNumber);
mOriginalData.add(NameNumber);
notifyDataSetChanged();
}
#SuppressWarnings("unchecked")
public Object getItem(int paramInt) {
return (ArrayList<Map<String, String>>) this.mAdapData.get(paramInt);
}
#Override
public long getItemId(int paramInt) {
return paramInt;
}
#Override
public View getView(final int paramInt, View paramView,
ViewGroup paramViewGroup) {
ViewHolder viewHolder;
if (paramView == null) {
viewHolder = new ViewHolder();
paramView = mInflater.inflate(R.layout.adapters_specialfilterrow,
paramViewGroup, false);
viewHolder.tvName = (TextView) paramView
.findViewById(R.id.textView1);
viewHolder.tvNumber = (TextView) paramView
.findViewById(R.id.textView2);
viewHolder.cb = (CheckBox) paramView.findViewById(R.id.checkBox1);
paramView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) paramView.getTag();
}
viewHolder.cb.setTag(paramInt);
viewHolder.cb.setOnCheckedChangeListener(null);
viewHolder.cb.setChecked(mSparseBooleanArray.get(paramInt));
viewHolder.cb.setOnCheckedChangeListener(mCheckedChangeListener);
viewHolder.tvName.setTextColor(Color.BLACK);
viewHolder.tvNumber.setTextColor(Color.BLACK);
Map<String, String> map = (Map<String, String>) mAdapData.get(paramInt);
final String name = map.get("Name");
final String numbr = map.get("Phone");
viewHolder.tvName.setText(name);
viewHolder.tvNumber.setText(numbr);
return paramView;
}
OnCheckedChangeListener mCheckedChangeListener = new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// get the item from the current mAdapData
Map<String, String> item = mAdapData.get((Integer) buttonView
.getTag());
int position = -1;
// see where is the item placed in the mOriginalData and use that
// position
for (int i = 0; i < mOriginalData.size(); i++) {
final Map<String, String> tmp = mOriginalData.get(i);
if (tmp.get("Name").toLowerCase().equals(item.get("Name").toLowerCase())) {
position = i;
break;
}
}
mSparseBooleanArray.put(position, isChecked);
}
};
public static class ViewHolder {
TextView tvName;
TextView tvNumber;
CheckBox cb;
}
#Override
public Filter getFilter() {
return new MyContactFilter();
}
#SuppressLint("DefaultLocale")
private class MyContactFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList<Map<String, String>> mFilteredData = new ArrayList<Map<String, String>>();
if (!TextUtils.isEmpty(constraint)) {
for (int i = 0; i < mAdapData.size(); i++) {
Map<String, String> map = (Map<String, String>) mAdapData
.get(i);
final String names = map.get("Name");
final String numbr = map.get("Phone");
if (names.toLowerCase().contains(
constraint.toString().toLowerCase())) {
Map<String, String> FilNameNumber = new HashMap<String, String>();
FilNameNumber.put("Name", names);
FilNameNumber.put("Phone", numbr);
mFilteredData.add(FilNameNumber);
}
}
results.values = mFilteredData;
results.count = mFilteredData.size();
} else {
synchronized (mOriginalData) {
results.values = mOriginalData;
results.count = mOriginalData.size();
}
}
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence cs, FilterResults fr) {
mAdapData = (ArrayList<Map<String, String>>) fr.values;
notifyDataSetChanged();
}
}
}
I have also implemented filter List View in my application. For that, I just need a snippet of code. Check it, if it helps.
editText.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
}
public void afterTextChanged(Editable arg0) {
sendToList.this.adapter.getFilter().filter(arg0);
}
});
in the getView() method , you didn't update the UI to have the values of the filtered results .
so it returned views with old results .
just before return paramView , update the view's data to what you have in the filtered results , and remove it from the preparation of the viewHolder , since this is called only a few times .
EDIT:
here's my correction of the code . i think it will fix it:
#Override
public View getView(final int paramInt, View paramView, ViewGroup paramViewGroup) {
ViewHolder viewHolder;
if (paramView == null) {
viewHolder = new ViewHolder();
paramView = mInflater.inflate(R.layout.multiplecontactview, null);
viewHolder.tvName = (TextView) paramView.findViewById(R.id.txtContactName);
viewHolder.tvNumber = (TextView) paramView.findViewById(R.id.txtContactNumber);
viewHolder.cb = (CheckBox) paramView.findViewById(R.id.checkBox1);
viewHolder.tvName.setTextColor(Color.BLACK);
viewHolder.tvNumber.setTextColor(Color.BLACK);
paramView.setTag(viewHolder);
viewHolder.cb.setOnCheckedChangeListener(mCheckedChangeListener);
} else {
viewHolder = (ViewHolder) paramView.getTag();
}
viewHolder.cb.setTag(paramInt);
viewHolder.cb.setChecked(mSparseBooleanArray.get(paramInt));
Map<String, String> map = (Map<String, String>) mAdapData.get(paramInt);
final String name = map.get("Name").toString();
Log.e("Name", name);
final String numbr = map.get("Phone").toString();
Log.e("Number", numbr);
viewHolder.tvName.setText(name);
viewHolder.tvNumber.setText(numbr);
return paramView;
}
EDIT:
here's a sample of how i handled the filtering :
#Override
public Filter getFilter()
{
final Filter filter=new Filter()
{
#Override
protected FilterResults performFiltering(final CharSequence constraint)
{
_lastFilterConstraint=constraint;
if(TextUtils.isEmpty(constraint))
return null;
final String constraintToCheck=constraint.toString().toLowerCase(Locale.getDefault());
final FilterResults results=new FilterResults();
// <- here i do the filtering itself and later put the results into "results"
results.values=values;
results.count=values.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(final CharSequence constraint,final FilterResults results)
{
_filteredItems==null ? null : (ArrayList<Item>)results.values;
notifyDataSetChanged();
}
};
return filter;
}
#Override
public int getCount()
{
if(_filteredItems!=null)
return _filteredItems.size();
return _originalItems.size();
}
#Override
public Item getItem(final int position)
{
if(_filteredItems!=null)
{
if(position<_filteredItems.size())
return _filteredItems.get(position);
return null;
}
if(position<_originalItems.size())
return _originalItems.get(position);
return null;
}
#Override
public View getView(final int position,final View convertView,final ViewGroup parent)
{
final View inflatedView;
final ViewHolder viewHolder;
if(convertView==null)
{
//<- here i inflate the view into the inflatedView
}
else
{
inflaterView=convertView;
viewHolder=(ViewHolder)inflaterView.getTag();
}
// <- here i use getItem and update the view according to its data .
return inflaterView;
}
Hi i am new to android.
1) I have a listview with names and checkboxes. I want to have a search function on this list where the user can search for a specific name.
2) I want the user to be able to select all the names in the listview with one click. When the user press on the selectAll button all the checkboxes should be checked.
I am a total beginner and totally confused.
Thanks
public class NewstipsActivity extends Activity {
CheckboxAdapter listItemAdapter;
ArrayList<String> listData;
Button getValue;
Button getchoice;
Button selectAll;
EditText edt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getchoice = (Button) findViewById(R.id.getchoice);
getValue = (Button)findViewById(R.id.get_value);
selectAll = (Button)findViewById(R.id.selectAll);
edt=(EditText)findViewById(R.id.EditText01);
ListView list = (ListView) findViewById(R.id.list);
ArrayList<HashMap<String, Object>> listData = new ArrayList<HashMap<String,Object>>();
JSONObject json = getJSON.getJSONfromURL("http://test.com/myurl.php");
try {
JSONArray results = json.getJSONArray("results");
for(int i = 0; i < results.length(); i++){
// creating new HashMap
HashMap<String, Object> map=new HashMap<String, Object>();
JSONObject e = results.getJSONObject(i);
// adding each child node to HashMap key => value
map.put("n_id", String.valueOf(i));
map.put("friend_image", R.drawable.icon);
map.put("friend_username", " " + e.getString("n_newspaper"));
map.put("friend_id", " " + e.getString("n_id"));
map.put("selected", false);
listData.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
listItemAdapter = new CheckboxAdapter(this, listData);
list.setAdapter(listItemAdapter);
//problem1 search
list.setTextFilterEnabled(true);
edt.addTextChangedListener(new TextWatcher()
{
#Override
public void onTextChanged( CharSequence s, int arg1, int arg2, int arg3)
{
Toast.makeText (NewstipsActivity.this, "On Search", Toast.LENGTH_LONG).show();
}
#Override
public void beforeTextChanged( CharSequence arg0, int arg1, int arg2, int arg3)
{
}
#Override
public void afterTextChanged( Editable arg0)
{
}
});
getValue.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
HashMap<Integer, Boolean> state =listItemAdapter.state;
String options="Newspapers: ";
for(int j=0; j<listItemAdapter.getCount(); j++){
System.out.println("state.get("+j+")=="+state.get(j));
if(state.get(j)!=null){
#SuppressWarnings("unchecked")
HashMap<String, Object> map=(HashMap<String, Object>) listItemAdapter.getItem(j);
String username=map.get("friend_username").toString();
String id=map.get("friend_id").toString();
options+="\n"+id+"."+username;
}
}
Toast.makeText(getApplicationContext(), options, Toast.LENGTH_LONG).show();
Intent intent = new Intent(NewstipsActivity.this, NewstipsPhoto.class);
startActivity(intent);
}
});
getchoice.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(NewstipsActivity.this, NewstipsPhoto.class);
startActivity(intent);
}
});
selectAll.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public class CheckboxAdapter extends BaseAdapter {
Context context;
ArrayList<HashMap<String, Object>> listData;
HashMap<Integer, Boolean> state = new HashMap<Integer, Boolean>();
public CheckboxAdapter(Context context, ArrayList<HashMap<String, Object>> listData) {
this.context = context;
this.listData = listData;
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater mInflater = LayoutInflater.from(context);
convertView = mInflater.inflate(R.layout.item, null);
ImageView image = (ImageView) convertView.findViewById(R.id.friend_image);
image.setBackgroundResource((Integer) listData.get(position).get("friend_image"));
TextView username = (TextView) convertView.findViewById(R.id.friend_username);
username.setText((String) listData.get(position).get("friend_username"));
TextView id = (TextView) convertView.findViewById(R.id.friend_id);
id.setText((String) listData.get(position).get("friend_id"));
CheckBox check = (CheckBox) convertView.findViewById(R.id.selected);
check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if (isChecked) {
state.put(position, isChecked);
} else {
state.remove(position);
}
}
});
check.setChecked((state.get(position) == null ? false : true));
return convertView;
}
}
}
I am trying to restore the previous state of my Checkboxes. I have nearly 20 checkbox in my Activity and what i want is when i restart my app, all the checkbox should be checked if it was checked before exiting the app. As i am using a custom adapter so i found it very difficult to achieve.
Here is my adapter's code -
public class IconAdapter extends BaseAdapter
{
private Activity activity;
private Object[] data;
private ArrayList<HashMap<String,String>> listItems;
public static LayoutInflater inflater = null;
private PackageManager pm;
public ArrayList<Boolean> itemChecked = null;
public ArrayList<String> itemSelected = new ArrayList<String>();
public ArrayList<CheckBox> ctv = new ArrayList<CheckBox>();
//TextView textView;
CheckBox cb;
//ImageView imageView;
public CompleteTaskManager ctm = new CompleteTaskManager();
public IconAdapter(Activity a, ArrayList<HashMap<String,String>> items)
{
activity = a;
listItems = items;
data = items.toArray();
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
pm = a.getPackageManager();
if(itemChecked==null){
itemChecked = new ArrayList<Boolean>();
for(int i = 0; i < items.size(); i++)
{
itemChecked.add(i,false);
}}
for(int i = 0; i < items.size(); i++)
{
itemSelected.add(i," ");
}
for(int i = 0; i < items.size(); i++)
{
cb = new CheckBox(a);
ctv.add(i,cb);
}
}
public int getCount() {
return listItems.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder{
public TextView textView;
public ImageView imageView;
public CheckBox checkBox;
}
public View getView(final int position, View convertView, ViewGroup parent)
{
View row = convertView;
final ViewHolder holder;
if(convertView==null)
{
row = inflater.inflate(R.layout.item, parent, false);
holder = new ViewHolder();
holder.textView = (TextView)row.findViewById(R.id.text1);
holder.checkBox = (CheckBox)row.findViewById(R.id.check); holder.checkBox.setChecked(itemChecked.get(position));
holder.imageView = (ImageView)row.findViewById(R.id.image);
row.setTag(holder);
}
else
{
holder = (ViewHolder)row.getTag();
}
String s = data[position].toString();
String[] tokens = s.split(",");
String[] mToken = tokens[0].split("=");
String taskName = mToken[1];
holder.textView.setText(taskName);
String[] mTokens = tokens[1].split("=");
final String pkgName = mTokens[1].substring(0, (mTokens[1].length() - 1));
holder.checkBox.setTag(position);
//this is how i am trying to restore the checked checkboxes.
**for(int i = 0; i < itemSelected.size(); i++)
{
if(itemSelected.contains(pkgName))
{
holder.checkBox.setChecked(true);
}
}**
ctv.set(position,holder.checkBox);
holder.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton button, boolean b) {
Integer posClicked = (Integer)button.getTag();
if(b)
{
itemChecked.set(posClicked, true);
itemSelected.set(posClicked, pkgName);
}
else
{
itemChecked.set(posClicked,false);
itemSelected.set(posClicked, " ");
}
}
});
holder.checkBox.setChecked(itemChecked.get(position));
try{
Drawable icon = pm.getApplicationIcon(pkgName);
holder.imageView.setImageDrawable(icon);
}
catch (PackageManager.NameNotFoundException ne)
{
}
row.setId(position);
return row;
}
public boolean isChecked(int position)
{
return itemChecked.get(position);
}
public String getPkgName(int position)
{
return itemSelected.get(position);
}
public void removeItem(int position)
{
listItems.remove(position);
}
}
and here is code in which i am trying to restore my pkgNames. I picked pkgName because i have noticed position could be shuffled as my list is dynamic but pkgName related to each item will stay same.
#Override
public void onPause()
{
super.onPause();
save(notes.itemSelected);
}
#Override
public void onResume()
{
super.onResume();
ArrayList<String> checkOld = load();
for (int i = 0 ; i < checkOld.size(); i++)
{
notes.itemSelected = checkOld;
}
}
#Override
public void onRestart()
{
super.onRestart();
ArrayList<String> checkOld = load();
for (int i = 0 ; i < checkOld.size(); i++)
{
notes.itemSelected = checkOld;
}
}
private void save(final ArrayList<String> isChecked) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
for(Integer i = 0; i < isChecked.size(); i++)
{
editor.putString(i.toString(), isChecked.get(i));
}
editor.commit();
}
private ArrayList<String> load() {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
ArrayList<String> reChecked = new ArrayList<String>();
for(Integer i = 0; i < notes.getCount(); i++)
{
reChecked.add(i, sharedPreferences.getString(i.toString(), " "));
}
return reChecked;
}
}
Please Please HELP!!!!
See how-do-i-save-an-android-applications-state