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();
}
}
Related
this is my adapter class where i am having a add to cart button
public class ServiceSelectionOptionsListAdapter extends ArrayAdapter<ServiceSelectionOptionsDataModel> {
private Context context;
private int layoutResourceId;
ListView list;
static final String TAG = "LISTT";
HashMap<Integer, Integer> hashMap;
String response;
ProgressDialog pdilog;
SharedPreferences prefs;
String serverresponse1;
private List<ServiceSelectionOptionsDataModel> data;
String custid;
JSONArray _jsonarray;
JSONObject jsonObject;
String subsrvceopid;
String quantity = "1";
String cartcounter;
TextView counter;
public ServiceSelectionOptionsListAdapter(Context context, int layoutResourceId,
List<ServiceSelectionOptionsDataModel> data) {
super(context, R.layout.serviceselectionoptionslist, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
hashMap = new HashMap<Integer, Integer>();
prefs = context.getSharedPreferences(AppConstants.VERIFICATION,
Context.MODE_PRIVATE);
custid = prefs.getString(AppConstants.CUSTOMERID, "");
cartcounter = prefs.getString(AppConstants.CARTITEMCOUNTER, "");
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) {
View row = convertView;
final ViewHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.optionname = (TextView) row.findViewById(R.id.tvsubserviceoptionname);
holder.addtocart = (Button) row.findViewById(R.id.btnaddtocart);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final ServiceSelectionOptionsDataModel item = data.get(position);
holder.optionname.setText(item.getOptionname());
holder.addtocart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Integer index = (Integer) view.getTag();
subsrvceopid = data.get(position).getId();
new addtocart().execute(custid, subsrvceopid, quantity);
new cartitemsdetails().execute(custid);
SharedPreferences.Editor editor = context.getSharedPreferences(AppConstants.VERIFICATION, context.MODE_PRIVATE).edit();
editor.putString(AppConstants.SUBSERVIEOPTIONID, subsrvceopid);
editor.commit();
notifyDataSetChanged();
}
});
return row;
}
static class ViewHolder {
TextView optionname;
// TextView charges;
Button addtocart;
TextView counter;
}
and this is my activity class where i m getting the size of the cart items list
class cartitemsdetails extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
pdilog = new ProgressDialog(ServiceSelectionOptionsListActivity.this);
pdilog.setMessage("Please Wait....");
pdilog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
String response = JSONFunctions.getJSONfromURL("http://cpanel.smartindiaservice.com/api/cartdetails?customerid=" + params[0]);
try {
jsonarray = new JSONArray(response);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
size = jsonarray.length();
counter.setText(String.valueOf(size));
if (size == 0 )
{
viewcart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ServiceSelectionOptionsListActivity.this, NoItemsInTheCart.class);
startActivity(intent);
}
});
cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ServiceSelectionOptionsListActivity.this, NoItemsInTheCart.class);
startActivity(intent);
}
});
}
if(size>0) {
viewcart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ServiceSelectionOptionsListActivity.this, MyCart.class);
startActivity(intent);
}
});
cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ServiceSelectionOptionsListActivity.this, MyCart.class);
startActivity(intent);
}
});
}
pdilog.dismiss();
super.onPostExecute(aVoid);
}
}
class OptionsSelection extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
response = JSONFunctions.getJSONfromURL("http://cpanel.smartindiaservice.com/api/subserviceoptions?subserviceid=" + params[0]);
try {
_jsonarray = new JSONArray(response);
for (int i = 0; i < _jsonarray.length(); i++) {
ServiceSelectionOptionsDataModel datamodel = new ServiceSelectionOptionsDataModel();
jsonObject = _jsonarray.getJSONObject(i);
optionname = jsonObject.getString("OptionName");
datamodel.setOptionname(optionname);
charge = jsonObject.getString("Charges");
datamodel.setCharge(charge);
subserviceoptionid = jsonObject.getString("SubServiceOptionID");
datamodel.setId(subserviceoptionid);
lstDataModel.add(datamodel);
}
} catch (Exception e) {
System.out.println(e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
ServiceSelectionOptionsListAdapter adapter = new ServiceSelectionOptionsListAdapter(ServiceSelectionOptionsListActivity.this, R.layout.serviceselectionoptionslist, lstDataModel);
options.setAdapter(adapter);
adapter.notifyDataSetChanged();
super.onPostExecute(result);
}
}
I have listview and after filtering items of listview when I click on item its always returning wrong position of listview item.
Following is Adapter Class:
public class AdmitPatientAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
ArrayList<HashMap<String, String>> TempArrList = new ArrayList<>();
private static LayoutInflater inflater = null;
public static final String TAG_MRDNO = "mrd_no";
public AdmitPatientAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
TempArrList.addAll(d);
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return TempArrList.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
TempArrList.clear();
if (charText.length() == 0) {
TempArrList.addAll(data);
} else {
HashMap<String, String> tMap;
for (int i = 0; i < data.size(); i++) {
tMap = data.get(i);
if (charText.length() != 0 && tMap.get("mrd_no").toLowerCase(Locale.getDefault()).contains(charText)) {//mrd_no
TempArrList.add(tMap);
} else if (charText.length() != 0 && tMap.get("pname").toLowerCase(Locale.getDefault()).contains(charText)) {//pname
TempArrList.add(tMap);
} else if (charText.length() != 0 && tMap.get("bed_no").toLowerCase(Locale.getDefault()).contains(charText)) {
TempArrList.add(tMap);
} else if (charText.length() != 0 && tMap.get("nursingstation").toLowerCase(Locale.getDefault()).contains(charText)) {
TempArrList.add(tMap);
}
}
notifyDataSetChanged();
}
}
public View getView(int position, View convertView, ViewGroup parent) {
View viw = convertView;
if (convertView == null)
viw = inflater.inflate(R.layout.ip_ptn_items, null);
TextView txt_Mr_dno = (TextView) viw.findViewById(R.id.txtMrdno);
TextView txt_pitnt_Name = (TextView) viw.findViewById(R.id.txtpitntName);
TextView txt_Bed_no = (TextView) viw.findViewById(R.id.txtBedno);
TextView txt_Dob = (TextView) viw.findViewById(R.id.txtDob);
TextView txt_drNme = (TextView) viw.findViewById(R.id.txtDr);
TextView txt_Sex = (TextView) viw.findViewById(R.id.txtSex);
TextView txt_Wrdnm = (TextView) viw.findViewById(R.id.txtWrdnm);
HashMap<String, String> item = new HashMap<String, String>();
item = TempArrList.get(position);
String mrd_no = item.get(TAG_MRDNO);
item.put(TAG_MRDNO, mrd_no);
mrd_no = item.get(TAG_MRDNO);
if (mrd_no.endsWith("*")) {
txt_Mr_dno.setTextColor(Color.RED);
txt_pitnt_Name.setTextColor(Color.RED);
txt_Dob.setTextColor(Color.RED);
txt_Sex.setTextColor(Color.RED);
txt_Wrdnm.setTextColor(Color.RED);
txt_Bed_no.setTextColor(Color.RED);
} else {
txt_Mr_dno.setTextColor(Color.BLACK);
txt_pitnt_Name.setTextColor(Color.BLACK);
txt_Dob.setTextColor(Color.BLACK);
txt_Sex.setTextColor(Color.BLACK);
txt_Wrdnm.setTextColor(Color.BLUE);
txt_Bed_no.setTextColor(Color.BLUE);
}
//Setting all values in listview
txt_Mr_dno.setText(item.get("mrd_no"));
txt_pitnt_Name.setText(item.get("pname"));
txt_Bed_no.setText(item.get("bed_no"));
txt_Dob.setText(item.get("dob"));
//txt_admit_Date.setText(item.get("admission_date"));
txt_Sex.setText(item.get("sex"));
txt_Wrdnm.setText(item.get("nursingstation"));
txt_drNme.setText(item.get("doctor"));
// item = data.get(position);
/// String userType = item.get(TAG_UTYPE);
// item.put(TAG_UTYPE, mrd_no);
// userType = item.get(TAG_UTYPE);
try {
if (item.get("userType").equals("doctor")) {
txt_drNme.setVisibility(View.INVISIBLE);
} else {
txt_drNme.setVisibility(View.VISIBLE);
}
} catch (Exception e) {
e.printStackTrace();
}
return viw;
}
}
and another one is on click event class:
public class AdmitPatientFragment extends Fragment implements FragmentCycle {
ListView lstViw;
AdmitPatientAdapter adapter;
String DcId = "";
String userType = "";
public static final String MyPREFERENCES = "MyPrefs";
SharedPreferences sharedPreferences;
// generic array list
ArrayList<HashMap<String, String>> dlst = new ArrayList<HashMap<String, String>>();
// json url
private static String url = "http://scanweb.dmhospital.org:81/amrita_login/AdmList.php?auth=Yes";
#Override
public void onResumeFragment() {
}
#Override
public void onPauseFragment() {
}
// json node names
private static final String TAG_ADMITLIST = "AdmissionList";
private static final String TAG_MRD = "mrd_no";
private static final String TAG_PNAME = "pname";
private static final String TAG_BNO = "bed_no";
private static final String TAG_DOB = "dob";
private static final String TAG_ADMIT_DATE = "admission_date";
private static final String TAG_DOCTOR = "doctor";
private static String TAG_SEX = "sex";
private static String TAG_PATN_ID = "patient_id";
private static String TAG_VISIT_ID = "visit_id";
private static final String TAG_WARD_NAME = "nursingstation";
public static final String TAG_UTYPE = "userType";
JSONArray AdmissionList = null;
public AdmitPatientFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
setReturnTransition(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
LinearLayout rootView = (LinearLayout) inflater.inflate(
R.layout.ip_ptn_lstviw, container, false);
dlst = new ArrayList<HashMap<String, String>>();
Intent intent = getActivity().getIntent();
DcId = intent.getStringExtra("drid");
if (CheckNetwork.isInternetAvailable(getActivity())) //returns true if internet available
{
} else {
Toast.makeText(getActivity(), "No Internet Connection", Toast.LENGTH_SHORT).show();
}
// to read doctor id from shared preferences
sharedPreferences = getActivity().getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);
DcId = sharedPreferences.getString("drid", DcId);
userType = sharedPreferences.getString("usertype", userType);
url = url + "&docID=" + DcId;
new paAsyncTask().execute();
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.three_dots_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
final MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
//*** setOnQueryTextFocusChangeListener ***
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String searchQuery) {
adapter.filter(searchQuery.toString().trim());
lstViw.invalidate();
return true;
}
});
MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Do something when collapsed
return true; // Return true to collapse action view
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Do something when expanded
return true; // Return true to expand action view
}
});
}
private class paAsyncTask extends AsyncTask<String, String, JSONObject> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait admit patient list is loading ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected JSONObject doInBackground(String... params) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
AdmissionList = json.getJSONArray(TAG_ADMITLIST);
dlst = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < AdmissionList.length(); i++) {
JSONObject c = AdmissionList.getJSONObject(i);
String admission_date = c.getString(TAG_ADMIT_DATE);
HashMap<String, String> map = new HashMap<String, String>();
String ageSex = "(" + c.getString(TAG_DOB) + " | " + c.getString(TAG_SEX) + ")";
String[] admDte = admission_date.split(":");
String[] admDte1 = admission_date.split(":");
String resultDte = admDte[0] + ":" + admDte1[1];
map.put(TAG_MRD, c.getString(TAG_MRD).toString());
map.put(TAG_PNAME, c.getString(TAG_PNAME));
map.put(TAG_BNO, c.getString(TAG_BNO));
map.put(TAG_DOB, ageSex);
map.put(TAG_ADMIT_DATE, resultDte);
map.put(TAG_UTYPE, userType);
map.put(TAG_DOCTOR, c.getString(TAG_DOCTOR).toString());
// map.put(TAG_SEX, str);
map.put(TAG_WARD_NAME, c.getString(TAG_WARD_NAME));
map.put(TAG_PATN_ID, c.getString(TAG_PATN_ID));
map.put(TAG_VISIT_ID, c.getString(TAG_VISIT_ID));
dlst.add(map);
}
lstViw = (ListView) getView().findViewById(R.id.lstAdmsion);
adapter = new AdmitPatientAdapter(getActivity(), dlst);
adapter.notifyDataSetChanged();
lstViw.setAdapter(adapter);
lstViw.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
HashMap<String, String> map = dlst.get(position);
Intent imp = new Intent(getActivity(),
NavigationDrawerActivity.class);
imp.putExtra("drid", DcId);
// imp.putExtra(TAG_ADMIT_DATE, map.get(""));
imp.putExtra("docNme", map.get(TAG_DOCTOR));
imp.putExtra("ptnId", map.get(TAG_PATN_ID));
imp.putExtra("vst_id", map.get(TAG_VISIT_ID));
startActivity(imp);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Try changing
HashMap<String, String> map = dlst.get(position);
to
HashMap<String, String> map = adapter.getItem(position);
Basically, the OnItemClickListener is grabbing objects from your ListView rather than your Adapter that has updated references...
EDIT 1: You also need to implement getItem in your Adapter so it returns an object from your filtered list. I'm assuming that's dlst...
So, you would need to put this in your adapter class:
public HashMap<String, String> getItem(int position){
return dlst.get(position);
}
I have a ListView that uses a layout containing a TextView which is a separator. I have code in place so that if the separator should show, it sets the Visibility to View.VISIBLE, and otherwise View.GONE. That is working fine, however I noticed the list is only correct the first load. Once I scroll the list to the bottom and back up it is incorrectly showing/hiding my separator. I know this is a known programming error with ListViews, but I'm a bit confused on how to tackle it. Below is my code. How can I fix this?
public class MaintenanceGrid extends Activity {
static final String KEY_DESCRIPTION = "description";
static final String KEY_SCHEDULEFLAG = "scheduleflag";
static final String KEY_LASTSERVICEDATE = "lastservicedate";
static final String KEY_LASTSERVICEMILEAGE = "lastservicemileage";
static final String KEY_LASTSERVICEVENDOR = "lastservicevendor";
static final String KEY_MILEAGEINTERVAL = "mileageinterval";
static final String KEY_CURRENTODOMETER = "currentodometer";
static final String KEY_MILEAGEOVERDUE = "mileageoverdue";
static final String KEY_NEXTMILEAGEDUE = "nextmileagedue";
AlertDialogManager alertDialog = new AlertDialogManager();
ArrayList<HashMap<String, String>> maintenanceGridList = new ArrayList<HashMap<String, String>>();
Globals globals;
MaintenanceGridData maintenanceGridData;
ProgressDialog progressDialog;
ListView list;
MaintenanceGridAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.maintenance_grid);
globals = (Globals) this.getApplication();
// Set our custom font
View rootView = findViewById(R.id.layoutMaintenanceGridContainer);
Globals.applyCustomFont((ViewGroup) rootView, FontClass.Arial(this));
// Execute main task to get the maintenance grid
new MaintenanceGridDetails().execute(globals.getCarID());
}
#Override
protected void onResume() {
super.onResume();
try {
globals = (Globals) this.getApplication();
if(globals.getDriverID()==null){
Intent i = new Intent(MaintenanceGrid.this, Splash.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
} catch(Exception e){
Intent i = new Intent(MaintenanceGrid.this, Splash.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
}
private class MaintenanceGridDetails extends AsyncTask<String, Integer, Integer>
{
static final int STATUS_SUCCESS = 1;
static final int STATUS_FAIL = 0;
static final int STATUS_NETWORK = 3;
static final int STATUS_ERROR = 2;
#Override
protected void onPreExecute()
{
progressDialog = ProgressDialog.show(getParent(), "", getResources().getString(R.string.general_msg_please_wait));
}
#Override
protected Integer doInBackground(String... params)
{
if(!NetworkStatus.getInstance(getApplicationContext()).isOnline(getApplicationContext())) {
return STATUS_NETWORK;
}
maintenanceGridData = MaintenanceGridDetails(params[0]);
if(maintenanceGridData==null) { return STATUS_ERROR; }
if(maintenanceGridData.getMaintenanceGridDescription().size()!=0){
return STATUS_SUCCESS;
} else {
return STATUS_FAIL;
}
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Integer result)
{
if (result == STATUS_ERROR)
{
progressDialog.dismiss();
alertDialog.showAlertDialog(getParent(), getResources().getString(R.string.error), getResources().getString(R.string.error_connect), false);
}
else
if (result == STATUS_NETWORK)
{
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
progressDialog.dismiss();
Intent networkError = new Intent(MaintenanceGrid.this, NetworkError.class);
networkError.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(networkError);
finish();
}
}, 1000);
}
else
if (result == STATUS_FAIL )
{
progressDialog.dismiss();
alertDialog.showAlertDialog(getParent(), getResources().getString(R.string.error), getResources().getString(R.string.maintenance_grid_unavailable), false);
}
else
{
//set values in hashmap for listview
for(int x=0; x<maintenanceGridData.getMaintenanceGridDescription().size(); x++)
{
//create new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_DESCRIPTION, maintenanceGridData.getMaintenanceGridDescription().get(x));
map.put(KEY_SCHEDULEFLAG, maintenanceGridData.getMaintenanceGridScheduleFlag().get(x));
map.put(KEY_LASTSERVICEDATE, maintenanceGridData.getMaintenanceGridLastServiceDate().get(x));
map.put(KEY_LASTSERVICEMILEAGE, maintenanceGridData.getMaintenanceGridLastServiceMileage().get(x));
map.put(KEY_LASTSERVICEVENDOR, maintenanceGridData.getMaintenanceGridLastServiceVendor().get(x));
map.put(KEY_MILEAGEINTERVAL, maintenanceGridData.getMaintenanceGridMileageInterval().get(x));
map.put(KEY_CURRENTODOMETER, maintenanceGridData.getMaintenanceGridCurrentOdometer().get(x));
map.put(KEY_MILEAGEOVERDUE, maintenanceGridData.getMaintenanceGridMileageOverdue().get(x));
map.put(KEY_NEXTMILEAGEDUE, maintenanceGridData.getMaintenanceGridNextMileageDue().get(x));
//add history entry to main arraylist
maintenanceGridList.add(map);
}
list = (ListView) findViewById(R.id.listMaintenanceGrid);
// Get adapter by passing xml data ArrayList
adapter = new MaintenanceGridAdapter(getApplicationContext(), getParent(), maintenanceGridList);
list.setAdapter(adapter);
//close dialog
progressDialog.dismiss();
// If the Status Badge id visible, hide it
if (Main.statusTabBadge.getVisibility() == View.VISIBLE) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Main.statusTabBadge.setVisibility(View.GONE);
Globals.ackMaintenanceItemsDue=true;
}
}, 500);
}
}
}
}
public MaintenanceGridData MaintenanceGridDetails (final String carid) {
// method here gets the data for my adapter
}
}
Adapter
static class ViewHolderItem {
TextView lblMaintenanceGridLastServiceDate, lblMaintenanceGridOdometer, lblMaintenanceGridCurrentOdometer, lblMaintenanceGridSeparator,
description, last_service_date, odometer, current_odometer;
ImageView imageMaintenanceItemIcon;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolderItem viewHolder;
View vi = convertView;
if(vi==null) {
vi = inflater.inflate(R.layout.maintenance_grid_item, parent, false);
viewHolder = new ViewHolderItem();
viewHolder.lblMaintenanceGridLastServiceDate = (TextView)vi.findViewById(R.id.lblMaintenanceGridLastServiceDate);
viewHolder.lblMaintenanceGridOdometer = (TextView)vi.findViewById(R.id.lblMaintenanceGridOdometer);
viewHolder.lblMaintenanceGridCurrentOdometer = (TextView)vi.findViewById(R.id.lblMaintenanceGridCurrentOdometer);
viewHolder.lblMaintenanceGridSeparator = (TextView)vi.findViewById(R.id.lblMaintenanceSeparator);
viewHolder.description = (TextView)vi.findViewById(R.id.lblMaintenanceGridDescription);
viewHolder.last_service_date = (TextView)vi.findViewById(R.id.txtMaintenanceGridLastServiceDate);
viewHolder.odometer = (TextView)vi.findViewById(R.id.txtMaintenanceGridOdometer);
viewHolder.current_odometer = (TextView)vi.findViewById(R.id.txtMaintenanceGridCurrentOdometer);
viewHolder.imageMaintenanceItemIcon = (ImageView)vi.findViewById(R.id.maintenanceGridItemIcon);
// Store the holder with the view
vi.setTag(viewHolder);
} else {
viewHolder = (ViewHolderItem) vi.getTag();
}
if(position % 2 == 0){
vi.setBackgroundResource(R.drawable.list_selector_even);
} else {
vi.setBackgroundResource(R.drawable.list_selector_odd);
}
// Make the items in this listview NOT clickable
vi.setEnabled(false);
vi.setOnClickListener(null);
HashMap<String, String> maintenanceGridItem = new HashMap<String, String>();
maintenanceGridItem = data.get(position);
if(data.get(position) != null) {
// Show/Hide the separator
if (!currentMileageInterval.equalsIgnoreCase(maintenanceGridItem.get(MaintenanceGrid.KEY_MILEAGEINTERVAL))) {
currentMileageInterval = maintenanceGridItem.get(MaintenanceGrid.KEY_MILEAGEINTERVAL);
viewHolder.lblMaintenanceGridSeparator.setText(context.getResources().getString(R.string.maintenance_grid_separator_text, currentMileageInterval));
viewHolder.lblMaintenanceGridSeparator.setVisibility(View.VISIBLE);
} else {
viewHolder.lblMaintenanceGridSeparator.setVisibility(View.GONE);
}
// Setting all values in listview
viewHolder.description.setText(maintenanceGridItem.get(MaintenanceGrid.KEY_DESCRIPTION));
viewHolder.last_service_date.setText(maintenanceGridItem.get(MaintenanceGrid.KEY_LASTSERVICEDATE));
viewHolder.odometer.setText(maintenanceGridItem.get(MaintenanceGrid.KEY_LASTSERVICEMILEAGE));
viewHolder.current_odometer.setText(maintenanceGridItem.get(MaintenanceGrid.KEY_CURRENTODOMETER));
// Set up the image
if (maintenanceGridItem.get(MaintenanceGrid.KEY_SCHEDULEFLAG).equalsIgnoreCase("overdue")) {
viewHolder.imageMaintenanceItemIcon.setImageResource(R.drawable.icon_alert_overdue);
} else if (maintenanceGridItem.get(MaintenanceGrid.KEY_SCHEDULEFLAG).equalsIgnoreCase("due")) {
viewHolder.imageMaintenanceItemIcon.setImageResource(R.drawable.icon_alert);
} else {
viewHolder.imageMaintenanceItemIcon.setImageResource(R.drawable.icon_check);
}
// Set our custom font
viewHolder.lblMaintenanceGridLastServiceDate.setTypeface(arialTypeface);
viewHolder.lblMaintenanceGridLastServiceDate.setTypeface(arialTypeface);
viewHolder.lblMaintenanceGridOdometer.setTypeface(arialTypeface);
viewHolder.lblMaintenanceGridCurrentOdometer.setTypeface(arialTypeface);
viewHolder.lblMaintenanceGridSeparator.setTypeface(arialTypeface, Typeface.BOLD);
viewHolder.description.setTypeface(arialTypeface, Typeface.BOLD);
viewHolder.last_service_date.setTypeface(arialTypeface);
viewHolder.odometer.setTypeface(arialTypeface);
viewHolder.current_odometer.setTypeface(arialTypeface);
}
return vi;
}
i have one listview and added content using BaseAdapter. it's working fine but when am going to scroll down items form top to bottom it automatically change the stage of selected items to default state in listview. how to solve this problem. please help. i new to android.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub_menu_list);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
customDialog = new CustomDialog(TakeoutListActivity.this);
Intent intent = getIntent();
Obj = intent.getStringExtra("CateValue");
Log.e("Obj", "" + Obj);
addtocardArr = new ArrayList<HashMap<String, String>>();
listView = (ListView) findViewById(R.id.subcategory_list);
notificationCount = 0;
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
customDialog.setContentView(R.layout.cus_dialog);
customDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
if (Obj != null) {
try {
JSONObject jsonObject = new JSONObject(Obj);
JSONArray jsonArray = jsonObject.getJSONArray("Details");
SubCateArrayList = new ArrayList<HashMap<String, String>>();
/*for (int i = 0; i < jsonArray.length(); i++) {
SubCateHashMapList = new HashMap<String, String>();
JSONObject DetailsObj = jsonArray.getJSONObject(i);
SubCateHashMapList.put("ItemName", DetailsObj.optString("ItemName"));
JSONArray AllItemArray = DetailsObj.getJSONArray("Allitems");
//Log.e("AllItemArray", "" + AllItemArray);
SubCateArrayList.add(SubCateHashMapList);
for (int j = 0; j < AllItemArray.length(); j++) {
SubInner = new HashMap<String, String>();
JSONObject AllItemObj = AllItemArray.getJSONObject(j);
SubInner.put("foodid", AllItemObj.getString("foodid"));
SubInner.put("name", AllItemObj.getString("name"));
SubInner.put("Description", AllItemObj.getString("Description"));
SubInner.put("image", AllItemObj.getString("image"));
SubInner.put("price", AllItemObj.getString("price"));
SubInner.put("favorite", AllItemObj.getString("favorite"));
SubCateArrayList.add(SubInner);
Log.e("SubCateArrayList", "" + SubCateArrayList);
}
}
Log.e("SubCateArrayList", "" + SubCateArrayList);*/
SubCateArrayList = new ArrayList<HashMap<String, String>>();
// SubCateArrayList.clear();
// SubCateInnerArrayList = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jsonArray.length(); i++) {
SubCateHashMapList = new HashMap<String, String>();
JSONObject DetailsObj = jsonArray.getJSONObject(i);
SubCateHashMapList.put("ItemName", DetailsObj.optString("ItemName"));
Log.e("SubCateHashMapList>>>>>>>>>", "" + SubCateHashMapList);
JSONArray AllItemArray = DetailsObj.getJSONArray("Allitems");
//Log.e("AllItemArray", "" + AllItemArray);
//SubCateArrayList.add(SubCateHashMapList);
for (int j=0; j<AllItemArray.length();j++)
{
SubInner = new HashMap<String, String>();
JSONObject AllItemObj = AllItemArray.getJSONObject(j);
SubInner.put("foodid", AllItemObj.getString("foodid"));
SubInner.put("name", AllItemObj.getString("name"));
SubInner.put("Description", AllItemObj.getString("Description"));
SubInner.put("image", AllItemObj.getString("image"));
SubInner.put("price", AllItemObj.getString("price"));
SubInner.put("favorite", AllItemObj.getString("favorite"));
SubCateArrayList.add(SubInner);
Log.d("SubCateInnerArrayList2349587", "" + SubCateArrayList);
}
//SubInner.putAll(SubCateHashMapList);
}
Log.e("SubCateArrayList", "" + SubCateArrayList);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
ErrorMsg = "JSONError";
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
customDialog.dismiss();
subCateListAdapter = new SubCateListAdapter(TakeoutListActivity.this, SubCateArrayList);
subCateListAdapter.notifyDataSetInvalidated();
listView.setFadingEdgeLength(0);
listView.setAdapter(subCateListAdapter);
}
}.execute();
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.cart_menu,menu);
MenuItem item = menu.findItem(R.id.cart_add);
drawable = (LayerDrawable)item.getIcon();
Log.d("notificationCount", "" + notificationCount);
BadgeHelper.setBadgeCount(this, drawable, notificationCount);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.cart_homeID)
{
Intent homeIntent = new Intent(TakeoutListActivity.this,HomeRestaurant.class);
startActivity(homeIntent);
TakeoutListActivity.this.finish();
}
if (id==R.id.cart_add)
{
if (notificationCount==0)
{
AlertDialog.Builder builder = new AlertDialog.Builder(TakeoutListActivity.this);
builder.setMessage("Please add to cart");
builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
else
{
Intent nextact = new Intent(TakeoutListActivity.this, AddCartActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("Selected", addtocardArr);
nextact.putExtras(bundle);
// nextact.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(nextact);
// Log.d("addtocardmap final", "********" + addtocardmap.toString());
}
return true;
}
return super.onOptionsItemSelected(item);
}
private class SubCateListAdapter extends BaseAdapter {
LayoutInflater layoutInflater;
Context context;
HashMap<String, String> display = new HashMap<String, String>();
ArrayList<HashMap<String, String>> data;
int count = 0;
String strcount="";
String[] clickedpositions;
int locid;
HashMap<String,String> toaddData;
public SubCateListAdapter(Context subMenuListActivity, ArrayList<HashMap<String, String>> subCateArrayList) {
this.context = subMenuListActivity;
this.data = subCateArrayList;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final TextView menuTitle, subMenuTitle, Price, des, countText, addCart, remove;
ImageView itemImage, FavImage;
ImageButton add, minus;
toaddData = new HashMap<String,String>();
display = data.get(position);
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view =layoutInflater.inflate(R.layout.takeout_listitem, parent, false);
//menuTitle = (TextView)view.findViewById(R.id.menu_title);
subMenuTitle = (TextView) view.findViewById(R.id.sub_title);
Price = (TextView) view.findViewById(R.id.price);
countText = (TextView) view.findViewById(R.id.count_text);
des = (TextView) view.findViewById(R.id.menu_des);
itemImage = (ImageView) view.findViewById(R.id.menu_Image);
FavImage = (ImageView) view.findViewById(R.id.fav);
addCart = (TextView)view.findViewById(R.id.addToCart);
add = (ImageButton)view.findViewById(R.id.add);
minus = (ImageButton)view.findViewById(R.id.minus);
//menuTitle.setText(display.get("ItemName"));
subMenuTitle.setText(display.get("name"));
des.setText(display.get("Description"));
Price.setText(display.get("price"));
Glide.with(getApplicationContext()).load(display.get("image")).error(R.drawable.list_bg).crossFade(500).into(itemImage);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textCount = Integer.parseInt(countText.getText().toString());
textCount++;
strcount = String.valueOf(textCount);
countText.setText(strcount);
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int textCount = Integer.parseInt(countText.getText().toString());
textCount--;
if(textCount<=0) {
strcount = String.valueOf(textCount);
countText.setText("0");
}
else
{
strcount = String.valueOf(textCount);
countText.setText(strcount);
}
}
});
addCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addtocardmap = new HashMap<String, String>();
recid = data.get(position).get("foodid");
pdttitle = data.get(position).get("name");
foodprice = data.get(position).get("price");
notifycount = countText.getText().toString();
poscount +=position;
strposcount += String.valueOf(position) + ",";
Log.e("strposcount", "" + strposcount);
toaddData.put("foodid", recid);
toaddData.put("name", pdttitle);
toaddData.put("notifycount", notifycount);
if(addtocardArr.contains(addtocardmap))
{
String quan = addtocardArr.get(position).get("qunatity");
int intquan = Integer.parseInt(quan)+Integer.parseInt(strcount);
strcount = String.valueOf(intquan);
// addtocardArr.remove(position - 1);
addtocardmap.put("foodid", recid);
addtocardmap.put("name", pdttitle);
addtocardmap.put("price", foodprice);
addtocardmap.put("qunatity", notifycount);
addtocardArr.set(position,addtocardmap);
Log.d("recid", "******" + recid);
Log.d("pdttitle", "******" + pdttitle);
Log.d("Quantity", "******" + notifycount);
Log.d("foodprice", "******" + foodprice);
Log.d("item position", "******" + position);
Log.d("addtocardmap", "********" + addtocardmap);
//addtocardArr.remove(position);
Log.d("After remove duplicates", "********" + addtocardArr);
}
else
{
//in object
addtocardmap.put("foodid", recid);
addtocardmap.put("name", pdttitle);
addtocardmap.put("price", foodprice);
addtocardmap.put("qunatity", notifycount);
//in array
Log.d("recid", "******" + recid);
Log.d("pdttitle", "******" + pdttitle);
Log.d("Quantity", "******" + notifycount);
Log.d("foodprice", "******" + foodprice);
Log.d("item position", "******" + position);
Log.d("addtocardmap", "********" + addtocardmap);
}
//tosendData.add(toaddData);
addtocardArr.add(addtocardmap);
Log.d("to add non-duplicate element", "" + addtocardArr);
// addtocardArr.add(new SelectedItems());
notificationCount++;
updateNotificationCount(String.valueOf(notificationCount));
}
});
return view;
}
}
See my Adapter and change your adapter like that
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder = null;
if (view == null) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.food_list_item, null);
holder = new ViewHolder();
holder.title = (TextView) view.findViewById(R.id.tvFoodItemTitle);
holder.desc = (TextView) view.findViewById(R.id.tvFoodItemDesc);
holder.image = (ImageView) view.findViewById(R.id.ivFoodItem);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.title.setText(getItem(position).getName());
holder.desc.setText(getItem(position).getDescription());
String imagePath = "assets://" + getItem(position).getImagePath();
ImageLoader.getInstance().displayImage(imagePath, holder.image);
return view;
}
class ViewHolder {
TextView title;
TextView desc;
ImageView image;
}
This example is done using the arraylist assuming lstcategory as your list and you can do similar for your hashmap too here I am just showing a simple logic to solve this you can do it accordingly if you get this logic
add boolean flag in your pojo class say
Boolean isSelected;
apply getter and setters in it.
initially set all the values for isSelected = false so that no list item is selected
now during onItem click set the current Object's isSelected to true
like this
within the onItemClick apply this
OnItemClickListener listViewOnItemClick = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View arg1, int position, long id) {
for(int i =0;i < lstcategory.size();i++}{
lstcategory.get(i).setIsSelected(false);
}
lstcategory.get(position).setIsSelected(true);
mAdapter.notifyDataSetChanged();
}
};
now in getview of your adapter class check if the lists item isChecked or not.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final View view = View.inflate(context, R.layout.item_list, null);
if (lstcategory.get(position).getIsSelected()) {
// set selected your color
}else{
//set default color
}
return view;
}
I am struggling with this problem for a while now. I am building a filterable list with edittext. The list populated fine initially BUT once I type something in the edittext field. The whole list is gone and returns no results. The following are my codes.
Note: My codes are mainly based on sacoskun's post.
ThreedListViewActivity.java
public class ThreedListViewActivity extends ActionBarActivity
{
// All static variables
static final String URL = "http://api.androidhive.info/music/music.xml";
// XML node keys
static final String KEY_SONG = "song"; // parent node
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_ARTIST = "artist";
static final String KEY_DURATION = "duration";
static final String KEY_THUMB_URL = "thumb_url";
ListView list;
ThreedListAdapterFilterable adapter;
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
EditText filterText = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.threed_listview);
setTitle(R.string.view_3d);
list=(ListView)findViewById(R.id.list);
adapter = new ThreedListAdapterFilterable(this, songsList);
new MyAsyncTask().execute();
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
private TextWatcher filterTextWatcher = 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) {
adapter.getFilter().filter(s.toString());
}
};
public class MyAsyncTask extends AsyncTask<Void,Void,Void>{
private final ProgressDialog dialog=new ProgressDialog(ThreedListViewActivity.this);
#Override
protected Void doInBackground(Void... params) {
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_SONG);
// looping through all song nodes <song>
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);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
// adding HashList to ArrayList
songsList.add(map);
}
return null;
}
#Override
protected void onPreExecute()
{
dialog.setMessage("Loading ...");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected void onPostExecute(Void result)
{
if(dialog.isShowing() == true)
{
dialog.dismiss();
}
// Getting adapter by passing xml data ArrayList
list.setAdapter(adapter);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_items, menu);
return true;
}
}
ThreedListAdapterFilterable.java
public class ThreedListAdapterFilterable extends BaseAdapter implements Filterable {
private Activity activity;
ArrayList<HashMap<String, String>> mDataShown;
ArrayList<HashMap<String, String>> mAllData;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public ThreedListAdapterFilterable(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
mDataShown= (ArrayList<HashMap<String, String>>) d;
mAllData = (ArrayList<HashMap<String, String>>) mDataShown.clone();
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return mDataShown.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.threed_listrow, null);
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
HashMap<String, String> song = new HashMap<String, String>();
song = mDataShown.get(position);
// Setting all values in listview
title.setText(song.get(ThreedListViewActivity.KEY_TITLE));
artist.setText(song.get(ThreedListViewActivity.KEY_ARTIST));
duration.setText(song.get(ThreedListViewActivity.KEY_DURATION));
imageLoader.DisplayImage(song.get(ThreedListViewActivity.KEY_THUMB_URL), thumb_image);
return vi;
}
public Filter getFilter() {
Filter nameFilter = new Filter() {
#SuppressWarnings("unchecked")
#Override
public String convertResultToString(Object resultValue) {
return ((HashMap<String, String>)(resultValue)).get(ThreedListViewActivity.KEY_TITLE);
}
#Override
protected FilterResults performFiltering(CharSequence s) {
if(s != null)
{
ArrayList<HashMap<String, String>> tmpAllData = mAllData;
ArrayList<HashMap<String, String>> tmpDataShown = mDataShown;
tmpDataShown.clear();
for(int i = 0; i < tmpAllData.size(); i++)
{
if(tmpAllData.get(i).get(ThreedListViewActivity.KEY_TITLE).toLowerCase().startsWith(s.toString().toLowerCase()))
{
tmpDataShown.add(tmpAllData.get(i));
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = tmpDataShown;
filterResults.count = tmpDataShown.size();
return filterResults;
}
else
{
return new FilterResults();
}
}
#Override
protected void publishResults(CharSequence s,
FilterResults results) {
if(results != null && results.count > 0)
{
notifyDataSetChanged();
}
}};
return nameFilter;
}
}
EDIT:
This is an updated adapter that will filter my list. BUT, it doesnt update my list when I backspace the text in the input text.
public class ProjectListAdapter extends BaseAdapter implements Filterable{
private Activity activity;
ArrayList<HashMap<String, String>> mDataShown;
ArrayList<HashMap<String, String>> mAllData;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
HashMap<String, String> song = new HashMap<String, String>();
ArrayList<HashMap<String, String>> filteredItems;
public ProjectListAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
mDataShown= (ArrayList<HashMap<String, String>>) d;
mAllData = (ArrayList<HashMap<String, String>>) mDataShown.clone();
filteredItems = mDataShown;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mDataShown.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi;
if(convertView==null){
vi=new View(activity);
vi = inflater.inflate(R.layout.recents_listrow, null);
}else{
vi = (View)convertView;
}
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView artist = (TextView)vi.findViewById(R.id.company); // artist name
ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
title.setText(filteredItems.get(position).get(RecentsFragment.KEY_TITLE));
artist.setText(filteredItems.get(position).get(RecentsFragment.KEY_COMPANY));
imageLoader.DisplayImage(filteredItems.get(position).get(RecentsFragment.KEY_THUMB_URL), thumb_image);
return vi;
}
public Filter getFilter() {
Filter nameFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
if(constraint != null && constraint.toString().length() > 0) {
constraint = constraint.toString().toUpperCase();
ArrayList<HashMap<String, String>> filt = mDataShown;
ArrayList<HashMap<String, String>> tmpItems = mAllData;
filt.clear();
for(int i = 0; i < tmpItems.size(); i++) {
if(tmpItems.get(i).get(RecentsFragment.KEY_TITLE).toLowerCase().startsWith(constraint.toString().toLowerCase()))
{
filt.add(tmpItems.get(i));
}
}
FilterResults filterResults = new FilterResults();
filterResults.count = filt.size();
filterResults.values = filt;
return filterResults;
}else{
return new FilterResults();
}
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
mDataShown = (ArrayList<HashMap<String, String>>)results.values;
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return nameFilter;
}
}
The list fragment i am trying to implement: RecentsFragment
public class RecentsFragment extends ListFragment {
// All static variables
static final String URL = "http://www.sundancepost.com/ivue/projects.xml";
// XML node keys
static final String KEY_PROJECT = "project"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_COMPANY = "company";
static final String KEY_THUMB_URL = "thumb_url";
int mCurCheckPosition = 0;
ListView list;
ProjectListAdapter adapter;
ArrayList<HashMap<String, String>> projectsList = new ArrayList<HashMap<String, String>>();
EditText filterText = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.recents_list, container, false);
list = (ListView)view.findViewById(android.R.id.list);
filterText = (EditText)view.findViewById(R.id.filter_box);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(null == savedInstanceState){
ConnectivityManager cMgr = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
if (cMgr.getActiveNetworkInfo() != null && cMgr.getActiveNetworkInfo().isConnectedOrConnecting()) {
new MyAsyncTask().execute();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Please check your internet connection");
builder.setTitle("Failed to download resources");
builder.setCancelable(false);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
return;
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
adapter = new ProjectListAdapter(getActivity(), projectsList);
list.requestFocus();
list.setTextFilterEnabled(true);
filterText.addTextChangedListener(filterTextWatcher);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(getActivity(), DetailsActivity.class);
intent.putExtra("title",projectsList.get(position).get(KEY_TITLE));
intent.putExtra("company", projectsList.get(position).get(KEY_COMPANY));
startActivity(intent);
}
});
}
#Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putInt("workaround", mCurCheckPosition);
}
private TextWatcher filterTextWatcher = 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) {
adapter.getFilter().filter(s);
}
};
#Override
public void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
public class MyAsyncTask extends AsyncTask<Void,Void,Void>{
private final ProgressDialog recents_dialog = new ProgressDialog(getActivity());
#Override
protected Void doInBackground(Void... params) {
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_PROJECT);
// looping through all song nodes <song>
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);
// adding each child node to HashMap key => value
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_COMPANY, parser.getValue(e, KEY_COMPANY));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
// adding HashList to ArrayList
projectsList.add(map);
}
return null;
}
#Override
protected void onPreExecute()
{
projectsList.clear();
recents_dialog.setMessage("Loading ...");
recents_dialog.show();
recents_dialog.setCancelable(false);
}
#Override
protected void onPostExecute(Void result)
{
if(recents_dialog.isShowing() == true)
{
recents_dialog.dismiss();
}
// Getting adapter by passing xml data ArrayList
list.setAdapter(adapter);
}
}
}
public class FriendsListActivity extends Activity implements OnClickListener {
private Handler mHandler;
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_INSTALLED = "installed";
static final String KEY_THUMB_URL = "picture";
protected ListView friendsList;
protected static JSONArray jsonArray;
FriendsListAdapter adapter;
ArrayList> friendslist;
EditText filterText;
String apiResponse;
Button play, invite;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.friends_list);
friendslist = new ArrayList<HashMap<String, String>>();
mHandler = new Handler();
ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
actionBar.setTitle("Facebook Friends");
actionBar.setHomeAction(new IntentAction(this, TruthorDareActivity
.createIntent(this), R.drawable.ic_home));
friendsList = (ListView) findViewById(R.id.friendsList);
filterText = (EditText) findViewById(R.id.searchBox);
filterText.addTextChangedListener(filterTextWatcher);
friendsList.setTextFilterEnabled(true);
friendsList.requestFocus();
play = (Button) findViewById(R.id.play);
invite = (Button) findViewById(R.id.invite);
play.setOnClickListener(this);
invite.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
apiResponse = extras.getString("API_RESPONSE");
callPlayList();
}
#Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
}
#Override
protected void onResume() {
super.onResume();
friendsList.requestFocus();
}
public void callPlayList() {
try {
jsonArray = new JSONObject(apiResponse).getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json_data = jsonArray.getJSONObject(i);
if (json_data.has("installed")
&& json_data.getBoolean("installed") == true) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_ID, json_data.getString("id"));
map.put(KEY_NAME, json_data.getString("name"));
map.put(KEY_THUMB_URL, json_data.getString("picture"));
map.put(KEY_INSTALLED, json_data.getString("installed"));
friendslist.add(map);
}
}
} catch (JSONException e) {
showToast("Error: " + e.getMessage());
return;
}
adapter = new FriendsListAdapter(FriendsListActivity.this, friendslist);
friendsList.setAdapter(adapter);
}
public void callInviteList() {
try {
jsonArray = new JSONObject(apiResponse).getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json_data = jsonArray.getJSONObject(i);
if (!json_data.has("installed")) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_ID, json_data.getString("id"));
map.put(KEY_NAME, json_data.getString("name"));
map.put(KEY_THUMB_URL, json_data.getString("picture"));
map.put(KEY_INSTALLED, "false");
friendslist.add(map);
}
}
} catch (JSONException e) {
showToast("Error: " + e.getMessage());
return;
}
adapter = new FriendsListAdapter(FriendsListActivity.this, friendslist);
friendsList.setAdapter(adapter);
}
public void clearAdapter(String params) {
friendslist.clear();
adapter.notifyDataSetChanged();
adapter.notifyDataSetInvalidated();
if (params.equals("invite")) {
callInviteList();
} else {
callPlayList();
}
}
public class PostDialogListener extends BaseDialogListener {
#Override
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
showToast("Message posted on the wall.");
} else {
showToast("No message posted on the wall.");
}
}
}
public void showToast(final String msg) {
mHandler.post(new Runnable() {
#Override
public void run() {
Toast toast = Toast.makeText(FriendsListActivity.this, msg,
Toast.LENGTH_LONG);
toast.show();
}
});
}
private TextWatcher filterTextWatcher = 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) {
adapter.getFilter().filter(s);
}
};
#Override
protected void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.play:
clearAdapter("play");
break;
case R.id.invite:
clearAdapter("invite");
break;
default:
break;
}
}
}
The next part is the adapter class I use in a separate class file.
public class FriendsListAdapter extends BaseAdapter implements Filterable {
private Activity activity;
public ArrayList<HashMap<String, String>> data;
public ArrayList<HashMap<String, String>> allData;
public HashMap<String, String> friends;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
private ItemsFilter mFilter;
static SharedPreferences TODLoginPrefs;
#SuppressWarnings({ "unchecked", "static-access" })
public FriendsListAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = (ArrayList<HashMap<String, String>>) d;
allData = (ArrayList<HashMap<String, String>>) data.clone();
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
TODLoginPrefs = activity.getSharedPreferences("LogInSession",
activity.MODE_PRIVATE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.friends_list_row, null);
TextView user = (TextView) vi.findViewById(R.id.gname);
Button play = (Button) vi.findViewById(R.id.btnPlay);
Button invite = (Button) vi.findViewById(R.id.btnInvite);
ImageView thumb_image = (ImageView) vi.findViewById(R.id.list_image);
friends = new HashMap<String, String>();
friends = data.get(position);
user.setText(friends.get(FriendsListActivity.KEY_NAME));
imageLoader.DisplayImage(
friends.get(FriendsListActivity.KEY_THUMB_URL), thumb_image);
final String friendrId = (friends.get(FriendsListActivity.KEY_ID));
final String name = (friends.get(FriendsListActivity.KEY_NAME));
final String installed = (friends
.get(FriendsListActivity.KEY_INSTALLED));
if (installed.equals("false")) {
play.setVisibility(View.GONE);
invite.setVisibility(View.VISIBLE);
}
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new AlertDialog.Builder(activity)
.setTitle("Create game with " + name + "?")
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
UserFunction userFunction = new UserFunction();
JSONObject json_game = userFunction
.newGame(
activity,
"Facebook",
TODLoginPrefs
.getString(
"UserID",
""),
friendrId, null, null);
if (json_game.has("success")) {
activity.startActivity(new Intent(
activity,
TruthorDareActivity.class));
} else {
try {
Toast.makeText(
activity,
json_game
.getString("error_msg"),
Toast.LENGTH_SHORT)
.show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}).setNegativeButton(R.string.no, null).show();
}
});
invite.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new AlertDialog.Builder(activity)
.setTitle("Invite " + name + "?")
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
UserFunction userFunction = new UserFunction();
JSONObject json_game = userFunction
.newInvite(
activity,
"Facebook",
TODLoginPrefs
.getString(
"UserID",
""),
friendrId, null, null);
if (json_game.has("success")) {
Bundle params = new Bundle();
params.putString("to", friendrId);
params.putString(
"message",
activity.getResources()
.getString(
R.string.app_request_message));
Utilities.facebook.dialog(activity,
"apprequests", params,
new AppRequestsListener());
} else {
try {
Toast.makeText(
activity,
json_game
.getString("error_msg"),
Toast.LENGTH_SHORT)
.show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}).setNegativeButton(R.string.no, null).show();
}
});
return vi;
}
#Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new ItemsFilter();
}
return mFilter;
}
private class ItemsFilter extends Filter {
#SuppressWarnings("unchecked")
#Override
public String convertResultToString(Object resultValue) {
return ((HashMap<String, String>) (resultValue))
.get(FriendsListActivity.KEY_NAME);
}
#Override
protected FilterResults performFiltering(CharSequence s) {
if (s != null) {
ArrayList<HashMap<String, String>> tmpAllData = allData;
ArrayList<HashMap<String, String>> tmpDataShown = data;
tmpDataShown.clear();
for (int i = 0; i < tmpAllData.size(); i++) {
if (tmpAllData.get(i).get(FriendsListActivity.KEY_NAME)
.toLowerCase()
.startsWith(s.toString().toLowerCase())) {
tmpDataShown.add(tmpAllData.get(i));
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = tmpDataShown;
filterResults.count = tmpDataShown.size();
return filterResults;
} else {
return new FilterResults();
}
}
#SuppressWarnings("unchecked")
protected void publishResults(CharSequence prefix, FilterResults results) {
data = (ArrayList<HashMap<String, String>>) results.values;
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
public class AppRequestsListener extends BaseDialogListener {
#Override
public void onComplete(Bundle values) {
Toast.makeText(activity, "App request sent", Toast.LENGTH_SHORT)
.show();
activity.startActivity(new Intent(activity,
TruthorDareActivity.class));
}
#Override
public void onFacebookError(FacebookError error) {
Toast.makeText(activity, "Facebook Error: " + error.getMessage(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onCancel() {
Toast.makeText(activity, "App request cancelled",
Toast.LENGTH_SHORT).show();
}
}
}
In the getFilter() method try this
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
mDataShown = (ArrayList<HashMap<String, String>>)results.values;
ProjectListAdapter.this.setListData(mDataShown);
ProjectListAdapter.this.notifyDataSetChanged();
};
And to refresh the list on backspace
private TextWatcher filterTextWatcher = 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) {
if(s.toString().equalsIgnoreCase(""))
{
adapter.setListData(projectListdata)
adapter.notifyDataSetChanged();
}
else
adapter.getFilter().filter(s);
}
};