How to parse local xml file to get country details android? - android

i have to parse xml file to get country details like country name and country postal code.
how can i parse country names to spinner adapter and when i select perticular country using spinner i have to display particular country code in textview.
please help me.
Thanks in advance.

Here is a code to parse Xml file where you will have to pass inputstream of your local xml file.
public static ArrayList<Country> parseCountry(Context context, InputStream inputStream) {
String KEY = "";
String VALUE = null;
ArrayList<Country> arrCountires = new ArrayList<Country>();
Country country = null;
ArrayList<State> arrStates = null;
State state= null;
ArrayList<City> arrCities = null;
City city = null;
try {
InputStreamReader inputreader = null;
if(inputStream != null) {
inputreader = new InputStreamReader(inputStream);
}
if(inputreader != null) {
XmlPullParserFactory factory = null;
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = null;
xpp = factory.newPullParser();
xpp.setInput(inputreader);
int eventType = 0;
eventType = xpp.getEventType();
eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if(eventType == XmlPullParser.START_TAG) {
KEY = xpp.getName();
if(KEY.equalsIgnoreCase(TAGS.COUNTRIES)) {
arrCountires = new ArrayList<Country>();
}else if(KEY.equalsIgnoreCase(TAGS.COUNTRY)) {
country = new Country();
arrStates = new ArrayList<State>();
country.setCountryId(xpp.getAttributeValue(null, TAGS.ID));
}else if(KEY.equalsIgnoreCase(TAGS.STATE)) {
state = new State();
arrCities = new ArrayList<City>();
state.setStateId(xpp.getAttributeValue(null, TAGS.ID));
}else if(KEY.equalsIgnoreCase(TAGS.CITY)) {
city = new City();
city.setCityId(xpp.getAttributeValue(null, TAGS.ID));
}
}else if(eventType == XmlPullParser.END_TAG) {
KEY = xpp.getName();
if(KEY.equalsIgnoreCase(TAGS.COUNTRY)) {
country.setArrStates(arrStates);
arrCountires.add(country);
}else if(KEY.equalsIgnoreCase(TAGS.COUNTRY_NAME)) {
country.setCountryName(VALUE);
}else if(KEY.equalsIgnoreCase(TAGS.STATE_NAME)) {
state.setStateName(VALUE);
}else if(KEY.equalsIgnoreCase(TAGS.STATE)) {
state.setArrCities(arrCities);
arrStates.add(state);
}else if(KEY.equalsIgnoreCase(TAGS.CITY)) {
arrCities.add(city);
}else if(KEY.equalsIgnoreCase(TAGS.CITY_NAME)) {
city.setCityName(VALUE);
}
}else if(eventType == XmlPullParser.TEXT) {
VALUE = xpp.getText();
}
eventType = xpp.next();
}
}
}
catch (Exception e) {
e.printStackTrace();
}finally {
if(inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return arrCountires;
}
Here is a Country class with Getter and Setter methods.
public class Country {
String countryId;
String countryName;
ArrayList<State> arrStates;
public ArrayList<State> getArrStates() {
return arrStates;
}
public void setArrStates(ArrayList<State> arrStates) {
this.arrStates = arrStates;
}
public String getCountryId() {
return countryId;
}
public void setCountryId(String countryId) {
this.countryId = countryId;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
}
Here is a Adapter class to set country in the spinner.
private class CountryAdapter implements SpinnerAdapter{
ArrayList<Country> data;
public CountryAdapter(ArrayList<Country> data){
this.data = data;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return android.R.layout.simple_spinner_dropdown_item;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView v = new TextView(getApplicationContext());
v.setTextColor(Color.BLACK);
v.setText(data.get(position).getName());
v.setTextSize(15);
v.setPadding(10, 10, 10, 10);
v.setSingleLine();
v.setEllipsize(TruncateAt.END);
return v;
}
#Override
public int getViewTypeCount() {
return android.R.layout.simple_spinner_item;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isEmpty() {
return false;
}
#Override
public void registerDataSetObserver(DataSetObserver observer) {
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer) {
}
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
return this.getView(position, convertView, parent);
}
}
Here is a Interface by which you can get the selected country from the spinner
OnItemSelectedListener OnCountrySelected = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View v, int position,
long id) {
if(position != AdapterView.INVALID_POSITION) {
System.out.println("Country name = " + arrCountries.get(position).getName());
//Here you can set this value to the textview
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
};
Here is a way how you can set the Listener to the spinner
spCountry.setOnItemSelectedListener(OnCountrySelected);
Here is a code to open file as inputstream from assets
try {
InputStream inputStream = v.getContext().getAssets().open("path of file");
ArrayList<Country> arrCountries = parseCountry(this, inputStream);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
When you get the response in the array of Country then set adapter to the spinner
CountryAdapter countryAdapter = new CountryAdapter(arrCountry);
spCountry.setAdapter(countryAdapter);

Related

search in listview only refreshes the whole list and does not get the result into list

I am getting the data from server using JSON and when i try to search in the listview it just refreshes the whole list and does not narrate it, but when i debug i can see the result on getfilter is right right and it drugsFiltered = (ArrayList<drugs_json_data>) results.values; does have the filtered data inside it. just the listview.setadaptor is being done inside onPostExecute of the asynctask.
here is my adapter code:
public class drugs_adaptor_listView extends ArrayAdapter<drugs_json_data> implements Filterable {
ArrayList<drugs_json_data> drugs;
ArrayList<drugs_json_data> drugsFiltered;
Context context;
int resource;
public drugs_adaptor_listView(Context context, int resource, ArrayList<drugs_json_data> drugs) {
super(context, resource, drugs);
this.drugs = drugs;
this.drugsFiltered = drugs;
this.context = context;
this.resource = resource;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View r = convertView;
ViewHolder viewHolder;
if (r == null) {
LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
r = layoutInflater.inflate(R.layout.row_layout_drugs, null, true);
viewHolder = new ViewHolder(r);
r.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) r.getTag();
}
drugs_json_data drugs_json_data = getItem(position);
viewHolder.txtDrugId.setText(drugs_json_data.getDrugId());
viewHolder.txtDrugName.setText(drugs_json_data.getDrugName());
viewHolder.txtDrugCategory.setText(drugs_json_data.getDrugCategory());
Picasso builder = new Picasso.Builder(context).build();
builder.load(drugs_json_data.getDrugImage()).memoryPolicy(MemoryPolicy.NO_STORE).placeholder(R.drawable.ic_launcher_foreground).into(viewHolder.imageView);
return r;
}
#NonNull
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
drugsFiltered = (ArrayList<drugs_json_data>) results.values; // has the filtered values
if (results.count>0) {
notifyDataSetChanged(); // notifies the data with new filtered values
}else {
notifyDataSetInvalidated();
}
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values
ArrayList<drugs_json_data> FilteredArrList = new ArrayList<>();
if (drugs == null) {
drugs = new ArrayList<>(drugsFiltered); // saves the original data in mOriginalValues
}
if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = drugs.size();
results.values = drugs;
} else {
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < drugs.size(); i++) {
String data = drugs.get(i).getDrugName();
if (data.startsWith(constraint.toString())) {
FilteredArrList.add(new drugs_json_data(drugs.get(i).getDrugId(), drugs.get(i).getDrugName(), drugs.get(i).getDrugCategory(), drugs.get(i).getDrugImage()));
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
return filter;
}
class ViewHolder {
TextView txtDrugId, txtDrugName, txtDrugCategory;
ImageView imageView;
ViewHolder(View v) {
txtDrugId = v.findViewById(R.id.txtDrugId);
txtDrugName = v.findViewById(R.id.txtDrugName);
txtDrugCategory = v.findViewById(R.id.txtDrugCat);
imageView = v.findViewById(R.id.ImageViewDrug);
}
}
}
here is the data model:
public class drugs_json_data {
private String drugImage;
private String drugName;
private String drugCategory;
private String drugId;
public drugs_json_data(String drugImage, String drugName, String drugCategory, String drugId) {
this.drugImage = drugImage;
this.drugName = drugName;
this.drugCategory = drugCategory;
this.drugId = drugId;
}
public String getDrugImage() {
return this.drugImage;
}
public void setDrugImage(String drugImage) {
this.drugImage = drugImage;
}
public String getDrugName() {
return this.drugName;
}
public void setDrugName(String drugName) {
this.drugName = drugName;
}
public String getDrugCategory() {
return this.drugCategory;
}
public void setDrugCategory(String drugCategory) {
this.drugCategory = drugCategory;
}
public String getDrugId() {
return this.drugId;
}
public void setDrugId(String drugId) {
this.drugId = drugId;
}
}
and here is the main activity code:
public class clerk_drugs extends AppCompatActivity {
ListView listView;
Button createDrug;
String drug_id, json_drug;
TextView noMed;
EditText searchTxt;
JSONObject jsonObject;
JSONArray jsonArray;
ArrayList<drugs_json_data> arrayList;
drugs_adaptor_listView adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clerk_drugs);
createDrug = findViewById(R.id.create_drug);
arrayList = new ArrayList<>();
listView = findViewById(R.id.list_drugs);
noMed = findViewById(R.id.no_med);
searchTxt = findViewById(R.id.listSearch);
searchTxt.setSingleLine(true);
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
new ReadJSON().execute("http://(mylink)").get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
try {
jsonObject = new JSONObject(json_drug);
jsonArray = jsonObject.getJSONArray("server_response");
} catch (JSONException e) {
e.printStackTrace();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
drug_id = ((TextView) view.findViewById(R.id.txtDrugId)).getText().toString();
for (int i = 0; i<jsonArray.length(); i++){
try {
JSONObject jobj = jsonArray.getJSONObject(i);
String drugid = jobj.getString("drug_id");
if(drugid.equals(drug_id)) {
String drugname = jobj.getString("drug_name");
String drugcategory = jobj.getString("drug_category");
String drugdescription = jobj.getString("drug_description");
String drugphoto = jobj.getString("drug_photo");
drug_update_dialog drug_update_dialog = new drug_update_dialog();
Bundle args = new Bundle();
args.putString("drug-id", drug_id);
args.putString("drug-name", drugname);
args.putString("drug-category", drugcategory);
args.putString("drug-description", drugdescription);
args.putString("drug_photo",drugphoto);
drug_update_dialog.setArguments(args);
drug_update_dialog.show(getSupportFragmentManager(),"ویرایش اطلاعات دارو");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
searchTxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s.toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
searchTxt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus){
hideKeyboard(v);
}
}
});
}
public void hideKeyboard(View view) {
InputMethodManager inputMethodManager =(InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
class ReadJSON extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
try {
JSONObject jsonObject = new JSONObject(content);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
for(int i=0; i<jsonArray.length();i++){
JSONObject drugObj = jsonArray.getJSONObject(i);
arrayList.add(new drugs_json_data(
drugObj.getString("drug_photo"),
drugObj.getString("drug_name"),
drugObj.getString("drug_category"),
drugObj.getString("drug_id")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter = new drugs_adaptor_listView(
getApplicationContext(), R.layout.row_layout_drugs, arrayList
);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
if (adapter.getCount()==0){
noMed.setVisibility(View.VISIBLE);
}
}
}
private String readURL(String theURL) {
StringBuilder content = new StringBuilder();
try{
URL url = new URL(theURL);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while((line=bufferedReader.readLine())!=null){
content.append(line).append("\n");
}
bufferedReader.close();
}catch (Exception e){
e.printStackTrace();
}
json_drug = content.toString();
return content.toString();
}
#Override
public void onBackPressed() {
finish();
Intent intent = new Intent(this,patient_mainPage.class);
startActivity(intent);
}
public void createDrugDialog(View view){
openDrugDialog();
}
private void openDrugDialog() {
drug_add_dialog drug_add_dialog = new drug_add_dialog();
drug_add_dialog.show(getSupportFragmentManager(),"ثبت داروی جدید");
}
}
I would be grateful if someone could help.
UPDATED
In getView method in Adapter
Replace
drugs_json_data drugs_json_data = getItem(position);
With
drugs_json_data drugs_json_data = drugsFiltered.get(position);

How to do Filter listview in android?

How to do the Filter concept from Below design? I here by attached two screen designs.
DashBoard Fragment -> Having Listview with Base adapter.
The above ListView code is given Below
DashBoardRefactor
public class DashBoardRefactor extends Fragment {
public static ProgressDialog progress;
public static List<DashListModel> dashRowList1 = new ArrayList<DashListModel>();
public static View footerView;
// #Bind(R.id.dashListView)
public static ListView dashListView;
int preCount = 2, scroll_Inc = 10, lastCount;
boolean flag = true;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dashboard_fragment, container, false);
ButterKnife.bind(this, v);
setHasOptionsMenu(true);
progress = new ProgressDialog(getActivity());
dashListView = (ListView) v.findViewById(R.id.dashListView);
footerView = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.dashboard_list_footer, null, false);
dashListView.addFooterView(footerView);
footerView.setVisibility(View.GONE);
dashRowList1.clear();
dashboardViewTask();
dashListView.setOnScrollListener(new EndlessScrollListener(getActivity(), dashListView, footerView));
return v;
}
public void dashboardViewTask() {
progress.setMessage("Loading...");
progress.setCanceledOnTouchOutside(false);
progress.setCancelable(false);
progress.show();
// footerView.setVisibility(View.VISIBLE);
Map<String, String> params = new HashMap<String, String>();
Log.e("candidate_id", "candidate_id---->" + SessionStores.getBullHornId(getActivity()));
params.put("candidate_id", SessionStores.getBullHornId(getActivity()));
params.put("employmentPreference", SessionStores.getEmploymentPreference(getActivity()));
params.put("page", "1");
new DashBoardTask(getActivity(), params, dashListView, footerView);
}
#Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {
if (menu != null) {
menu.removeItem(R.id.menu_notify);
}
inflater.inflate(R.menu.menu_options, menu);
MenuItem item = menu.findItem(R.id.menu_filter);
item.setVisible(true);
getActivity().invalidateOptionsMenu();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.his__menu_accept:
Toast.makeText(getActivity(), "clicked dashboard menu accept", Toast.LENGTH_LONG).show();
return true;
case R.id.menu_filter:
// click evnt for filter
Toast.makeText(getActivity(), "clicked dashboard filter", Toast.LENGTH_LONG).show();
Intent filter_intent = new Intent(getActivity(), DashBoardFilterScreen.class);
startActivity(filter_intent);
getActivity().overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onPause() {
super.onPause();
// dashboardViewTask();
}
}
DashBoardTask:
public class DashBoardTask {
public static String candidateIdNo;
public static Integer isBookmarked;
public ListAdapter dashListAdapter;
ListView dashListView;
View footerView;
String fromdate_formated = "";
String todate_formated = "";
private Context context;
private JSONObject jObject = null;
private String result, authorizationKey;
private Map<String, String> params;
public DashBoardTask(Context context, Map<String, String> params, ListView dashListView, View footerView) {
this.context = context;
Log.e("context ", "DashBoardTask: " + context);
this.dashListView = dashListView;
Dashboard.dashRowList.clear();
this.params = params;
this.footerView = footerView;
ResponseTask();
}
private void ResponseTask() {
authorizationKey = Constants.ACCESS_TOKEN;
new ServerResponse(ApiClass.getApiUrl(Constants.DASHBOARD_VIEW)).getJSONObjectfromURL(ServerResponse.RequestType.POST, params, authorizationKey, context, "", new VolleyResponseListener() {
#Override
public void onError(String message) {
if (DashBoardRefactor.progress.isShowing()) {
DashBoardRefactor.progress.dismiss();
}
}
#Override
public void onResponse(String response) {
String dateEnd = "", startDate = "";
result = response.toString();
try {
jObject = new JSONObject(result);
if (jObject != null) {
Integer totalJobList = jObject.getInt("page_count");
Integer total = jObject.getInt("total");
Integer count = jObject.getInt("count");
Integer start = jObject.getInt("start");
if (footerView.isShown() && count == 0) {
footerView.setVisibility(View.GONE);
}
Integer Status = jObject.getInt("status");
if (Status == 1) {
SessionStores.savetotalJobList(totalJobList, context);
JSONArray dataObject = jObject.getJSONArray("data");
Dashboard.dashRowList.clear();
for (int i = 0; i < dataObject.length(); i++) {
Log.e("length", "lenght----->" + dataObject.length());
JSONObject jobDetail = dataObject.getJSONObject(i);
Log.e("jobDetail", "jobDetail----->" + jobDetail);
Integer goalsName = jobDetail.getInt("id");
String compnyTitle = jobDetail.getString("title");
String description = jobDetail.getString("description");
Integer salary = jobDetail.getInt("salary");
String dateAdded = jobDetail.getString("dateAdded");
if (jobDetail.getString("startDate") != null && !jobDetail.getString("startDate").isEmpty() && !jobDetail.getString("startDate").equals("null")) {
startDate = jobDetail.getString("startDate");
} else {
Log.e("Task Null", "Task Null----startDate->");
}
if (jobDetail.getString("dateEnd") != null && !jobDetail.getString("dateEnd").isEmpty() && !jobDetail.getString("dateEnd").equals("null")) {
dateEnd = jobDetail.getString("dateEnd");
} else {
Log.e("Task Null", "Task Null----->");
}
isBookmarked = jobDetail.getInt("isBookmarked");
Integer startSalary = jobDetail.getInt("customFloat1");
Integer endSalary = jobDetail.getInt("customFloat2");
JSONObject cmpanyName = jobDetail.getJSONObject("clientCorporation");
String compnyNamede = cmpanyName.getString("name");
String city = jobDetail.getString("customText1");
JSONObject candidateId = jobDetail.getJSONObject("clientContact");
candidateIdNo = candidateId.getString("id");
DashListModel dashListItem = new DashListModel();
dashListItem.setDashCompanyName(compnyNamede);
dashListItem.setDashJobDescription(description);
dashListItem.setDashJobPosition(compnyTitle);
dashListItem.setDashJobCity(city);
// dashListItem.setDashJobState(state);
dashListItem.setDashSalary(startSalary.toString());
dashListItem.setDashJobAvailableDate(dateAdded);
dashListItem.setDashId(goalsName.toString());
dashListItem.setDashIsBookMarked(isBookmarked.toString());
dashListItem.setDashEndSalary(endSalary.toString());
dashListItem.setToDate(dateEnd);
////////////////////////////////////
String fromDate = null, toDate = null, postedDate = null;
if (startDate.length() > 11) {
Log.e("11", "11---->");
fromDate = Utils.convertFromUnixDateAdded(startDate);
} else if (startDate.length() == 10) {
Log.e("10", "10----->");
fromDate = Utils.convertFromUnix(startDate);
}
if (dateEnd.length() > 11) {
Log.e("11", "11---->");
toDate = Utils.convertFromUnixDateAdded(dateEnd);
} else if (dateEnd.length() == 10) {
Log.e("10", "10----->");
toDate = Utils.convertFromUnix(dateEnd);
}
if (dateAdded.length() > 11) {
Log.e("11", "11---->");
postedDate = Utils.convertFromUnixDateAdded(dateAdded);
} else if (dateAdded.length() == 10) {
Log.e("10", "10----->");
postedDate = Utils.convertFromUnix(dateAdded);
}
try {
if (!fromDate.isEmpty() || !fromDate.equalsIgnoreCase("null")) {
String[] fromDateSplit = fromDate.split("/");
String fromMonth = fromDateSplit[0];
String fromDat = fromDateSplit[1];
String fromYear = fromDateSplit[2];
String fromMonthName = new DateFormatSymbols().getMonths()[Integer.parseInt(fromMonth) - 1];
fromdate_formated = fromMonthName.substring(0, 3) + " " + fromDat + getDayOfMonthSuffix(Integer.parseInt(fromDat));
Log.e("fromdate", "fromdate---->" + fromDate);
Log.e("toDate", "toDate---->" + toDate);
Log.e("fromMonth", "fromMonth---->" + fromMonth);
Log.e("fromDat", "fromDat---->" + fromDat);
Log.e("fromYear", "fromYear---->" + fromYear);
}
if (!toDate.isEmpty() || !toDate.equalsIgnoreCase("null")) {
String[] toDateSplit = toDate.split("/");
String toMonth = toDateSplit[0];
String toDat = toDateSplit[1];
String toYear = toDateSplit[2];
String toMonthName = new DateFormatSymbols().getMonths()[Integer.parseInt(toMonth) - 1];
todate_formated = toMonthName.substring(0, 3) + " " + toDat + getDayOfMonthSuffix(Integer.parseInt(toDat)) + " " + toYear;
Log.e("________________", "-------------------->");
Log.e("toMonth", "toMonth---->" + toMonth);
Log.e("toDat", "toDat---->" + toDat);
Log.e("toYear", "toYear---->" + toYear);
Log.e("________________", "-------------------->");
Log.e("toMonthName", "toMonthName---->" + toMonthName);
}
} catch (Exception e) {
e.printStackTrace();
}
dashListItem.setPostedDate(postedDate);
dashListItem.setFromDate(fromdate_formated);
dashListItem.setEndDate(todate_formated);
/////////////////////////////////////////
// Dashboard.dashRowList.add(dashListItem);
DashBoardRefactor.dashRowList1.add(dashListItem);
}
// get listview current position - used to maintain scroll position
int currentPosition = dashListView.getFirstVisiblePosition();
dashListAdapter = new DashListAdapter(context, DashBoardRefactor.dashRowList1, dashListView);
dashListView.setAdapter(dashListAdapter);
((BaseAdapter) dashListAdapter).notifyDataSetChanged();
if (currentPosition != 0) {
// Setting new scroll position
dashListView.setSelectionFromTop(currentPosition + 1, 0);
}
} else if (Status==0 && count==0 && start==0){
String Message = jObject.getString("message");
Utils.ShowAlert(context, Message);
}
if (footerView.isShown()) {
footerView.setVisibility(View.GONE);
}
//progress.dismiss();
if (DashBoardRefactor.progress.isShowing()) {
try {
DashBoardRefactor.progress.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
}
DashListModel:
public class DashListModel {
private String dashCompanyName;
private String dashJobPosition;
private String dashJobPostedDate;
private String dashJobDescription;
private String dashSalary;
private String dashJobCity;
private String dashJobState;
private String dashJobAvailableDate;
private String dashId, dashIsBookmarked;
private String dashEndSalary;
private String toDate;
private String postedDate, fromdate, enddate;
public String getDashCompanyName() {
return dashCompanyName;
}
public void setDashCompanyName(String dashCompanyName) {
this.dashCompanyName = dashCompanyName;
}
public String getDashJobPosition() {
return dashJobPosition;
}
public void setDashJobPosition(String dashJobPosition) {
this.dashJobPosition = dashJobPosition;
}
public String getDashJobDescription() {
return dashJobDescription;
}
public void setDashJobDescription(String dashJobDescription) {
this.dashJobDescription = dashJobDescription;
}
public String getDashJobPostedDate() {
return dashJobPostedDate;
}
public void setDashJobPostedDate(String dashJobPostedDate) {
this.dashJobPostedDate = dashJobPostedDate;
}
public String getDashSalary() {
return dashSalary;
}
public void setDashSalary(String dashSalary) {
this.dashSalary = dashSalary;
}
public String getDashJobCity() {
return dashJobCity;
}
public void setDashJobCity(String dashJobCity) {
this.dashJobCity = dashJobCity;
}
/* public String getDashJobState() {
return dashJobState;
}
public void setDashJobState(String dashJobState) {
this.dashJobState = dashJobState;
}*/
public String getDashJobAvailableDate() {
return dashJobAvailableDate;
}
public void setDashJobAvailableDate(String dashJobAvailableDate) {
this.dashJobAvailableDate = dashJobAvailableDate;
}
public String getDashId() {
return dashId;
}
public void setDashId(String dashId) {
this.dashId = dashId;
}
public String getDashIsBookmarked() {
return dashIsBookmarked;
}
public void setDashIsBookMarked(String dashIsBookmarked) {
this.dashIsBookmarked = dashIsBookmarked;
}
public String getDashEndSalary() {
return dashEndSalary;
}
public void setDashEndSalary(String dashEndSalary) {
this.dashEndSalary = dashEndSalary;
}
public String getToDate() {
return toDate;
}
public void setToDate(String toDate) {
this.toDate = toDate;
}
public String getPostedDate() {
return postedDate;
}
public void setPostedDate(String postedDate) {
this.postedDate = postedDate;
}
public String getFromDate() {
return fromdate;
}
public void setFromDate(String fromdate) {
this.fromdate = fromdate;
}
public String getEndDate() {
return enddate;
}
public void setEndDate(String enddate) {
this.enddate = enddate;
}
DashListAdapter:
package com.peoplecaddie.adapter;
public class DashListAdapter extends BaseAdapter {
public static ListView dashListView;
Context c;
private LayoutInflater inflater;
private List<DashListModel> dashRowList;
public DashListAdapter(Context c, List<DashListModel> dashRowList, ListView dashListView) {
this.c = c;
this.dashListView = dashListView;
this.dashRowList = dashRowList;
}
#Override
public int getCount() {
return this.dashRowList.size();
}
#Override
public Object getItem(int position) {
return dashRowList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder dashHolder;
if (inflater == null)
inflater = (LayoutInflater) c
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.dashboard_jobdetails_list, null);
final DashListModel dashModel = dashRowList.get(position);
dashHolder = new ViewHolder(convertView);
dashHolder.dash_company_name.setText(dashModel.getDashCompanyName());
dashHolder.dash_position_name.setText(dashModel.getDashJobPosition());
dashHolder.dash_posted_date.setText(dashModel.getPostedDate());
dashHolder.dash_job_description.setText(Utils.stripHtml(dashModel.getDashJobDescription()));
dashHolder.dash_salary.setText(dashModel.getDashSalary() + " - " + dashModel.getDashEndSalary());
dashHolder.dash_available_date.setText(dashModel.getFromDate() + " - " + dashModel.getEndDate());
dashHolder.book_jobCity.setText(dashModel.getDashJobCity());
if (dashModel.getDashIsBookmarked().equalsIgnoreCase("1")) {
dashHolder.bookmark_img.setImageResource(R.drawable.bookmark);
} else if (dashModel.getDashIsBookmarked().equalsIgnoreCase("0")) {
dashHolder.bookmark_img.setImageResource(R.drawable.blue_tag_img);
}
dashHolder.bookmark_img.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (dashModel.getDashIsBookmarked().equalsIgnoreCase("0")) {
dashModel.setDashIsBookMarked("1");
Map<String, String> params = new HashMap<String, String>();
params.put("candidate_id", SessionStores.getBullHornId(c));
params.put("joborder_id", dashModel.getDashId());
BackGroundTasks bookmark_add_bg_tasks = new BackGroundTasks(c, new JSONObject(params), Constants.BOOKMARK_ADD_TAG);
bookmark_add_bg_tasks.ResponseTask(new BackGroundTasks.VolleyCallbackOnEdit() {
#Override
public void onSuccess(String result) {
String resp_resultsd = result;
Log.e("insidecallback", " bookmark_add_bg_tasks----->" + resp_resultsd);
// finish();
dashHolder.bookmark_img.setImageResource(R.drawable.bookmark);
notifyDataSetChanged();
}
});
} else if (dashModel.getDashIsBookmarked().equalsIgnoreCase("1")) {
dashModel.setDashIsBookMarked("0");
Log.e("imgchange", " imgchange");
Map<String, String> params = new HashMap<String, String>();
params.put("candidate_id", SessionStores.getBullHornId(c));
params.put("joborder_id", dashModel.getDashId());
BackGroundTasks bookmark_delete_bg_tasks = new BackGroundTasks(c, new JSONObject(params), Constants.BOOKMARK_DELETE_TAG);
bookmark_delete_bg_tasks.ResponseTask(new BackGroundTasks.VolleyCallbackOnEdit() {
#Override
public void onSuccess(String result) {
String resp_resultsd = result;
Log.e("insidecallback", " bookmark_delete_bg_tasks----->" + resp_resultsd);
// finish();
dashHolder.bookmark_img.setImageResource(R.drawable.blue_tag_img);
notifyDataSetChanged();
}
});
}
}
});
return convertView;
}
static class ViewHolder {
#Bind(R.id.book_company_name)
TextView dash_company_name;
private RelativeLayout.LayoutParams viewLayParams;
public ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
}
Clarification:
How do to Filter while click the Filter Button On DashBoard Fragment. Please Suggest the way. I here by attached My Filter design also.
Dashboard Fragment--> Filter Button-> Filter screen-> the Filtered results should view on DashBoard Fragment.
Once click the apply Button Based on the input from Filter screen it filters the list view the result comes from back end team. I have to display that result on Dashboard Fragment.
Kindly please clarify this Filter concept.

Android ListView doesn't populate

This is simple Android project that I did. I get no warnings or errors while running. But the ListView doesn't get populated. I don't understand what's going wrong.
Since I dont' understand where is the exact problem and copy-pasting all the code won't help, here is my project code repository: https://bitbucket.org/geejo/msk-v2
Any kind of help will be appreciated
MSKFragment.java
public class MSKFragment extends android.support.v4.app.Fragment implements android.support.v4.app.LoaderManager.LoaderCallbacks<Cursor>
{
private ServiceAdapter mServiceAdapter;
public static final int SERVICE_LOADER = 0;
private static final String[] SERVICE_COLUMNS =
{
ServiceContract.ServiceEntry.TABLE_NAME,
ServiceContract.ServiceEntry._ID,
ServiceContract.ServiceEntry.COLUMN_NAME,
ServiceContract.ServiceEntry.COLUMN_ORGANIZATION_NAME,
ServiceContract.ServiceEntry.COLUMN_PRICE
};
public static final int COL_ID = 0;
public static final int COL_NAME = 1;
public static final int COL_ORG_NAME = 2;
public static final int COL_PRICE = 3;
public MSKFragment()
{
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
getLoaderManager().initLoader(SERVICE_LOADER, null, this);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
inflater.inflate(R.menu.menu_fragment_msk, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_refresh)
{
//Moving functions to a helper class, so that when Activity starts the data can be displayed
updateServices();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
mServiceAdapter = new ServiceAdapter(getActivity(), null, 0);
View rootView = inflater.inflate(R.layout.fragment_msk, container, false);
ListView listView = (ListView) rootView.findViewById(R.id.listViewMainService);
listView.setAdapter(mServiceAdapter);
return rootView;
}
#Override
public void onStart()
{
super.onStart();
//Refresh called and service updated when activity starts
updateServices();
}
//Calling FetchServiceTask and executing it.
private void updateServices()
{
FetchServicesTask serviceTask = new FetchServicesTask(getActivity());
serviceTask.execute();
}
#Override
public android.support.v4.content.Loader<Cursor> onCreateLoader(int i, Bundle args)
{
Uri serviceUri = ServiceContract.ServiceEntry.buildServiceUri(i);
return new android.support.v4.content.CursorLoader(getActivity(), serviceUri, null, null, null, null);
}
#Override
public void onLoadFinished(android.support.v4.content.Loader<Cursor> loader, Cursor data)
{
mServiceAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(android.support.v4.content.Loader<Cursor> loader)
{
mServiceAdapter.swapCursor(null);
}
}
FetchServices.java (AsyncTasks)
public class FetchServicesTask extends AsyncTask<String, Void, Void>
{
private final String LOG_TAG = FetchServicesTask.class.getSimpleName();
private final Context mContext;
private boolean DEBUG = true;
public FetchServicesTask(Context context )
{
mContext = context;
}
private String[] getServicesDatafromJson(String serviceJsonStr) throws JSONException
{
final String MSK_NAME = "name";
final String MSK_PRICE = "price";
final String MSK_ORG_NAME = "organizationName";
final String MSK_POSTED_USER = "postedUser";
final String MSK_PROFILE = "profile";
int totalResults = 25;
String resultStrs[] = new String[totalResults];
try
{
JSONArray serviceArray = new JSONArray(serviceJsonStr);
Vector<ContentValues> cVVector = new Vector<ContentValues>(serviceArray.length());
for(int i=0;i<serviceArray.length();i++)
{
String name, organizationName;
int price;
JSONObject serviceObject = serviceArray.getJSONObject(i);
name = serviceObject.getString(MSK_NAME);
price = serviceObject.getInt(MSK_PRICE);
JSONObject postedUserObject = serviceObject.getJSONObject(MSK_POSTED_USER);
JSONObject profileObject = postedUserObject.getJSONObject(MSK_PROFILE);
organizationName = profileObject.getString(MSK_ORG_NAME);
ContentValues serviceValues = new ContentValues();
serviceValues.put(ServiceContract.ServiceEntry.COLUMN_NAME, name);
serviceValues.put(ServiceContract.ServiceEntry.COLUMN_ORGANIZATION_NAME, organizationName);
serviceValues.put(ServiceContract.ServiceEntry.COLUMN_PRICE, price);
cVVector.add(serviceValues);
}
int inserted = 0;
if(cVVector.size()>0)
{
ContentValues[] cvArray = new ContentValues[cVVector.size()];
cVVector.toArray(cvArray);
inserted = mContext.getContentResolver().bulkInsert(ServiceContract.ServiceEntry.CONTENT_URI, cvArray);
}
Log.d(LOG_TAG, "FetchServicesTask Complete. " + inserted + " Inserted");
}
catch(JSONException e)
{
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
/////////////////////////////// NETWORKING BOILER PLATE ///////////////////////////
#Override
protected Void doInBackground(String... params)
{
if (params.length == 0)
{
return null;
}
HttpURLConnection urlConnection = null; //Streaming data using HTTP
String serviceJsonStr = null; //raw JSON response
BufferedReader reader = null; //read text from character i/p stream
int pageNo = 1;
int numResults = 5;
try
{
//-------------------------CONNECTION--------------------//
final String SERVICE_BASE_URL = "http://myservicekart.com/public/";
final String SEARCH_BASE_URL = "http://myservicekart.com/public/search?";
final String SEARCH_PARAM = "search";
final String PAGE_PARAM = "pageno";
/*Using a helper class UriBuilder for building and manipulating URI references*/
Uri builtServiceUri = Uri.parse(SERVICE_BASE_URL);
Uri builtSearchUri = Uri.parse(SEARCH_BASE_URL).buildUpon().
appendQueryParameter(SEARCH_PARAM, "").
appendQueryParameter(PAGE_PARAM, Integer.toString(pageNo)).
build();
URL searchUrl = new URL(builtSearchUri.toString());
Log.v(LOG_TAG, "Built SearchUri" +builtSearchUri.toString());
urlConnection = (HttpURLConnection) searchUrl.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
//------------------------BUFFERING---------------------//
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if(inputStream==null)
{
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while((line = reader.readLine()) != null)
{
buffer.append(line + "\n");
}
if(buffer.length()==0)
{
return null;
}
serviceJsonStr = buffer.toString();
getServicesDatafromJson(serviceJsonStr);
Log.v(LOG_TAG, "Services JSON String: " +serviceJsonStr);
}
catch(IOException e)
{
Log.e(LOG_TAG, "Error cannot connect to URL", e);
return null;
}
catch (JSONException e)
{
e.printStackTrace();
}
finally
{
if(urlConnection!=null)
{
urlConnection.disconnect();
}
if(reader!=null)
{
try
{
reader.close();
}
catch (final IOException e)
{
Log.e(LOG_TAG,"Error closing stream",e);
}
}
}
return null;
}
}
ServiceAdapter.java
public class ServiceAdapter extends CursorAdapter
{
public ServiceAdapter(Context context, Cursor c, int flags)
{
super(context, c, flags);
}
private String convertCursorRowToUXFormat(Cursor cursor)
{
return cursor.getString(MSKFragment.COL_NAME) + "-" + cursor.getString(MSKFragment.COL_ORG_NAME) +
" - " + cursor.getInt(MSKFragment.COL_PRICE);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent)
{
View view = LayoutInflater.from(context).inflate(R.layout.list_item_main, parent, false);
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor)
{
TextView tv = (TextView)view;
tv.setText(convertCursorRowToUXFormat(cursor));
}
}
change the method newView() in ServiceAdapter.java to :
public View newView(Context context, Cursor cursor, ViewGroup parent){
View view = LayoutInflater.from(context).inflate(android.R.layout.simple_list_item_1, parent, false);
return view;}

how to select multiple items in a listview populated from ArrayList in Android

I am trying to write a program to select multiple items in the listview i populate. but I am having difficulty of selecting multiple items. Please let me know how to do it. Bellow is how i have populate the Arraylist and i have a custom row with checkbox. i need to get the selected items (name, number) on the button click event. Thank you in advance. I have tried to understand the other posts, but since i was unable to relate them to my code, i am not sure of how to do.
public class Contactselect extends Activity {
ListView lv;
EditText et;
int count;
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
String phoneNumber;
String name;
String Name = "Contact";
String Phone = "Phonenumber";
TextWatcher search;
SimpleAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts);
listcontacts();
lv = (ListView) findViewById(R.id.contactlist);
lv.setChoiceMode(lv.CHOICE_MODE_MULTIPLE);
lv.setTextFilterEnabled(true);
adapter = new SimpleAdapter(this, list, R.layout.row, new String[] {
Name, Phone }, new int[] { R.id.names, R.id.numbers });
lv.setAdapter(adapter);
Button b = (Button) findViewById(R.id.done);
b.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
String selected = "";
int cntChoice = lv.getCount();
SparseBooleanArray sparseBooleanArray = lv
.getCheckedItemPositions();
for (int i = 0; i < cntChoice; i++) {
if (sparseBooleanArray.get(i)) {
selected += lv.getItemAtPosition(i).toString() + "\n";
}
}
Toast.makeText(Contactselect.this, selected, Toast.LENGTH_LONG)
.show();
}
});
et = (EditText) findViewById(R.id.search);
et.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
Contactselect.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
private ArrayList<HashMap<String, String>> listcontacts() {
// TODO Auto-generated method stub
FileInputStream fis = null;
try {
fis = openFileInput("contacts.xml");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
XmlPullParserFactory factory;
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = factory.newPullParser();
parser.setInput(new InputStreamReader(fis));
int eventType = parser.getEventType();
int o = 0;
while (eventType != XmlPullParser.END_DOCUMENT) {
HashMap<String, String> map = new HashMap<String, String>();
// set flags for main tags.
if (eventType == XmlPullParser.START_DOCUMENT) {
} else if (eventType == XmlPullParser.START_TAG) {
String tag_name = parser.getName();
if (tag_name.contains("contacts")) {
// Log.i("tag",
// "name"
// + String.valueOf(parser
// .getAttributeValue(0))
// + "......................"
// + "number"
// + String.valueOf(parser
// .getAttributeValue(1)));
name = String.valueOf(parser.getAttributeValue(0));
phoneNumber = String.valueOf(parser
.getAttributeValue(1));
Log.i(name, phoneNumber);
map.put(Name, name);
map.put(Phone, phoneNumber);
list.add(map);
count++;
}
}
try {
eventType = parser.next();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Log.i("End document", "Ended" + count);
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
}
Try this way,hope this will help you to solve your problem.
public class Contactselect extends Activity {
private ListView lv;
private EditText et;
private Button b;
private int count;
private String Name = "Contact";
private String Phone = "Phonenumber";
private String IsSelected = "isSelected";
private ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
private ContactAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.contactlist);
lv.setTextFilterEnabled(true);
et = (EditText) findViewById(R.id.search);
b = (Button) findViewById(R.id.done);
listcontacts();
adapter = new ContactAdapter(this,list);
lv.setAdapter(adapter);
b.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
String selected = "";
for (HashMap<String,String> row : list){
if(row.get(IsSelected).equals("true")){
selected += row.get(Name) + "\n";
}
}
Toast.makeText(Contactselect.this, selected, Toast.LENGTH_LONG)
.show();
}
});
et.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2,int arg3) {
adapter.filter(cs.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,int arg2, int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
}
});
}
private void listcontacts() {
FileInputStream fis = null;
try {
fis = openFileInput("contacts.xml");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
XmlPullParserFactory factory;
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = factory.newPullParser();
parser.setInput(new InputStreamReader(fis));
int eventType = parser.getEventType();
int o = 0;
while (eventType != XmlPullParser.END_DOCUMENT) {
HashMap<String, String> map = new HashMap<String, String>();
// set flags for main tags.
if (eventType == XmlPullParser.START_DOCUMENT) {
} else if (eventType == XmlPullParser.START_TAG) {
String tag_name = parser.getName();
if (tag_name.contains("contacts")) {
// Log.i("tag",
// "name"
// + String.valueOf(parser
// .getAttributeValue(0))
// + "......................"
// + "number"
// + String.valueOf(parser
// .getAttributeValue(1)));
Log.i(name, phoneNumber);
map.put(Name, String.valueOf(parser.getAttributeValue(0)));
map.put(Phone, String.valueOf(parser
.getAttributeValue(1)));
map.put(IsSelected,"false");
list.add(map);
count++;
}
}
try {
eventType = parser.next();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.i("End document", "Ended" + count);
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
class ContactAdapter extends BaseAdapter {
private Context context;
private ArrayList<HashMap<String,String>> contacts;
public ContactAdapter(Context context,ArrayList<HashMap<String,String>> contacts) {
this.context =context;
this.contacts =new ArrayList<HashMap<String, String>>();
this.contacts.addAll(contacts);
}
#Override
public int getCount() {
return contacts.size();
}
#Override
public Object getItem(int position) {
return contacts.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.row, null);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.numbers = (TextView) convertView.findViewById(R.id.numbers);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.checkbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(contacts.get(position).get(Name));
holder.numbers.setText(contacts.get(position).get(Phone));
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton ButtonView, boolean isChecked) {
contacts.get(position).put(IsSelected, "" + isChecked);
for (HashMap<String,String> data : list){
if(data.get(Name).equals(contacts.get(position).get(Name))){
data.put(IsSelected,contacts.get(position).get(IsSelected));
break;
}
}
notifyDataSetChanged();
}
});
if (contacts.get(position).get(IsSelected).toString().equals("false")) {
holder.checkbox.setChecked(false);
} else {
holder.checkbox.setChecked(true);
}
return convertView;
}
public void filter(String charText) {
contacts.clear();
if (charText.length() == 0) {
contacts.addAll(list);
} else {
for (HashMap<String,String> contact : list) {
if (contact.get(Name).toLowerCase().contains(charText.toLowerCase())) {
contacts.add(contact);
}
}
}
notifyDataSetChanged();
}
class ViewHolder {
TextView name;
TextView number;
CheckBox checkbox;
}
}
}

notifyDataSetChanged does not update the listView of custom objects after sorting

I am trying to sort the collection in custom arrayadapter and making a call to update the view . However, the view does not gets updated.
There are two values over which I want to sort (date and amount) and have a custom comparators for them.
I can see that the data itself has changed (i.e if a list item has gone outside of view after sorting and when it gets the view, the data it show is the correct data that should exist after sorting).
The second question is about the filter. The way the filter is implemented right now, it does not update the views either.
Here is code
public class SearchActivity extends BListActivity {
private Bundle sessionInfo;
private TransactionDetailsHandler transactionDetailsHandler = new TransactionDetailsHandler();
private static boolean ascDate = false;
private static boolean ascAmount = false;
private ArrayList<TransactionDetails> transactionDetails;
private ArrayList<TransactionDetails> filterResults;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sessionInfo = getIntent().getExtras();
final String sessionId = sessionInfo.getString("sessionId");
final String transactionResponse = sessionInfo
.getString(C.TRN_DETAIL_KEY);
try {
Xml.parse(transactionResponse, transactionDetailsHandler);
} catch (Exception ex) {
ex.printStackTrace();
}
final ArrayAdapter<TransactionDetails> adapter = getArrayAdapter();
findViewById(R.id.amount_btn).setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
if (ascDate) {
adapter.sort(new TransactionDetailAmountComparatorAsc());
ascDate = false;
} else {
adapter.sort(new TransactionDetailAmountComparatorDesc());
ascDate = true;
}
adapter.notifyDataSetChanged();
}
});
findViewById(R.id.date_btn).setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
if (ascAmount) {
adapter.sort(new TransactionDetailDateComparatorAsc());
ascAmount = false;
} else {
adapter.sort(new TransactionDetailDateComparatorDesc());
ascAmount = true;
}
adapter.notifyDataSetChanged();
}
});
findViewById(R.id.search_btn).setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
findViewById(R.id.buttonLL).setVisibility(View.GONE);
findViewById(R.id.searchLL).setVisibility(View.VISIBLE);
}
});
findViewById(R.id.cancel_btn).setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
findViewById(R.id.searchLL).setVisibility(View.GONE);
findViewById(R.id.buttonLL).setVisibility(View.VISIBLE);
}
});
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) {
System.out.println("XXXX Constraint = " + s);
adapter.getFilter().filter(s);
}
};
EditText et = (EditText) findViewById(R.id.edit_box);
et.addTextChangedListener(filterTextWatcher);
}
protected ArrayAdapter<TransactionDetails> getArrayAdapter() {
transactionDetails = transactionDetailsHandler
.getTransactionDetailsList();
filterResults = transactionDetails;
return new SearchListAdapter(this,
(List<TransactionDetails>) transactionDetails);
}
protected class SearchListAdapter extends ArrayAdapter<TransactionDetails> {
private int rId;
private List<TransactionDetails> data;
private Filter filter;
public SearchListAdapter(Context context, List<TransactionDetails> data) {
super(context, R.layout.search_list_item, data);
this.rId = R.layout.search_list_item;
this.data = data;
}
#Override
public View getView(int position, View cv, ViewGroup parent) {
cv = getLayoutInflater().inflate(rId, parent, false);
TransactionDetails item = data.get(position);
((TextView) cv.findViewById(R.id.t_id)).setText(item.getTrnId());
((TextView) cv.findViewById(R.id.date)).setText(item
.getTrnDatetime());
((TextView) cv.findViewById(R.id.amount)).setText(item
.getTrnAmount());
((TextView) cv.findViewById(R.id.card_num))
.setText("XXXX XXXX XXXX " + item.getTrnMaskedCard());
try {
if (item.getTrnCardType() != null
&& item.getTrnCardType().trim().length() > 0)
((ImageView) cv.findViewById(R.id.card_img))
.setImageResource(Integer.parseInt(item
.getTrnCardType()));
} catch (Exception ex) {
ex.printStackTrace();
}
((TextView) cv.findViewById(R.id.result)).setText(item
.getTrnStatus());
return cv;
}
#Override
public Filter getFilter() {
if (filter == null)
filter = new TransactionDetailFilter();
return filter;
}
private class TransactionDetailFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
System.out.println("XXXX Started filtering with Constraint = "
+ constraint);
FilterResults results = new FilterResults();
String prefix = constraint.toString().toLowerCase();
if (prefix == null || prefix.length() == 0) {
ArrayList<TransactionDetails> list = new ArrayList<TransactionDetails>(
transactionDetails);
results.values = list;
results.count = list.size();
} else {
final ArrayList<TransactionDetails> list = new ArrayList<TransactionDetails>(
transactionDetails);
final ArrayList<TransactionDetails> nlist = new ArrayList<TransactionDetails>();
int count = list.size();
System.out
.println("XXXX List to be search size = " + count);
for (int i = 0; i < count; i++) {
final TransactionDetails details = list.get(i);
System.out.println("XXXX List to be searched = "
+ details.toString());
if (details.getTrnId().startsWith(prefix)
|| details.getTrnDatetime().startsWith(prefix)
|| details.getTrnAmount().startsWith(prefix)
|| details.getTrnMaskedCard()
.startsWith(prefix)
|| details.getTrnStatus().startsWith(prefix)) {
System.out.println("XXXX Adding result "
+ details.toString());
nlist.add(details);
}
}
results.values = nlist;
results.count = nlist.size();
}
System.out.println("XXXX Ended filtering with Constraint = "
+ constraint + " . Result size = " + results.count);
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
System.out.println("XXXX Preparing to publish results. Result size = "+ results.count);
ArrayList<TransactionDetails> fitems = (ArrayList<TransactionDetails>) results.values;
clear();
int count = fitems.size();
for (int i = 0; i < count; i++) {
TransactionDetails details = (TransactionDetails) fitems
.get(i);
add(details);
}
notifyDataSetChanged();
System.out.println("XXXX Finished publishing results.");
}
}
#Override
public void add(TransactionDetails item) {
System.out.println("XXXX Adding items to be published." + item.toString());
filterResults.add(item);
}
}
// -------------------------------------------------------------------------------------------------------------------------------------------------
class TransactionDetailAmountComparatorAsc implements
Comparator<TransactionDetails> {
public int compare(TransactionDetails detail1,
TransactionDetails detail2) {
float f = Float.parseFloat(detail1.getTrnAmount())
- Float.parseFloat(detail2.getTrnAmount());
if (f > 0)
return 1;
if (f < 1)
return -1;
return 0;
}
}
class TransactionDetailAmountComparatorDesc implements
Comparator<TransactionDetails> {
public int compare(TransactionDetails detail1,
TransactionDetails detail2) {
float f = Float.parseFloat(detail1.getTrnAmount())
- Float.parseFloat(detail2.getTrnAmount());
if (f > 0)
return -1;
if (f < 1)
return 1;
return 0;
}
}
class TransactionDetailDateComparatorAsc implements
Comparator<TransactionDetails> {
public int compare(TransactionDetails detail1,
TransactionDetails detail2) {
detail1.getTrnDatetime();
detail2.getTrnDatetime();
String pattern = "MM/dd/yy HH:mm";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
Date date1 = format.parse(detail1.getTrnDatetime());
Date date2 = format.parse(detail2.getTrnDatetime());
return date1.compareTo(date2);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}
class TransactionDetailDateComparatorDesc implements
Comparator<TransactionDetails> {
public int compare(TransactionDetails detail1,
TransactionDetails detail2) {
detail1.getTrnDatetime();
detail2.getTrnDatetime();
String pattern = "MM/dd/yy HH:mm";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
Date date1 = format.parse(detail1.getTrnDatetime());
Date date2 = format.parse(detail2.getTrnDatetime());
return -(date1.compareTo(date2));
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
position -= ((ListView) parent).getHeaderViewsCount();
TransactionDetails details = (TransactionDetails) parent.getAdapter()
.getItem(position);
Bundle b = new Bundle(sessionInfo);
b.putSerializable(C.TRN_DETAIL_KEY, details);
Util.openView(SearchActivity.this, TransDetailActivity.class, b);
}
#Override
protected int getContentView() {
return R.layout.search_layout;
}
#Override
protected int getStringArrayID() {
return 0;
}
#Override
protected Class<?>[] getDestinations() {
return null;
}
#Override
protected int getTitleId() {
return R.string.search;
}
}

Categories

Resources