ListView not displayed with values in android - android

I have made a very simple, form with certain fields,In that i have put a ListView for country List,I am fetching all country names from a webservice,I got all data,But i am unable to set it in ListView,My ListView not visible,Please help me for it.thank you my code is as below:
RegistrationActivity.java
package com.epe.yehki.ui;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.epe.yehki.adapter.CountryAdapter;
import com.epe.yehki.adapter.ProductAdapter;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.backend.RegisterationAPI;
import com.epe.yehki.backend.ResponseListener;
import com.epe.yehki.uc.Menu;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Const.API_RESULT;
import com.example.yehki.R;
public class RegistrationActivity extends Activity {
public RegisterationAPI registartionAPI;
private EditText fName;
private EditText lName;
private EditText eMail;
private Button register;
private CountryAdapter countryContent;
private EditText contact;
private EditText password;
private ListView countrylist;
private ListView statelist;
public static ArrayList<String> countryArray;
private TextView country;
private TextView state;
JSONArray countries = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> countryList;
ArrayList<HashMap<String, String>> stateList;
public com.epe.yehki.uc.Menu regMenu;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_registration);
// FINDING IDS...
fName = (EditText) findViewById(R.id.et_fname);
lName = (EditText) findViewById(R.id.et_lname);
eMail = (EditText) findViewById(R.id.et_email);
contact = (EditText) findViewById(R.id.et_contact);
password = (EditText) findViewById(R.id.et_pwd);
country = (TextView) findViewById(R.id.et_country);
state = (TextView) findViewById(R.id.et_state);
regMenu = (Menu) findViewById(R.id.menuReg);
register = (Button) findViewById(R.id.btn_register);
countryList = new ArrayList<HashMap<String, String>>();
countrylist = (ListView) findViewById(R.id.country_list);
statelist = (ListView) findViewById(R.id.state_list);
countryArray = new ArrayList<String>();
regMenu.setSelectedTab(1);
// COUNTRY LIST CLICK EVENT...!!!
countrylist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
String countryname = ((TextView) view.findViewById(R.id.name)).getText().toString();
country.setText(countryname);
// countrylist.setVisibility(view.GONE);
}
});
// REGISTER BUTTOM CLICK EVENT.....!
register.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (!fName.getText().toString().equals("") && fName.getText().toString() != null) {
if ((!lName.getText().toString().equals("") && lName.getText().toString() != null)) {
if ((!country.getText().toString().equals("") && country.getText().toString() != null)) {
if ((!state.getText().toString().equals("") && state.getText().toString() != null)) {
if ((!eMail.getText().toString().equals("") && eMail.getText().toString() != null)) {
if ((!password.getText().toString().equals("") && password.getText().toString() != null)) {
if ((!contact.getText().toString().equals("") && contact.getText().toString() != null)) {
} else {// CONTACT NUMBER
validation(getResources().getString(R.string.valid_number));
password.requestFocus();
}
} else {// password...
validation(getResources().getString(R.string.valid_pwd));
password.requestFocus();
}
} else {// EMAIL
validation(getResources().getString(R.string.valid_mail));
eMail.requestFocus();
}
} else {// STATE
validation(getResources().getString(R.string.valid_state));
state.requestFocus();
}
} else {// COUNTRY
validation(getResources().getString(R.string.valid_country));
country.requestFocus();
}
} else {// LAST NAME
validation(getResources().getString(R.string.valid_lname));
lName.requestFocus();
}
} else {// FIRST NAME
validation(getResources().getString(R.string.valid_fname));
fName.requestFocus();
}
}
});
// COUINTRY LIST CLICK EVENT...!!!!
country.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
countrylist.setVisibility(View.VISIBLE);
new GetCountries().execute();
}
});
}
void validation(String msg) {
Toast.makeText(RegistrationActivity.this, msg, Toast.LENGTH_SHORT).show();
}
ResponseListener responseListener = new ResponseListener() {
#Override
public void onResponce(String api, API_RESULT result, Object obj) {
System.out.println("::::::::::::::inside response Listener::::::::");
if (progressDialog != null && progressDialog.isShowing())
progressDialog.dismiss();
if (api.equals(Const.API_LOGIN)) {
System.out.println("::::::::::::::inside response Listener::::::::1");
if (result == Const.API_RESULT.SUCCESS) {
registartionAPI = null;
// as
// doctor
System.out.println("success Login::::::::::>>>>>>>>>>>>>>>>>>" + result);
startActivity(new Intent(RegistrationActivity.this, HomeActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
} else {
System.out.println("failed Login::::::::::>>>>>>>>>>>>>>>>>>" + result);
}
}
}
};
// ASYNC TASK FOR GETTING COUNTRY LIST...!!!
private class GetCountries extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
/*
* pDialog = new ProgressDialog(CategoryActivity.this);
* pDialog.setMessage("Please wait...");
* pDialog.setCancelable(false); pDialog.show();
*/
System.out.println("==========inside preexecute===================");
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
BackendAPIService sh = new BackendAPIService();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(Const.API_COUTRY, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
System.out.println("=============MY RESPONSE========== FOR COUNTRYlIST" + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
if (jsonObj.has(Const.TAG_COUNTY_LIST)) {
// looping through All Contacts
countries = jsonObj.getJSONArray(Const.TAG_COUNTY_LIST);
for (int i = 0; i < countries.length(); i++) {
JSONObject c = countries.getJSONObject(i);
String cId = c.getString(Const.TAG_COUNTRY_ID);
String countryName = c.getString(Const.TAG_COUNTRY_NAME);
System.out.println("::::::::::::CountryId:::::::::::::" + countryName);
HashMap<String, String> country = new HashMap<String, String>();
country.put(Const.TAG_COUNTRY_ID, cId);
country.put(Const.TAG_COUNTRY_NAME, countryName);
countryList.add(country);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
countryContent = new CountryAdapter(RegistrationActivity.this, countryList);
countrylist.setAdapter(countryContent);
}
}
}
CountryAdapter.java
package com.epe.yehki.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.epe.yehki.util.Const;
import com.example.yehki.R;
public class CountryAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> countryArray;
private Context mContext;
public CountryAdapter(Context paramContext, ArrayList<HashMap<String, String>> cuntryList) {
this.mContext = paramContext;
this.countryArray = cuntryList;
}
public int getCount() {
return this.countryArray.size();
}
public Object getItem(int paramInt) {
return Integer.valueOf(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
#SuppressWarnings("static-access")
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater");
Viewholder localViewholder = null;
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.list_item, paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.countryid = ((TextView) paramView.findViewById(R.id.cat_id));
localViewholder.countryName = ((TextView) paramView.findViewById(R.id.name));
paramView.setTag(localViewholder);
} else {
localViewholder = new Viewholder();
localViewholder = (Viewholder) paramView.getTag();
}
System.out.println("::::::::::::::array indexes::::::::::::" + countryArray.get(paramInt));
localViewholder.countryName.setText(countryArray.get(paramInt).get(Const.TAG_COUNTRY_NAME));
localViewholder.countryid.setText(countryArray.get(paramInt).get(Const.TAG_COUNTRY_ID));
return paramView;
}
static class Viewholder {
TextView countryName;
TextView countryid;
}
}

It is display nothing because you do not fill up the dataset you want to display. You create the Adapter in onCreate but at the time the dataset is empty. Imo you should change the Adapter constructor from
public CountryAdapter(Context paramContext, ArrayList<String> paramArrayList) {
to
public CountryAdapter(Context paramContext, ArrayList<HashMap<String, String>> paramArrayList) {
and when onPostExecuted is called, you create a new CountryAdapter and submit it to the ListView. Of course you have to adjust your Adapter in order to reflect the changes of the Adapter's constructor

Related

Display Filtered Data on ListView

I'm having an issue while trying to display my filtered list on my list view.
I print out the data after filtering and it's actually correct but it doesn't display on my ListView please what I am doing wrong? My code is below
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Icon;
import android.media.Image;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.BaseAdapter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
public class SchoolListAdapter extends BaseAdapter implements Filterable {
private Activity activity;
ArrayList<HashMap<String, String>> data;
ArrayList<HashMap<String, String>> displayedData;
private static LayoutInflater inflater=null;
public SchoolListAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
displayedData = d;
inflater = LayoutInflater.from(a);
}
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.school_details_list, null);
}
ImageView schoolLogo = (ImageView) vi.findViewById(R.id.schoolLogo);
TextView lblSchoolId = (TextView)vi.findViewById(R.id.lblSchoolId);
TextView lblSchoolName = (TextView)vi.findViewById(R.id.lblSchoolName);
HashMap<String, String> school = data.get(position);
// Setting all values in listview
lblSchoolId.setText(school.get("id"));
lblSchoolName.setText(school.get("name"));
String logo = school.get("logo");
byte []img = Base64.decode(logo,Base64.DEFAULT);
Bitmap bmp = BitmapFactory.decodeByteArray(img, 0, img.length);
schoolLogo.setImageBitmap(bmp);
return vi;
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected void publishResults(CharSequence constraint,FilterResults results) {
if(results.count == 0){
notifyDataSetInvalidated();
}else{
displayedData = (ArrayList<HashMap<String, String>>) results.values; // has the filtered values
notifyDataSetChanged(); // notifies the data with new filtered values
}
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values
ArrayList<HashMap<String, String>> FilteredArrList = new ArrayList();
if (data == null) {
data = new ArrayList(displayedData); // saves the original data in data
}
/********
*
* If constraint(CharSequence that is received) is null returns the data(Original) values
* else does the Filtering and returns FilteredArrList(Filtered)
*
********/
if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = data.size();
results.values = data;
} else {
constraint = constraint.toString().toUpperCase();
HashMap <String, String>schools = new HashMap();
for (int i = 0; i < data.size(); i++) {
String dat = data.get(i).get("name");
if(dat.toString().matches(".*"+constraint+".*")){
schools.put("id",data.get(i).get("id"));
schools.put("name",data.get(i).get("name"));
schools.put("logo",data.get(i).get("logo"));
FilteredArrList.add(schools);
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
return filter;
}
}
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class SelectSchoolActivity extends ListActivity implements AdapterView.OnItemClickListener {
private ProgressDialog pDialog;
private ListView lv;
private SharedPreferences sharedPreferences;
public static String SCHOOLING_PREFERENCES = "SCHOOL_PREF";
private ArrayList<HashMap<String, String>> schoolList;
private EditText txtSearch;
private SchoolListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_school);
sharedPreferences = getSharedPreferences(SCHOOLING_PREFERENCES, Context.MODE_PRIVATE);
txtSearch = (EditText)findViewById(R.id.txtSearch);
schoolList = new ArrayList();
if(sharedPreferences.contains("school")){
Intent intent = new Intent(SelectSchoolActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}else{
new GetSchoolList(SelectSchoolActivity.this).execute();
lv = getListView();
lv.setOnItemClickListener(this);
// Add Text Change Listener to EditText
txtSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Call back the Adapter with current character to Filter
adapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String school = ((TextView)view.findViewById(R.id.lblSchoolId)).getText().toString();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("school", school);
editor.commit();
Intent intent = new Intent(SelectSchoolActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
private class GetSchoolList extends AsyncTask<Void, Void, Void> {
private Activity context;
public GetSchoolList(Activity context){
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(context);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
String url = "http://192.168.34.1:8085/SchoolWebService/rest/Student/school_list";
// Making a request to url and getting response
String details = sh.makeServiceCall(url, ServiceHandler.GET);
if (details != null) {
try {
JSONArray results = new JSONArray(details);
for(int i = 0; i<results.length(); i++) {
JSONObject c = results.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String logo = c.getString("logo");
// tmp hashmap for single feeDetails
HashMap <String, String>school = new HashMap();
school.put("id", id);
school.put("name", name);
school.put("logo", logo);
schoolList.add(school);
}
} catch (Exception e) {
Log.e("Exception", Log.getStackTraceString(e));
}
} else {
//snackbar.setText("Connection Failed!").show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing()) {
pDialog.dismiss();
}
adapter = new SchoolListAdapter(context, schoolList);
setListAdapter(adapter);
}
}
}
#medhdj pointed out and error in my code so I was able to find and fix the problem.
Please refer to his comment

how can I stop my contacts being listed twice?

I have a sample app where the contacts in my android phone are listed and I can search for them. However, very often the contacts are listed twice. I only want them to be listed once. What should I change in my code to fix this? I've posted the relevant parts of my code below.
I did try here how to remove duplicate contacts from arraylist but I couldn't modify the code sufficiently to suit my needs.
MainActivity.java
package com.example.chris.contactlistcustomlistview;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
// ArrayList
ArrayList<SelectUser> selectUsers;
List<SelectUser> temp;
// Contact List
ListView listView;
// Cursor to load contacts list
Cursor phones, email;
// Pop up
ContentResolver resolver;
SearchView search;
SelectUserAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectUsers = new ArrayList<SelectUser>();
resolver = this.getContentResolver();
listView = (ListView) findViewById(R.id.contacts_list);
phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
// retrieves contact information
LoadContact loadContact = new LoadContact();
loadContact.execute();
// let's set up our search box,
search = (SearchView) findViewById(R.id.searchView);
//*** setOnQueryTextListener ***
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// when the text in searchView changes, call the filter function
adapter.filter(newText);
return false;
}
});
}
// Load data on background
class LoadContact extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
// Get Contact list from Phone
if (phones != null) {
Log.e("count", "" + phones.getCount());
if (phones.getCount() == 0) {
Toast.makeText(MainActivity.this, "No contacts in your contact list.", Toast.LENGTH_LONG).show();
}
while (phones.moveToNext()) {
Bitmap bit_thumb = null;
String id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String EmailAddr = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA2));
String image_thumb = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI));
try {
if (image_thumb != null) {
bit_thumb = MediaStore.Images.Media.getBitmap(resolver, Uri.parse(image_thumb));
} else {
Log.e("No Image Thumb", "--------------");
}
} catch (IOException e) {
e.printStackTrace();
}
//what's happening here? For every user in the phonebook, show an image, the name, number, an id and maybe a checkbox?
SelectUser selectUser = new SelectUser();
selectUser.setThumb(bit_thumb);
selectUser.setName(name);
selectUser.setPhone(phoneNumber);
selectUser.setEmail(id);
selectUser.setCheckedBox(false);
selectUsers.add(selectUser);
}
} else {
Log.e("Cursor close 1", "----------------");
}
//phones.close();
return null;
}
#Override
// when DoInBackground is finished, when we have our phone number, name etc... display the results in our listview.
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adapter = new SelectUserAdapter(selectUsers, MainActivity.this);
listView.setAdapter(adapter);
// Select item on listclick
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.e("search", "here---------------- listener");
SelectUser data = selectUsers.get(i);
}
});
listView.setFastScrollEnabled(true);
}
}
#Override
protected void onStop() {
super.onStop();
phones.close();
}
}
SelectUserAdapter.java
package com.example.chris.contactlistcustomlistview;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* Created by Chris on 25/03/2016.
*/
public class SelectUserAdapter extends BaseAdapter {
public List<SelectUser> _data;
private ArrayList<SelectUser> arraylist;
Context _c;
ViewHolder v;
// RoundImage roundedImage;
public SelectUserAdapter(List<SelectUser> selectUsers, Context context) {
_data = selectUsers;
_c = context;
this.arraylist = new ArrayList<SelectUser>();
this.arraylist.addAll(_data);
}
#Override
public int getCount() {
return _data.size();
}
#Override
public Object getItem(int i) {
return _data.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
View view = convertView;
if (view == null) {
LayoutInflater li = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.inflate_listview, null);
Log.e("Inside", "here--------------------------- In view1");
} else {
view = convertView;
Log.e("Inside", "here--------------------------- In view2");
}
// we are making a cell format in the ListView, which will contain info like
// number, name... the layout for this, with name, no, pic etc...
// is contained in inflate_listview.xml, which describes how each cell data
// loads into the listview
v = new ViewHolder();
// So, for example, title is cast to the name id, in activity main,
// phone is cast to the id called no etc
v.title = (TextView) view.findViewById(R.id.name);
v.check = (CheckBox) view.findViewById(R.id.check);
v.phone = (TextView) view.findViewById(R.id.no);
// v.imageView = (ImageView) view.findViewById(R.id.pic);
// for each new cell with title, name, number etc...
//
final SelectUser data = (SelectUser) _data.get(i);
v.title.setText(data.getName());
v.check.setChecked(data.getCheckedBox());
v.phone.setText(data.getPhone());
Log.e("Image Thumb", "--------------" + data.getThumb());
view.setTag(data);
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
// _data is our list of Users, or contacts
_data.clear();
// If there is nothing in the searchbox,
// then show all the contacts
if (charText.length() == 0) {
_data.addAll(arraylist);
// or else....
} else {
for (SelectUser wp : arraylist) {
// If a contact's phone number matches the input thus far that the user
// is filtering for, then include it in the listview.
if (wp.getPhone().toLowerCase(Locale.getDefault())
.contains(charText)) {
_data.add(wp);
}
}
}
notifyDataSetChanged();
}
static class ViewHolder {
// In each cell in the listview show a name and phone number
// ImageView imageView;
TextView title, phone;
CheckBox check;
}
}
public class MainActivity extends Activity {
Cursor cursor;
ListView mainListView;
ArrayList hashMapsArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (cursor != null) {
cursor.moveToFirst();}
try {
cursor = getApplicationContext().getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
int Idx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
int nameIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int phoneNumberIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int photoIdIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI);
cursor.moveToFirst();
Set<String> ids = new HashSet<>();
do {
System.out.println("=====>in while");
String contactid=cursor.getString(Idx);
if (!ids.contains(contactid)) {
ids.add(contactid);
HashMap<String, String> hashMap = new HashMap<String, String>();
String name = cursor.getString(nameIdx);
String phoneNumber = cursor.getString(phoneNumberIdx);
String image = cursor.getString(photoIdIdx);
System.out.println("Id--->"+contactid+"Name--->"+name);
System.out.println("Id--->"+contactid+"Number--->"+phoneNumber);
if (!phoneNumber.contains("*")) {
hashMap.put("contactid", "" + contactid);
hashMap.put("name", "" + name);
hashMap.put("phoneNumber", "" + phoneNumber);
hashMap.put("image", "" + image);
// hashMap.put("email", ""+email);
if (hashMapsArrayList != null) {
hashMapsArrayList.add(hashMap);}
// hashMapsArrayList.add(hashMap);
}
}
} while (cursor.moveToNext());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
}
}
Try this, I am not sure it will solve this problem.
if (selectUsers.indexOf(selectUser) == -1) {
selectUsers.add(selectUser);
}

Issues with Filtering listview with edittext

Hello I'm working on an app which has an edittext to search for items on the listview. If the user types a letter in the edittext the listview is getting filtered perfectlty.Have used Adapter also.Now i have following issues:
1)when i m clearing letters edittext my listview is not getting Updated..
2) if i enter wrong letter or letter which does not corrorsponds to any item of a listview the listview is getting clear.
Have gone thorugh exmaples in SO
Android filter listview custom adapter
And googled also for same problem but not getting solved it..Plz anybody help me..
Here is my code:
package com.AAAAA.AAAAA;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.AdapterView.OnItemClickListener;
import com.AAAAA.adapter.UpdateSingleItemViewActivity;
import com.AAAAA.adapter.UpdatesAdapterList;
import com.AAAAA.local.database.DBController;
import com.AAAAA.AAAAA.AAAAA.constant.Constant;
import com.AAAAA.AAAAA.AAAAA.utils.Utility;
public class Cardiology_updates extends Activity implements OnClickListener,
OnRefreshListener {
EditText et ;
private Context appContext;
// ProgressDialog mProgressDialog;
private Dialog dialog;
private boolean isFinish = false;
String result = "";
JSONObject jsonobject;
JSONArray jsonArray;
ArrayList<HashMap<String, String>> UpdatesHmList;
public static ArrayList<HashMap<String, String>> FinalLocalDataList;
ArrayList<HashMap<String, String>> LocalDataList;
DBController controller = new DBController(this);
HashMap<String, String> queryValues;
ListView list;
UpdatesAdapterList adapter;
public static String UpdateID = "UpdateID";
public static String UpdateTitle = "Title";
/*
* public static String UpdateDescription = "Description"; public static
* String POPULATION = "UpdateDate"; public static String UpdateImage =
* "Photo";
*/
public static String UpdateDescription = "Description";
public static String POPULATION = "Title";
public static String UpdateImage = "Complete_imagePath";
public static String Complete_imagePath;
public static String Title;
public static String Description;
SwipeRefreshLayout swipeLayout;
private ProgressBar progressbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cardiology_updates);
// controller.deleteAllJsonData();
appContext = this;
animationView();
initComponent();
}
private void animationView() {
// TODO Auto-generated method stub
progressbar = (ProgressBar) findViewById(R.id.loading);
}
private void initComponent() {
// TODO Auto-generated method stub
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
dialog = new Dialog(appContext);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.alert_dialog);
((Button) findViewById(R.id.Button01)).setOnClickListener(this);
((Button) dialog.findViewById(R.id.btnOk)).setOnClickListener(this);
new GetUpdatesInfo().execute();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.Button01) {
finish();
// finishActivity() ;
} else if (v.getId() == R.id.btnOk) {
dialog.dismiss();
if (isFinish) {
this.finish();
}
}
}
public class GetUpdatesInfo extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
super.onPreExecute();
if (progressbar.getVisibility() != View.VISIBLE) {
progressbar.setVisibility(View.VISIBLE);
}
}
#Override
protected String doInBackground(String... params) {
// Create an array
UpdatesHmList = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
String url = null;
url = Constant.serverUrl + "/GetUpdateList";
result = Utility.postParamsAndfindJSON(url);
Log.e("result doInBackground", "" + result);
if (!(result == null)) {
try {
controller.deleteAllJsonData();
// Locate the array name in JSON
jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonArray.getJSONObject(i);
// Retrive JSON Objects
map.put("UpdateID", jsonobject.getString("UpdateID"));
map.put("Title", jsonobject.getString("Title"));
String Upadates_Photo = jsonobject.optString("Photo")
.toString();
String Complete_imagePath = Constant.prifixserverUrl
+ Upadates_Photo;
String Title = jsonobject.getString("Title").toString();
String Description = jsonobject
.getString("Description").toString();
String noHtml = Description.replaceAll("<[^>]*>", "");
String parseResponse = noHtml.replaceAll(" ", "");
map.put("Photo", Complete_imagePath);
map.put("Description", Description);
map.put("UpdateDate",
jsonobject.getString("UpdateDate"));
Log.e("UpdateID ",
" "
+ jsonobject.getString("UpdateID")
.toString());
Log.e("Title ", " "
+ jsonobject.getString("Title").toString());
Log.e("Complete_imagePath ",
" " + Complete_imagePath.toString());
Log.e("Description ", " " + parseResponse);
Log.e("UpdateDate ",
" "
+ jsonobject.getString("UpdateDate")
.toString());
queryValues = new HashMap<String, String>();
queryValues.put("Complete_imagePath",
Complete_imagePath);
queryValues.put("Title", Title);
queryValues.put("Description", Description);
controller.insertAllJsonData(queryValues);
// Set the JSON Objects into the array
UpdatesHmList.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
return result;
}
#Override
protected void onPostExecute(String result) {
// Locate the listview in listview_main.xml
if (progressbar.getVisibility() == View.VISIBLE) {
progressbar.setVisibility(View.GONE);
}
/*
* if (result == null) { //mProgressDialog.dismiss();
* localalldata();
*
* }
*/
localalldata();
/*
* list = (ListView) findViewById(R.id.list_Upadates); // Pass the
* results into ListViewAdapter.java adapter = new
* UpdatesAdapterList(Cardiology_updates.this, FinalLocalDataList);
* // Set the adapter to the ListView list.setAdapter(adapter);
*/
// Close the progressdialog
// mProgressDialog.dismiss();
}
}
#Override
public void onRefresh() {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
getSomeData();
// localalldata();
swipeLayout.setRefreshing(false);
}
}, 5000);
}
protected void getSomeData() {
// TODO Auto-generated method stub
// localalldata();
new GetUpdatesInfo().execute();
adapter.notifyDataSetChanged();
/*
* if (LocalDataList == null) { Log.e("LocalDataList inside if ",
* "LocalDataList inside if "); new GetUpdatesInfo().execute();
*
* } else { // adapter.imageLoader.clearCache();
* Log.e("LocalDataList else ", "LocalDataList else ");
*
* adapter.notifyDataSetChanged(); }
*/
}
private void localalldata() {
// TODO Auto-generated method stub
LocalDataList = controller.getAllJsonData();
FinalLocalDataList = new ArrayList<HashMap<String, String>>();
for (HashMap<String, String> hashMap : LocalDataList) {
System.out.println(hashMap.keySet());
HashMap<String, String> map = new HashMap<String, String>();
for (String key : hashMap.keySet()) {
System.out.println(hashMap.get(key));
Complete_imagePath = hashMap.get("Complete_imagePath");
Title = hashMap.get("Title");
Description = hashMap.get("Description");
map.put("Complete_imagePath", Complete_imagePath);
map.put("Title", Title);
map.put("Description", Description);
Log.v("All Json CodiateUpdate Title", "" + Complete_imagePath);
Log.v("All Json CodiateUpdate Title", "" + Title);
}
FinalLocalDataList.add(map);
}
list = (ListView) findViewById(R.id.list_Upadates);
// Pass the results into ListViewAdapter.java
adapter = new UpdatesAdapterList(Cardiology_updates.this,
FinalLocalDataList);
// Set the adapter to the ListView
list.setTextFilterEnabled(true);
list.setAdapter(adapter);
// adapter.notifyDataSetChanged();
et = (EditText) findViewById(R.id.search);
// Capture Text in EditText
et.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
adapter.filter(arg0.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
//String text = et.getText().toString().toLowerCase(Locale.getDefault());
//adapter.getFilter().filter(arg0);
}
});
}
}
Here is my Adapter:
package com.AAAA.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import com.AAAA.AAAA.Cardiology_updates;
import com.AAAA.AAAA.R;
import com.AAAA.imageloader.ImageLoader;
public class UpdatesAdapterList extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
public ImageLoader imageLoader;
private Activity activity;
//HashMap<String, String> resultp = new HashMap<String, String>();
private ArrayList<HashMap<String,String>> filterData;
public UpdatesAdapterList(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context.getApplicationContext());
filterData = new ArrayList<HashMap<String,String>>();
filterData.addAll(this.data);
}
#Override
public int getCount() {
return filterData.size();
}
#Override
public Object getItem(int position) {
return filterData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.listview_updateitem, null);
holder.UpdateTitle = (TextView) convertView.findViewById(R.id.txtUpdatetitle);
holder.UpdateImage = (ImageView) convertView.findViewById(R.id.list_UpdateImage);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.UpdateTitle.setText(filterData.get(position).get(Cardiology_updates.UpdateTitle));
imageLoader.DisplayImage(filterData.get(position).get(Cardiology_updates.UpdateImage), holder.UpdateImage);
// Capture ListView item click
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
//resultp = data.get(position);
Intent intent = new Intent(context, UpdateSingleItemViewActivity.class);
// Pass all data rank
intent.putExtra("UpdateTile", filterData.get(position).get(Cardiology_updates.UpdateTitle));
// Pass all data country
intent.putExtra("UpdateDescription", filterData.get(position).get(Cardiology_updates.UpdateDescription));
// Pass all data population
intent.putExtra("population",filterData.get(position).get(Cardiology_updates.POPULATION));
// Pass all data flag
intent.putExtra("UpdateImage", filterData.get(position).get(Cardiology_updates.UpdateImage));
// Start SingleItemView Class
intent.putExtra("position", position);
context.startActivity(intent);
}
}); return convertView;
}
class ViewHolder{
TextView UpdateTitle;
ImageView UpdateImage;
}
public void filter(String constraint) {
filterData.clear();
if (constraint.length() == 0) {
filterData.addAll(data);
}else{
for (HashMap<String,String> row: data) {
if(row.get(Cardiology_updates.UpdateTitle).toUpperCase().startsWith(constraint.toString().toUpperCase())){
filterData.add(row);
}
}
}
notifyDataSetChanged();
}
}
Activity opens on cliking listview items:
package com.AAAAA.adapter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import com.AAAAA.AAAAA.Cardiology_updates;
import com.AAAAA.AAAAA.R;
public class UpdateSingleItemViewActivity extends Activity {
int position;
String UpdateTile;
String UpdateDescription;
String population;
String UpdateImage;
//String position;
ViewPager viewPager;
PagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_update_single_item_view);
Log.e("UpdateSingleItemViewActivity class",
"UpdateSingleItemViewActivity class");
/*
* WebView webview = new WebView(this); setContentView(webview);
*/
Button btnback = (Button) findViewById(R.id.Button01);
btnback.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
//WebView webview = (WebView) findViewById(R.id.webview);
Intent i = getIntent();
// Get the result of rank
UpdateTile = i.getStringExtra("UpdateTile");
// Get the result of country
UpdateDescription = i.getStringExtra("UpdateDescription");
// Get the result of population
population = i.getStringExtra("population");
// Get the result of flag
UpdateImage = i.getStringExtra("UpdateImage");
//i.putExtra("POSITION_KEY", position);
position = i.getExtras().getInt("position");
//webview.loadData(UpdateDescription, "text/html", null);
viewPager = (ViewPager) findViewById(R.id.viewpager_layout);
// Pass results to ViewPagerAdapter Class
adapter = new ViewPagerAdapter(UpdateSingleItemViewActivity.this, Cardiology_updates.FinalLocalDataList);
// Binds the Adapter to the ViewPager
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(position);
}
}
its Corrosponding adapter:
package com.AAAAA.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import com.AAAAA.AAAAA.Cardiology_updates;
import com.AAAAA.AAAAA.R;
import com.AAAAA.imageloader.ImageLoader;
import android.app.Activity;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.LinearLayout;
public class ViewPagerAdapter extends PagerAdapter {
String UpdateTile;
String UpdateDescription;
//String population;
String UpdateImage;
String position;
LayoutInflater inflater;
Context context;
ArrayList<HashMap<String, String>> data;
public ImageLoader imageLoader;
private Activity activity;
//HashMap<String, String> resultp = new HashMap<String, String>();
ArrayList<HashMap<String,String>> filterData;
public ViewPagerAdapter(Context context, ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
filterData = new ArrayList<HashMap<String,String>>();
filterData.addAll(this.data);
}
#Override
public int getCount() {
return filterData.size();
}
public Object getItem(int position) {
return filterData.get(position);
}
public long getItemId(int position) {
return position;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
WebView webview;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.viewpager_item, container,
false);
//resultp =data.get(position);
webview=(WebView)itemView.findViewById(R.id.webview1);
//webview.setText(webview[position]);
webview.loadData(filterData.get(position).get(Cardiology_updates.UpdateDescription), "text/html", null);
((ViewPager) container).addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((LinearLayout) object);
}
}
When used custom adapter always try to implement ViewHolder design pattern for ListView performance and use custom filter function instead Filterable implementation :
Custom filter funcation required two array list one is filterable data list and another one is for orignal data list :
public void filter(String constraint) {
filterData.clear();
if (constraint.length() == 0) {
filterData.addAll(orignalData);
}else{
for (HashMap<String,String> row: orignalData) {
if(row.get(Cardiology_updates.UpdateTitle).toUpperCase().startsWith(constraint.toString().toUpperCase())){
filterData.add(row);
}
}
}
notifyDataSetChanged();
}
Example :
et.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
adapter.filter(arg0.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,int arg2, int arg3) {
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) {
}
});
public class UpdatesAdapterList extends BaseAdapter {
private Context context;
private ArrayList<HashMap<String,String>> filterData;
private ArrayList<HashMap<String,String>> orignalData;
public ImageLoader imageLoader;
public UpdatesAdapterList(Context context,ArrayList<HashMap<String, String>> orignalData) {
this.context = context;
this.orignalData = orignalData;
filterData = new ArrayList<HashMap<String,String>>();
filterData.addAll(this.orignalData);
imageLoader = new ImageLoader(this.context);
}
#Override
public int getCount() {
return filterData.size();
}
#Override
public Object getItem(int position) {
return filterData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.listview_updateitem, null);
holder.UpdateTitle = (TextView) convertView.findViewById(R.id.txtUpdatetitle);
holder.UpdateImage = (ImageView) convertView.findViewById(R.id.list_UpdateImage);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.UpdateTitle.setText(filterData.get(position).get(Cardiology_updates.UpdateTitle));
imageLoader.DisplayImage(filterData.get(position).get(Cardiology_updates.UpdateImage), holder.UpdateImage);
// Capture ListView item click
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, UpdateSingleItemViewActivity.class);
// Pass all data rank
intent.putExtra("UpdateTile", filterData.get(position).get(Cardiology_updates.UpdateTitle));
// Pass all data country
intent.putExtra("UpdateDescription", filterData.get(position).get(Cardiology_updates.UpdateDescription));
// Pass all data population
intent.putExtra("population",filterData.get(position).get(Cardiology_updates.POPULATION));
// Pass all data flag
intent.putExtra("UpdateImage", filterData.get(position).get(Cardiology_updates.UpdateImage));
// Start SingleItemView Class
intent.putExtra("position", position);
context.startActivity(intent);
}
});
return convertView;
}
class ViewHolder{
TextView UpdateTitle;
ImageView UpdateImage;
}
public void filter(String constraint) {
filterData.clear();
if (constraint.length() == 0) {
filterData.addAll(orignalData);
}else{
for (HashMap<String,String> row: orignalData) {
if(row.get(Cardiology_updates.UpdateTitle).toUpperCase().startsWith(constraint.toString().toUpperCase())){
filterData.add(row);
}
}
}
notifyDataSetChanged();
}
}

on Click of text View inside a List Item not getting proper value

I have a ListView ,In that each ListItem having some items(textViews),In which one textView is having click event.That I have put in my custom adater,And I am calling an asynctask on its cLick event,For that I want a value when I click on that textView its "queID" I want,But currently I am gettong it null..Please see my code and help me please..!
"qoute" is that textView.On which I have put click event.how to set"buyer_req_Id" and get tag on it?I currrently successfully get the tag on each "ListItem" Click event ,I want to set the same tag on ListItem's textView.Inside java class I have put only adapter,In which I want "buyer_request_id".
Adapter.java
package com.epe.yehki.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.epe.yehki.ui.BuyingreqActivity;
import com.epe.yehki.ui.BuyingreqActivity.GetQuoteList;
import com.epe.yehki.util.Const;
import com.example.yehki.R;
public class BuyingRequestAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> BuyingRequestArray;
private Context mContext;
public BuyingRequestAdapter(Context paramContext, ArrayList<HashMap<String, String>> productList) {
this.mContext = paramContext;
this.BuyingRequestArray = productList;
}
public int getCount() {
return this.BuyingRequestArray.size();
}
public Object getItem(int paramInt) {
return BuyingRequestArray.get(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
#SuppressWarnings("static-access")
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater");
Viewholder localViewholder;
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.raw_buying_req, paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.sub = ((TextView) paramView.findViewById(R.id.sub));
localViewholder.expDate = ((TextView) paramView.findViewById(R.id.exp_date));
localViewholder.quote = ((TextView) paramView.findViewById(R.id.quote));
localViewholder.status = ((TextView) paramView.findViewById(R.id.status));
localViewholder.lastUpdate = ((TextView) paramView.findViewById(R.id.last_updated));
paramView.setTag(localViewholder);
} else {
localViewholder = (Viewholder) paramView.getTag();
}
System.out.println(":::::::::::::::values:::::::::::::::" + BuyingRequestArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
localViewholder.sub.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
localViewholder.expDate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_EXPIRY_DATE));
localViewholder.lastUpdate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_DATE_MODIFIED));
localViewholder.quote.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_QUOTE_COUNT));
localViewholder.quote.setTextColor(Color.parseColor("#0000ff"));
localViewholder.status.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_BUYING_REQUEST_STATUS));
localViewholder.quote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("::::::::::::::::::quote clicked...!!");
GetQuoteList getQuoteList = ((BuyingreqActivity) mContext).new GetQuoteList();
getQuoteList.execute();
}
});
return paramView;
}
static class Viewholder {
TextView sub;
TextView lastUpdate;
TextView expDate;
TextView quote;
TextView status;
}
}
java class(asynctask)
public class GetQuoteList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(BuyingreqActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
scr_post.setVisibility(View.GONE);
scr_view.setVisibility(View.GONE);
quote_view.setVisibility(View.VISIBLE);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// String query = "?customer_id=" +
// Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "")
// + "&buyer_request_id=23";
String query = "?customer_id=" + Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "") + "&buyer_request_id=" + buyer_request_id;
query = query.replace(" ", "%20");
viewURL = Const.API_QUOTE_RECIEVED + query;
BackendAPIService sh = new BackendAPIService();
System.out.println(":::::::::::::::::::ADDRESS URL:::::::::::::::::" + viewURL);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(viewURL, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.has(Const.TAG_BUYING_REQUEST)) {
System.out.println("::::::::::::::::true::::::::::::::::" + jsonObj.has(Const.TAG_ADDRESS_LIST));
requestes = jsonObj.getJSONArray(Const.TAG_BUYING_REQUEST);
if (requestes != null && requestes.length() != 0) {
// looping through All Contacts
System.out.println(":::::::::::FLAG IN SUB:::::::::::" + flag);
for (int i = 0; i < requestes.length(); i++) {
JSONObject c = requestes.getJSONObject(i);
buyerID = c.getString(Const.TAG_BUYING_REQUEST_ID);
System.out.println(":::::::::::::::MY buying request:::::::::::::" + buyerID);
String product_name = c.getString(Const.TAG_PRODUCT_NAME);
String quote_id = c.getString(Const.TAG_QUOTE_ID);
String supplier_name = c.getString(Const.TAG_SUPPLIER_NAME);
String status = c.getString(Const.TAG_STATUS);
HashMap<String, String> quote = new HashMap<String, String>();
quote.put(Const.TAG_BUYING_REQUEST_ID, buyerID);
quote.put(Const.TAG_PRODUCT_NAME, product_name);
quote.put(Const.TAG_QUOTE_ID, quote_id);
quote.put(Const.TAG_EXPIRY_DATE, supplier_name);
quote.put(Const.TAG_QUOTE_COUNT, status);
queList.add(quote);
System.out.println(":::::::::::::Buyer request ID:" + buyerID);
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
*
* */
quoteAdapter = new QuoteAdapter(BuyingreqActivity.this, queList);
quoteList.setAdapter(quoteAdapter);
}
}
// Try this way,hope this will help you...
localViewholder.quote.setTag(BuyingRequestArray.get(paramInt).get(Const.TAG_BUYING_REQUEST_ID));
localViewholder.quote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("::::::::::::::::::quote clicked...!!");
String buyerId = v.getTag().toString(); // user this buyerId for your requirement
System.out.println("Buyer Id Is "+buyerId);
GetQuoteList getQuoteList = ((BuyingreqActivity) mContext).new GetQuoteList();
getQuoteList.execute();
}
});
I have solved my problem as below by changing my asynctask to void to string :
adapter.java
package com.epe.yehki.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.epe.yehki.ui.BuyingreqActivity;
import com.epe.yehki.ui.BuyingreqActivity.GetQuoteList;
import com.epe.yehki.util.Const;
import com.example.yehki.R;
public class BuyingRequestAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> BuyingRequestArray;
private Context mContext;
public BuyingRequestAdapter(Context paramContext, ArrayList<HashMap<String, String>> reqList) {
this.mContext = paramContext;
this.BuyingRequestArray = reqList;
}
public int getCount() {
return this.BuyingRequestArray.size();
}
public Object getItem(int paramInt) {
return BuyingRequestArray.get(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
#SuppressWarnings("static-access")
public View getView(final int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater");
Viewholder localViewholder;
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.raw_buying_req, paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.sub = ((TextView) paramView.findViewById(R.id.sub));
localViewholder.expDate = ((TextView) paramView.findViewById(R.id.exp_date));
localViewholder.quote = ((TextView) paramView.findViewById(R.id.quote));
localViewholder.status = ((TextView) paramView.findViewById(R.id.status));
localViewholder.lastUpdate = ((TextView) paramView.findViewById(R.id.last_updated));
paramView.setTag(localViewholder);
/* localViewholder.quote.setTag(localViewholder); */
} else {
localViewholder = (Viewholder) paramView.getTag();
/* localViewholder.quote = ((TextView) paramView.getTag()); */
}
final String reqId = BuyingRequestArray.get(paramInt).get(Const.TAG_BUYING_REQUEST_ID);
System.out.println("::::::::::::::My reqId:::::::::::" + reqId);
localViewholder.sub.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
localViewholder.expDate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_EXPIRY_DATE));
localViewholder.lastUpdate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_DATE_MODIFIED));
localViewholder.quote.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_QUOTE_COUNT));
localViewholder.quote.setTextColor(Color.parseColor("#0000ff"));
localViewholder.status.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_BUYING_REQUEST_STATUS));
localViewholder.quote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("::::::::::::::::::quote clicked...!!");
System.out.println("Buyer Id Is " + reqId);
GetQuoteList getQuoteList = ((BuyingreqActivity) mContext).new GetQuoteList();
getQuoteList.execute(reqId);
}
});
return paramView;
}
static class Viewholder {
TextView sub;
TextView lastUpdate;
TextView expDate;
TextView quote;
TextView status;
}
}

Custom Adapter not working Properly in android

I hakve made a custom adaptor for binding parsed data into a listView,I have tried as below,But it only gives me 1st value .please help me.I want to bind all the values to listView but currently i only able to bind only 1\one value in it..
Registration.java
package com.epe.yehki.ui;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.epe.yehki.adapter.CountryAdapter;
import com.epe.yehki.adapter.WholesaleProductAdapter;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.backend.RegisterationAPI;
import com.epe.yehki.backend.ResponseListener;
import com.epe.yehki.uc.Menu;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Const.API_RESULT;
import com.example.yehki.R;
public class RegistrationActivity extends Activity {
public RegisterationAPI registartionAPI;
private EditText fName;
private EditText lName;
private EditText eMail;
private Button register;
private EditText contact;
private EditText password;
private ListView countrylist;
private ListView statelist;
private TextView tv_country;
private TextView state;
JSONArray countries = null;
// Fetching List
JSONObject jsonObj;
JSONArray contries = null;
ArrayList<HashMap<String, String>> countryList;
private CountryAdapter countryContent;
// Hashmap for ListView
public com.epe.yehki.uc.Menu regMenu;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_registration);
// FINDING IDS...
fName = (EditText) findViewById(R.id.et_fname);
lName = (EditText) findViewById(R.id.et_lname);
eMail = (EditText) findViewById(R.id.et_email);
contact = (EditText) findViewById(R.id.et_contact);
password = (EditText) findViewById(R.id.et_pwd);
tv_country = (TextView) findViewById(R.id.et_country);
state = (TextView) findViewById(R.id.et_state);
regMenu = (Menu) findViewById(R.id.menuReg);
register = (Button) findViewById(R.id.btn_register);
countrylist = (ListView) findViewById(R.id.country_list);
countrylist.setVisibility(View.GONE);
statelist = (ListView) findViewById(R.id.state_list);
countryList = new ArrayList<HashMap<String, String>>();
regMenu.setSelectedTab(1);
new GetCountries().execute();
countrylist.setVisibility(View.GONE);
// COUNTRY LIST CLICK EVENT...!!!
countrylist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
String countryname = ((TextView) view.findViewById(R.id.name)).getText().toString();
tv_country.setText(countryname);
// countrylist.setVisibility(view.GONE);
}
});
// REGISTER BUTTOM CLICK EVENT.....!
register.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (!fName.getText().toString().equals("") && fName.getText().toString() != null) {
if ((!lName.getText().toString().equals("") && lName.getText().toString() != null)) {
if ((!tv_country.getText().toString().equals("") && tv_country.getText().toString() != null)) {
if ((!state.getText().toString().equals("") && state.getText().toString() != null)) {
if ((!eMail.getText().toString().equals("") && eMail.getText().toString() != null)) {
if ((!password.getText().toString().equals("") && password.getText().toString() != null)) {
if ((!contact.getText().toString().equals("") && contact.getText().toString() != null)) {
} else {// CONTACT NUMBER
validation(getResources().getString(R.string.valid_number));
password.requestFocus();
}
} else {// password...
validation(getResources().getString(R.string.valid_pwd));
password.requestFocus();
}
} else {// EMAIL
validation(getResources().getString(R.string.valid_mail));
eMail.requestFocus();
}
} else {// STATE
validation(getResources().getString(R.string.valid_state));
state.requestFocus();
}
} else {// COUNTRY
validation(getResources().getString(R.string.valid_country));
tv_country.requestFocus();
}
} else {// LAST NAME
validation(getResources().getString(R.string.valid_lname));
lName.requestFocus();
}
} else {// FIRST NAME
validation(getResources().getString(R.string.valid_fname));
fName.requestFocus();
}
}
});
// COUINTRY LIST CLICK EVENT...!!!!
tv_country.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
countrylist.setVisibility(View.VISIBLE);
}
});
}
void validation(String msg) {
Toast.makeText(RegistrationActivity.this, msg, Toast.LENGTH_SHORT).show();
}
ResponseListener responseListener = new ResponseListener() {
#Override
public void onResponce(String api, API_RESULT result, Object obj) {
System.out.println("::::::::::::::inside response Listener::::::::");
if (progressDialog != null && progressDialog.isShowing())
progressDialog.dismiss();
if (api.equals(Const.API_LOGIN)) {
System.out.println("::::::::::::::inside response Listener::::::::1");
if (result == Const.API_RESULT.SUCCESS) {
registartionAPI = null;
// as
// doctor
System.out.println("success Login::::::::::>>>>>>>>>>>>>>>>>>" + result);
startActivity(new Intent(RegistrationActivity.this, HomeActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
} else {
System.out.println("failed Login::::::::::>>>>>>>>>>>>>>>>>>" + result);
}
}
}
};
// ASYNC TASK FOR GETTING COUNTRY LIST...!!!
private class GetCountries extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
BackendAPIService sh = new BackendAPIService();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(Const.API_COUTRY, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.has(Const.TAG_COUNTY_LIST)) {
contries = jsonObj.getJSONArray(Const.TAG_COUNTY_LIST);
System.out.println(":::::::::PRODUCT lENGTH:::::::::::" + contries.length());
if (contries != null && contries.length() != 0) {
// looping through All Contacts
for (int i = 0; i < contries.length(); i++) {
JSONObject c = contries.getJSONObject(i);
String Con_id = c.getString(Const.TAG_COUNTRY_ID);
System.out.println("::::::::::::::::::PARSING PRODUCT ID:::::::::::::" + Con_id);
String CountryName = c.getString(Const.TAG_COUNTRY_NAME);
HashMap<String, String> country = new HashMap<String, String>();
// adding each child node to HashMap key =>
// value
country.put(Const.TAG_COUNTRY_ID, Con_id);
country.put(Const.TAG_COUNTRY_NAME, CountryName);
countryList.add(country);
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
countryContent = new CountryAdapter(RegistrationActivity.this, countryList);
countrylist.setAdapter(countryContent);
}
}
}
Adapter.java
package com.epe.yehki.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.epe.yehki.util.Const;
import com.example.yehki.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
public class CountryAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> countryArray;
private Context mContext;
public CountryAdapter(Context paramContext, ArrayList<HashMap<String, String>> countryList) {
this.mContext = paramContext;
this.countryArray = countryList;
}
public int getCount() {
return this.countryArray.size();
}
public Object getItem(int paramInt) {
return Integer.valueOf(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
#SuppressWarnings("static-access")
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater");
Viewholder localViewholder = null;
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.list_item, paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.con_id = ((TextView) paramView.findViewById(R.id.cat_id));
localViewholder.con_name = ((TextView) paramView.findViewById(R.id.name));
paramView.setTag(localViewholder);
} else {
localViewholder = new Viewholder();
localViewholder = (Viewholder) paramView.getTag();
}
localViewholder.con_name.setText(countryArray.get(paramInt).get(Const.TAG_COUNTRY_NAME));
System.out.println("::::::::::::::::::;PRDUCT name" + countryArray.get(paramInt).get(Const.TAG_COUNTRY_NAME));
return paramView;
}
static class Viewholder {
TextView con_id;
TextView con_name;
}
}
Please try the following class:
public class CountryAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> countryArray;
private Context mContext;
public a(Context paramContext, ArrayList<HashMap<String, String>> countryList) {
this.mContext = paramContext;
this.countryArray = countryList;
}
public int getCount() {
return countryArray.size();
}
public Object getItem(int paramInt) {
return countryArray.get(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
#SuppressWarnings("static-access")
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
Viewholder localViewholder;
LayoutInflater localLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.list_item, paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.con_id = ((TextView) paramView.findViewById(R.id.cat_id));
localViewholder.con_name = ((TextView) paramView.findViewById(R.id.name));
paramView.setTag(localViewholder);
} else {
localViewholder = (Viewholder) paramView.getTag();
}
HashMap<String, String> data = (HashMap<String, String>) getItem(paramInt);
localViewholder.con_name.setText(data.get(Const.TAG_COUNTRY_NAME));
return paramView;
}
static class Viewholder {
TextView con_id;
TextView con_name;
}
}
Please note you can't use System.out.println on Android, please use Log class instead: Log.d("myTag", "message").
Please update the line
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater");
to
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
remove localViewholder = new Viewholder(); from getView else condition. Here you are creating a new holder object every time.
It should be
else {
localViewholder = (Viewholder) paramView.getTag();
}

Categories

Resources