I want to sort listview on the basis of counter but i am unable to do that please any body help me on that.
Here i am sharing my code and screen shot.
This is the adapter which is linked to the listview
Custom_adapter_group.java
public class CustomAdapter_groups extends BaseAdapter {
String phone = "";
Button bttn_request;
ArrayList<DiscoverModel> discoverModel;
SharedPreference_Main sharedPreference;
String[] result;
String[] details;
private Context context;
private int[] prgmImages;
private LayoutInflater inflater = null;
public Database4 db4;
private ArrayList<DiscoverModel> listupdate;
protected int position;
public CustomAdapter_groups(Context context,
ArrayList<DiscoverModel> discoverModel) {
// TODO Auto-generated constructor stub
this.context = context;
this.discoverModel = discoverModel;
this.listupdate = listupdate;
this.inflater = (LayoutInflater) ((context))
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
db4 = new Database4(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return discoverModel.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return discoverModel.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder {
TextView tv;
ImageView img;
TextView tv_pushcounter;
private Holder() {
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
sharedPreference = new SharedPreference_Main(context);
final Holder holder;
if (convertView == null) {
holder = new Holder();
convertView = this.inflater.inflate(
R.layout.fragment_others_list_view_elements, null);
holder.tv = (TextView) convertView.findViewById(R.id.tv_foodibdhe);
holder.img = (ImageView) convertView.findViewById(R.id.iv_foodie);
holder.tv_pushcounter = (TextView) convertView
.findViewById(R.id.tv_pushcounter);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
if (discoverModel.get(position) != null) {
holder.tv.setText(discoverModel.get(position).getGroupname());
// //Condition for counter
if (db4.getCounter(discoverModel.get(position).getGroupchatid()) == "0") {
holder.tv_pushcounter.setVisibility(View.GONE);
} else if (db4.getCounter(discoverModel.get(position)
.getGroupchatid()) == "101") {
holder.tv_pushcounter.setText("100+");
}
holder.tv_pushcounter.setText(db4.getCounter(discoverModel.get(
position).getGroupchatid()));
Picasso.with(context)
.load(discoverModel.get(position).getGroupimage())
.resize(200, 200).centerCrop()
.transform(new CircleTransform())
.into(holder.img, new Callback() {
#Override
public void onError() {
holder.img
.setBackgroundResource(R.drawable.group_friend_list_icon);
}
#Override
public void onSuccess() {
}
});
}
String update1 = sharedPreference.getlistupdate1();
// if (!update1.equalsIgnoreCase("")) {
// discoverModel.add(0, discoverModel.get(position));
// discoverModel.
// notifyDataSetChanged();
// }
notifyDataSetChanged();
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(context,
Private_group_chat_activity.class);
sharedPreference = new SharedPreference_Main(context);
sharedPreference.is_slient(""
+ discoverModel.get(position).getIs_slient());
i.putExtra("public_group", "1");
i.putExtra("isMember", ""
+ discoverModel.get(position).getIsMember());
i.putExtra("groupidentify", ""
+ discoverModel.get(position).getGroup_identify());
i.putExtra("public_priavte_Identify",
"" + discoverModel.get(position).getPublic_private());
i.putExtra("groupchatid", ""
+ discoverModel.get(position).getGroupchatid());
i.putExtra("groupname", ""
+ discoverModel.get(position).getGroupname());
i.putExtra("groupId", ""
+ discoverModel.get(position).getGroupid());
i.putExtra("isAdmin", ""
+ discoverModel.get(position).getIsAdmin());
context.startActivity(i);
// discoverModel.add(0, discoverModel.get(position));
// notifyDataSetChanged();
}
});
return convertView;
Collections.sort(discoverModel, myComparator);
}
public Comparator<Database4> myComparator = new Comparator<Database4>() {
public int compare(Database4 obj1, Database4 obj2) {
return obj1
.getCounter(discoverModel.get(position).getGroupchatid())
.compareTo(
obj2.getCounter(discoverModel.get(position)
.getGroupchatid()));
}
};
}
Here is the code where ListView is used
Fragment_groups.java
public class Fragment_groups extends Fragment implements ApiConstants,UpdateListener
{
private static int FLAG = 0;
private ListView lv_list_view;
private RelativeLayout rl_foodie;
private EditText et_type_groups;
private Database2 db2;
private Database4 db4;
private String newResponse;
private String counter;
private Button bttn_create_private_group;
private ArrayList<DiscoverModel> discoverModel;
private ArrayList<DiscoverModel> listupdate;
private CustomAdapter_groups CustomAdapter_groups;
SharedPreference_Main sharedPreference;
public ArrayList<DiscoverModel> discoverModelSearch;
public ArrayList<DiscoverModel> discoverModelStore;
Activity activity;
// Fragment_groups context;
public static int\[\] prgmImages = { R.drawable.group_chat_icon,
R.drawable.group_chat_icon, R.drawable.group_chat_icon };
public static String\[\] prgmNameList = { "Foodie", "Football" };
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
sharedPreference = new SharedPreference_Main(getActivity());
View v = inflater.inflate(R.layout.fragment_others, container, false);
// Inflate the layout for this fragment
// this.setUpdatedCounter();
activity = this.getActivity();
lv_list_view = (ListView) v.findViewById(R.id.lv_list_view);
et_type_groups = (EditText) v.findViewById(R.id.et_type_groups);
discoverModel = new ArrayList<DiscoverModel>();
listupdate = new ArrayList<DiscoverModel>();
discoverModelSearch = new ArrayList<DiscoverModel>();
discoverModelStore = new ArrayList<DiscoverModel>();
db2 = new Database2(getActivity());
db4 = new Database4(getActivity());
bttn_create_private_group = (Button) v
.findViewById(R.id.bttn_create_private_group);
bttn_create_private_group.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity(), Private_group.class);
startActivity(intent);
}
});
et_type_groups.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
searchText(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
get_groups_api();
isOnline();
return v;
}
private void isOnline() {
// TODO Auto-generated method stub
ConnectivityManager conMgr = (ConnectivityManager) getActivity()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if (netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()) {
Toast.makeText(getActivity(), "No Internet connection!",
Toast.LENGTH_LONG).show();
newResponse = db2.getResponse(getActivity(), newResponse, 3);
jsonparsing(newResponse);
}
return;
}
public void get_groups_api() {
FLAG = 0;
// TODO Auto-generated method stub
final ProgressDialog pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
StringRequest sr = new StringRequest(Request.Method.POST,
"http://unichatapi.approutes.com:80/groups",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pDialog.hide();
discoverModel.clear();
// parsing method passing the response
Log.e("groups response", "" + response);
jsonparsing(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.hide();
VolleyLog.e("TAG", "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("deviceId", sharedPreference.getRegisteration_id());
params.put("sessionId", "" + sharedPreference.getSession());
params.put("option", "getGroups");
params.put("userId", "" + sharedPreference.getUserId());
params.put("unixTime", "" + 0);
return params;
}
};
AppController.getInstance().addToRequestQueue(sr);
}
protected void jsonparsing(String response) {
// TODO Auto-generated method stub
db2.update(response, 2, "1");
try {
JSONObject jsonO = new JSONObject(response);
Log.e("message", "" + jsonO.getString("message"));
Log.e("serverTime", "" + jsonO.getString("serverTime"));
sharedPreference.server_time(jsonO.getString("serverTime"));
// code for public group
JSONArray publicgroupsA = jsonO.getJSONArray("publicGroups");
for (int i = 0; i < publicgroupsA.length(); i++) {
DiscoverModel cm = new DiscoverModel();
JSONObject public_groupO = publicgroupsA.getJSONObject(i);
// if(sharedPreference.getlistupdate1().equalsIgnoreCase(public_groupO.getString("groupChatId")))
// {
// listupdate.add(cm);
// }
DiscoverModel dm = new DiscoverModel();
dm.setGroup_identify("1");
dm.setPublic_private("0");
dm.setIs_slient(public_groupO.getString("is_silent"));
dm.setGroupid(public_groupO.getString("groupId"));
Log.e("groupId", "" + public_groupO.getString("groupId"));
dm.setGroupname(public_groupO.getString("groupName"));
Log.e("groupName", "" + public_groupO.getString("groupName"));
dm.setGroupimage("http://unichatapi.approutes.com/vchatfiles/"
+ public_groupO.getString("groupImage"));
dm.setGroupchatid(public_groupO.getString("groupChatId"));
// counter = db4.getCounter(dm.getGroupchatid());
Log.e("value from counter",""+counter);
// dm.setPushcounter(counter);
dm.setGroup_modified_on(public_groupO.getString("modifiedOn"));
dm.setGroup_created_on(public_groupO.getString("createdOn"));
discoverModel.add(dm);
db4.insertIncidentDetails(getActivity(), dm);
}
// code for private group
JSONArray fullDataA = jsonO.getJSONArray("fullData");
for (int j = 0; j < fullDataA.length(); j++) {
DiscoverModel fm = new DiscoverModel();
JSONObject jsongroup = fullDataA.getJSONObject(j);
fm.setGroup_identify("2");
fm.setPublic_private("1");
fm.setGroupid(jsongroup.getString("groupId"));
fm.setIsMember(jsongroup.getString("isMember"));
fm.setIsAdmin(jsongroup.getString("isAdmin"));
fm.setGroupname(jsongroup.getString("groupName"));
fm.setGroupimage("http://unichatapi.approutes.com/vchatfiles/"
+ jsongroup.getString("groupImage"));
fm.setGroupchatid(jsongroup.getString("groupChatId"));
fm.setGroup_modified_on(jsongroup.getString("modifiedOn"));
fm.setGroup_created_on(jsongroup.getString("createdOn"));
Log.e("groupid", "" + jsongroup.getString("groupId"));
Log.e("groupName", "" + jsongroup.getString("groupName"));
Log.e("groupImage", "" + jsongroup.getString("groupImage"));
Log.e("groupChatId", "" + jsongroup.getString("groupChatId"));
Log.e("modifiedOn", "" + jsongroup.getString("modifiedOn"));
Log.e("createdOn", "" + jsongroup.getString("createdOn"));
discoverModel.add(fm);
db4.insertIncidentDetails(getActivity(), fm);
// CustomAdapter_groups.notifyDataSetChanged();
}
CustomAdapter_groups = new CustomAdapter_groups(getActivity(),
discoverModel);
lv_list_view.setAdapter(CustomAdapter_groups);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "" + e, Toast.LENGTH_SHORT).show();
}
}
public LayoutInflater getSystemService(String layoutInflaterService) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(broadcastReceiver, new IntentFilter("com.example.vchat"));
}
#Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(broadcastReceiver);
}
public void searchText(String chartext) {
// TODO Auto-generated method stub
chartext = chartext.toLowerCase(Locale.getDefault());
if (FLAG == 0) {
discoverModelStore.clear();
discoverModelStore.addAll(discoverModel);
FLAG = 1;
}
discoverModelSearch.clear();
discoverModelSearch.addAll(discoverModelStore);
discoverModel.clear();
if (chartext.length() == 0) {
// discoverModel.clear();
discoverModel.addAll(discoverModelStore);
CustomAdapter_groups.notifyDataSetChanged();
} else if (chartext.length() >= 0) {
// discoverModel.clear();
for (DiscoverModel dm : discoverModelSearch) {
if (dm.getGroupname().toLowerCase(Locale.getDefault())
.contains(chartext)) {
discoverModel.add(dm);
}
}
}
CustomAdapter_groups.notifyDataSetChanged();
}
#Override
public void setUpdatedCounter() {
// TODO Auto-generated method stub
}
BroadcastReceiver broadcastReceiver=new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
CustomAdapter_groups.notifyDataSetChanged();
}
};
}
here is the screen shot of screen
Try sort list in desc order, use this
Collections.sort(myIntegerList, new Comparator<Integer>() {
public int compare(Integer one, Integer other) {
if (one >= other) {
return -1;
} else {
return 1;
}
}
});
Check this for more detail.
Related
I have a listview with searchview and multiple selection option.For that i'm trying the following code that is as follows..
Mainactivity:-
public class MainActivity extends Activity {
Context context = null;
ContactsAdapter objAdapter;
ListView lv = null;
EditText edtSearch = null;
LinearLayout llContainer = null;
Button btnOK = null;
RelativeLayout rlPBContainer = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
rlPBContainer = (RelativeLayout) findViewById(R.id.pbcontainer);
edtSearch = (EditText) findViewById(R.id.input_search);
llContainer = (LinearLayout) findViewById(R.id.data_container);
btnOK = (Button) findViewById(R.id.ok_button);
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
getSelectedContacts();
}
});
edtSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
// When user changed the Text
String text = edtSearch.getText().toString()
.toLowerCase(Locale.getDefault());
objAdapter.filter(text);
}
#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
}
});
addContactsInList();
}
private void getSelectedContacts() {
// TODO Auto-generated method stub
StringBuffer sb = new StringBuffer();
for (ContactObject bean : ContactsListClass.phoneList) {
if (bean.isSelected()) {
sb.append(bean.getName());
sb.append(",");
}
}
String s = sb.toString().trim();
if (TextUtils.isEmpty(s)) {
Toast.makeText(context, "Select atleast one Contact",
Toast.LENGTH_SHORT).show();
} else {
s = s.substring(0, s.length() - 1);
Toast.makeText(context, "Selected Contacts : " + s,
Toast.LENGTH_SHORT).show();
}
}
private void addContactsInList() {
// TODO Auto-generated method stub
Thread thread = new Thread() {
#Override
public void run() {
showPB();
try {
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, null);
try {
ContactsListClass.phoneList.clear();
} catch (Exception e) {
}
while (phones.moveToNext()) {
String phoneName = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String phoneImage = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
ContactObject cp = new ContactObject();
cp.setName(phoneName);
cp.setNumber(phoneNumber);
cp.setImage(phoneImage);
ContactsListClass.phoneList.add(cp);
}
phones.close();
lv = new ListView(context);
lv.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT));
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
llContainer.addView(lv);
}
});
Collections.sort(ContactsListClass.phoneList,
new Comparator<ContactObject>() {
#Override
public int compare(ContactObject lhs,
ContactObject rhs) {
return lhs.getName().compareTo(
rhs.getName());
}
});
objAdapter = new ContactsAdapter(MainActivity.this,
ContactsListClass.phoneList);
lv.setAdapter(objAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
CheckBox chk = (CheckBox) view
.findViewById(R.id.contactcheck);
ContactObject bean = ContactsListClass.phoneList
.get(position);
if (bean.isSelected()) {
bean.setSelected(false);
chk.setChecked(false);
} else {
bean.setSelected(true);
chk.setChecked(true);
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
hidePB();
}
};
thread.start();
}
void showPB() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
rlPBContainer.setVisibility(View.VISIBLE);
edtSearch.setVisibility(View.GONE);
btnOK.setVisibility(View.GONE);
}
});
}
void hidePB() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
rlPBContainer.setVisibility(View.GONE);
edtSearch.setVisibility(View.VISIBLE);
btnOK.setVisibility(View.VISIBLE);
}
});
}
}
Adapter class:-
public class ContactsAdapter extends BaseAdapter {
Context mContext;
LayoutInflater inflater;
private List<ContactObject> mainDataList = null;
private ArrayList<ContactObject> arraylist;
public ContactsAdapter(Context context, List<ContactObject> mainDataList) {
mContext = context;
this.mainDataList = mainDataList;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<ContactObject>();
this.arraylist.addAll(mainDataList);
}
static class ViewHolder {
protected TextView name;
protected TextView number;
protected CheckBox check;
protected ImageView image;
}
#Override
public int getCount() {
return mainDataList.size();
}
#Override
public ContactObject getItem(int position) {
return mainDataList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.list_row, null);
holder.name = (TextView) view.findViewById(R.id.contactname);
holder.number = (TextView) view.findViewById(R.id.contactno);
holder.check = (CheckBox) view.findViewById(R.id.contactcheck);
holder.image = (ImageView) view.findViewById(R.id.contactimage);
view.setTag(holder);
view.setTag(R.id.contactname, holder.name);
view.setTag(R.id.contactno, holder.number);
view.setTag(R.id.contactcheck, holder.check);
holder.check
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton vw,
boolean isChecked) {
int getPosition = (Integer) vw.getTag();
mainDataList.get(getPosition).setSelected(
vw.isChecked());
}
});
} else {
holder = (ViewHolder) view.getTag();
}
holder.check.setTag(position);
holder.name.setText(mainDataList.get(position).getName());
holder.number.setText(mainDataList.get(position).getNumber());
if (getByteContactPhoto(mainDataList.get(position).getImage()) == null) {
holder.image.setImageResource(R.drawable.abc_ab_share_pack_mtrl_alpha);
} else {
holder.image.setImageBitmap(getByteContactPhoto(mainDataList.get(position).getImage()));
}
holder.check.setChecked(mainDataList.get(position).isSelected());
return view;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
mainDataList.clear();
if (charText.length() == 0) {
mainDataList.addAll(arraylist);
} else {
for (ContactObject wp : arraylist) {
if (wp.getName().toLowerCase(Locale.getDefault())
.contains(charText)) {
mainDataList.add(wp);
}
}
}
notifyDataSetChanged();
}
public Bitmap getByteContactPhoto(String contactId) {
Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(contactId));
Uri photoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = mContext.getContentResolver().query(photoUri,
new String[]{ContactsContract.Contacts.Photo.DATA15}, null, null, null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return BitmapFactory.decodeStream(new ByteArrayInputStream(data));
}
}
} finally {
cursor.close();
}
return null;
}
}
my problem is
step-1 : i have selected a contact from the listview.
step-2 : now i have searched for xxx contact and i selected it.
step-3 : now when i press on ok button it is retrieving only xxx contact.
step-4 : It needs to retrieve all the selected contacts from the view
How can i do that help me in solving this.
You can simply make a list of objects and everytime user select an item in list view you add object contained in this view, and go further. If user wants to delete an object just search for it in your list and delete it.
with the help of This link
I have taken the one array and added all the selected items before text changing this solved my problem.
MainActivity:-
public class MainActivity extends Activity {
Context context = null;
ContactsAdapter objAdapter;
ListView lv = null;
EditText edtSearch = null;
LinearLayout llContainer = null;
Button btnOK = null;
RelativeLayout rlPBContainer = null;
ArrayList<String> selected = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
rlPBContainer = (RelativeLayout) findViewById(R.id.pbcontainer);
edtSearch = (EditText) findViewById(R.id.input_search);
llContainer = (LinearLayout) findViewById(R.id.data_container);
btnOK = (Button) findViewById(R.id.ok_button);
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
getSelectedContacts();
}
});
edtSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
// When user changed the Text
String text = edtSearch.getText().toString()
.toLowerCase(Locale.getDefault());
objAdapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
for (ContactObject bean : ContactsListClass.phoneList) {
if (bean.isSelected()) {
selected.add(bean.getName());
}
}
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
addContactsInList();
}
private void getSelectedContacts() {
StringBuffer sb = new StringBuffer();
for (ContactObject bean : ContactsListClass.phoneList) {
if (bean.isSelected()) {
selected.add(bean.getName());
}
}
for (int i = 0; i < selected.size(); i++) {
sb.append(selected.get(i));
sb.append(",");
}
String s = sb.toString().trim();
if (TextUtils.isEmpty(s)) {
Toast.makeText(context, "Select atleast one Contact",
Toast.LENGTH_SHORT).show();
} else {
s = s.substring(0, s.length() - 1);
Toast.makeText(context, "Selected Contacts : " + s,
Toast.LENGTH_SHORT).show();
}
}
private void addContactsInList() {
Thread thread = new Thread() {
#Override
public void run() {
showPB();
try {
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, null);
try {
ContactsListClass.phoneList.clear();
} catch (Exception e) {
}
while (phones.moveToNext()) {
String phoneName = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String phoneImage = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
ContactObject cp = new ContactObject();
cp.setName(phoneName);
cp.setNumber(phoneNumber);
cp.setImage(phoneImage);
ContactsListClass.phoneList.add(cp);
}
phones.close();
lv = new ListView(context);
lv.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT));
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
llContainer.addView(lv);
}
});
Collections.sort(ContactsListClass.phoneList,
new Comparator<ContactObject>() {
#Override
public int compare(ContactObject lhs,
ContactObject rhs) {
return lhs.getName().compareTo(
rhs.getName());
}
});
objAdapter = new ContactsAdapter(MainActivity.this,
ContactsListClass.phoneList);
lv.setAdapter(objAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
CheckBox chk = (CheckBox) view
.findViewById(R.id.contactcheck);
ContactObject bean = ContactsListClass.phoneList
.get(position);
if (bean.isSelected()) {
bean.setSelected(false);
chk.setChecked(false);
} else {
bean.setSelected(true);
chk.setChecked(true);
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
hidePB();
}
};
thread.start();
}
void showPB() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
rlPBContainer.setVisibility(View.VISIBLE);
edtSearch.setVisibility(View.GONE);
btnOK.setVisibility(View.GONE);
}
});
}
void hidePB() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
rlPBContainer.setVisibility(View.GONE);
edtSearch.setVisibility(View.VISIBLE);
btnOK.setVisibility(View.VISIBLE);
}
});
}
}
I am working on ListView Adapter, and trying to make a button visible when clicked on EditText. It is working for one item, but is not working when I am trying to do that for multiple items. When I click on EditText at the first position, at that time my other position item buttons are not shown.
public class CartAdapter extends BaseAdapter {
Context context;
ViewHolder holder;
public ArrayList<CartList> arr_cart;
private AsyncHttpClient client;
private RequestParams params;
private TextView tv_PayableAmount;
double dNationalShippingCost, dInternationalShippingCost, dSellingPrice,
dQuantity, TotalCost, dgetPayableTotal, dGrandTotal;
String totalString = null, sShippingCost = null, sNationalShippingCost,
sInternationalShippingCost, sQuantity, sSellingPrice,
sgetPayableTotal, sGrandTotal;
int count = 0;
Double d = null;
SessionManager sessionManager;
HashMap<String, String> userData;
private static LayoutInflater inflater = null;
public CartAdapter(Context context, ArrayList<CartList> arr_cart,
TextView tv_PayableAmount) {
// TODO Auto-generated constructor stub
this.context = context;
this.arr_cart = arr_cart;
this.tv_PayableAmount = tv_PayableAmount;
sessionManager = new SessionManager(context);
userData = sessionManager.getUserDetails();
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
private static class ViewHolder {
private TextView tv_Title, tv_Price, tv_SellingPrice,
tv_ShippingCharge, tv_TotalPrice, tv_Qty, tv_ShowSellingPrice,
tv_ShowShippingCharge, tv_ShowTotalPrice;
private EditText edt_Qty;
private Button btn_Save;
private ImageView iv_Cancel, iv_ProductImage;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arr_cart.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.cart_item, null);
holder.iv_ProductImage = (ImageView) convertView
.findViewById(R.id.iv_ProductImage);
holder.tv_Title = (TextView) convertView
.findViewById(R.id.tv_Title);
holder.tv_Qty = (TextView) convertView.findViewById(R.id.tv_Qty);
holder.edt_Qty = (EditText) convertView.findViewById(R.id.edt_Qty);
holder.btn_Save = (Button) convertView.findViewById(R.id.btn_Save);
holder.tv_Price = (TextView) convertView
.findViewById(R.id.tv_Price);
holder.tv_ShowSellingPrice = (TextView) convertView
.findViewById(R.id.tv_ShowSellingPrice);
holder.tv_SellingPrice = (TextView) convertView
.findViewById(R.id.tv_SellingPrice);
holder.tv_ShowShippingCharge = (TextView) convertView
.findViewById(R.id.tv_ShowShippingCharge);
holder.tv_ShippingCharge = (TextView) convertView
.findViewById(R.id.tv_ShippingCharge);
holder.tv_ShowTotalPrice = (TextView) convertView
.findViewById(R.id.tv_ShowTotalPrice);
holder.tv_TotalPrice = (TextView) convertView
.findViewById(R.id.tv_TotalPrice);
holder.iv_Cancel = (ImageView) convertView
.findViewById(R.id.iv_Cancel);
// holder.iv_Cancel.setTag(arr_cart.get(position));
// holder.btn_Save.setTag(arr_cart.get(position));
// holder.edt_Qty.setTag(arr_cart.get(position));
setTypeface();
convertView.setTag(holder);
} else {
// the getTag returns the viewHolder object set as a tag to the view
holder = (ViewHolder) convertView.getTag();
}
String[] image = arr_cart.get(position).getImage().split(",");
String firstImage = image[0];
if (firstImage.equals("")) {
} else {
Picasso.with(this.context).load(firstImage)
.into(holder.iv_ProductImage);
}
holder.tv_Title.setText(arr_cart.get(position).getAddTitle());
holder.edt_Qty.setText(arr_cart.get(position).getQuantity());
holder.tv_Price.setText(arr_cart.get(position).getAddPrice());
holder.tv_SellingPrice.setText(arr_cart.get(position)
.getAddSellingPrice());
makeTotal(position);
holder.iv_Cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
deleteCartItem(position);
}
});
holder.edt_Qty.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// updatequantity = holder.edt_Qty.getText().toString();
holder.btn_Save.setVisibility(View.VISIBLE);
}
});
holder.btn_Save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
updateQuantity(position);
holder.btn_Save.setVisibility(View.GONE);
}
});
return convertView;
}
private void makeTotal(int position) {
// TODO Auto-generated method stub
try {
// get cost in String
sSellingPrice = arr_cart.get(position).getAddSellingPrice();
sNationalShippingCost = arr_cart.get(position)
.getAddNationalShippingCharge();
sInternationalShippingCost = arr_cart.get(position)
.getAddWorldShippingCharge();
sQuantity = holder.edt_Qty.getText().toString();
// sQuantity = arr_cart.get(position).getQuantity();
// convert in to double
dSellingPrice = Double.parseDouble(sSellingPrice);
dNationalShippingCost = Double.parseDouble(sNationalShippingCost);
dInternationalShippingCost = Double
.parseDouble(sInternationalShippingCost);
dQuantity = Double.parseDouble(sQuantity);
// total Shipping Cost in double
TotalCost = dQuantity
* (dInternationalShippingCost + dSellingPrice);
// convert in to string
sShippingCost = Double.toString(dInternationalShippingCost);
totalString = Double.toString(TotalCost);
holder.tv_ShippingCharge.setText(sShippingCost);
holder.tv_TotalPrice.setText(totalString);
} catch (NumberFormatException e) {
}
}
private void setTypeface() {
// TODO Auto-generated method stub
holder.tv_Title.setTypeface(Global.SetFontRegular(context));
holder.tv_Qty.setTypeface(Global.SetFontRegular(context));
holder.edt_Qty.setTypeface(Global.SetFontRegular(context));
holder.btn_Save.setTypeface(Global.SetFontRegular(context));
holder.tv_Price.setTypeface(Global.SetFontRegular(context));
holder.tv_SellingPrice.setTypeface(Global.SetFontRegular(context));
holder.tv_ShowSellingPrice.setTypeface(Global.SetFontRegular(context));
holder.tv_ShippingCharge.setTypeface(Global.SetFontRegular(context));
holder.tv_ShowShippingCharge
.setTypeface(Global.SetFontRegular(context));
holder.tv_TotalPrice.setTypeface(Global.SetFontRegular(context));
holder.tv_ShowTotalPrice.setTypeface(Global.SetFontRegular(context));
holder.tv_Title.setTypeface(Global.SetFontRegular(context));
holder.tv_Title.setTypeface(Global.SetFontRegular(context));
}
private void deleteCartItam(final int delete_position) {
// TODO Auto-generated method stub
client = new AsyncHttpClient();
params = new RequestParams();
client.getHttpClient()
.getParams()
.setParameter(CoreProtocolPNames.USER_AGENT,
Global.SERVER_HEADER);
params.put("cartId", arr_cart.get(delete_position).getCartId());
Log.e("params", "" + params);
client.post(Global.REMOVE_PRODUCT_FROM_CART_URL, params,
new JsonHttpResponseHandler() {
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
#Override
public void onSuccess(int statusCode, Header[] headers,
JSONObject response) {
// TODO Auto-generated method stub
if (response != null) {
try {
if (response.getInt("ResponseCode") == 1
&& response.getBoolean("Result") == true) {
// Log.e("OnSuccess", "OnSuccess : "
// + response);
makeTotal(delete_position);
sgetPayableTotal = tv_PayableAmount
.getText().toString();
dgetPayableTotal = Double
.parseDouble(sgetPayableTotal);
// Log.e("total pay", "" + dgt);
// Log.e("delete total", "" + TotalCost);
dGrandTotal = dgetPayableTotal - TotalCost;
// Log.e("after delete pos", "" + grnto);
sGrandTotal = Double.toString(dGrandTotal);
tv_PayableAmount.setText(sGrandTotal);
arr_cart.remove(delete_position);
arr_cart.trimToSize();
CartAdapter.this.notifyDataSetChanged();
Global.ShowTost(context,
"Your Item is Deleted successfuly");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
// TODO Auto-generated method stub
super.onFailure(statusCode, headers, responseString,
throwable);
Log.e("onFailure", "onFailure : " + responseString);
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
super.onFinish();
}
});
}
#SuppressWarnings("static-access")
private void updateQuantity(final int update_position) {
// TODO Auto-generated method stub
client = new AsyncHttpClient();
params = new RequestParams();
client.getHttpClient()
.getParams()
.setParameter(CoreProtocolPNames.USER_AGENT,
Global.SERVER_HEADER);
params.put("userId", userData.get(sessionManager.KEY_USERID));
params.put("addId", arr_cart.get(update_position).getAddId());
params.put("quantity", holder.edt_Qty.getText().toString());
params.put("totalPrice", TotalCost);
Log.e("params", "" + params);
client.post(Global.INSERT_PRODUCT_IN_CART_URL, params,
new JsonHttpResponseHandler() {
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
#Override
public void onSuccess(int statusCode, Header[] headers,
JSONObject response) {
// TODO Auto-generated method stub
if (response != null) {
try {
if (response.getInt("ResponseCode") == 1
&& response.getBoolean("Result") == true) {
// Log.e("OnSuccess", "OnSuccess : "
// + response);
// Log.e("olddddddddd", "" + TotalCost);
makeTotal(update_position);
sgetPayableTotal = tv_PayableAmount
.getText().toString();
dgetPayableTotal = Double
.parseDouble(sgetPayableTotal);
// Log.e("old totel", "" +
// dgetPayableTotal);
// Log.e("after update quantity", ""
// + TotalCost);
// Log.e("old delete total", ""
// + arr_cart.get(update_position)
// .getTotalPrice());
if (count == 0) {
updateQuantity(update_position);
// Log.e("in loop old totel", ""
// + dgetPayableTotal);
// Log.e("in loop after update quantity",
// "" + TotalCost);
// Log.e("in loop old delete total", ""
// + arr_cart.get(update_position)
// .getTotalPrice());
String str = arr_cart.get(
update_position)
.getTotalPrice();
d = Double.parseDouble(str);
// Log.e("dddd", "" + d);
double add = dgetPayableTotal
+ TotalCost;
// Log.e("add", "" + add);
dGrandTotal = add - d;
// Log.e("dGrandTotal", "" +
// dGrandTotal);
count++;
} else {
}
sGrandTotal = Double.toString(dGrandTotal);
tv_PayableAmount.setText(sGrandTotal);
// CartAdapter.this.notifyDataSetChanged();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
// TODO Auto-generated method stub
super.onFailure(statusCode, headers, responseString,
throwable);
Log.e("onFailure", "onFailure : " + responseString);
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
super.onFinish();
}
});
}
}
here is the sample code of your problem
ButtonList.java
package com.example.helppeople;
import java.util.ArrayList;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.ListView;
public class ButtonList extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
ListView mLists = (ListView) findViewById(R.id.listbutton);
ArrayList<SampleList> mList = new ArrayList<SampleList>();
mList.add(new SampleList("123"));
mList.add(new SampleList("456"));
mList.add(new SampleList("789"));
mList.add(new SampleList("012"));
ButtonAdapter mAdapter = new ButtonAdapter(getApplicationContext(),
mList);
mLists.setAdapter(mAdapter);
}
}
listview.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/listbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
ButtonAdapter.java
package com.example.helppeople;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
public class ButtonAdapter extends BaseAdapter {
private ArrayList<SampleList> mList;
private Context mContext;
/*
* Creates the Adapter for the list
*/
public ButtonAdapter(Context context, ArrayList<SampleList> list) {
mList = list;
mContext = context;
}
/**
* inflate view for each row
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
/* if the given channel row view is not being updated */
if (v == null) {
/* inflate layout */
LayoutInflater vi = LayoutInflater.from(mContext);
v = vi.inflate(R.layout.rowlist, null, false);
}
/* get the component pointers */
final TextView etname = (TextView) v.findViewById(R.id.textView1);
final Button button = (Button) v.findViewById(R.id.button1);
etname.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
button.setVisibility(View.VISIBLE);
}
});
return v;
}
#Override
public int getCount() {
return mList.size();
}
#Override
public SampleList getItem(int position) {
return mList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
rowlist.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Button"
android:visibility="gone" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_alignBaseline="#+id/button1"
android:layout_alignBottom="#+id/button1"
android:layout_alignParentLeft="true"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#android:color/black" />
</RelativeLayout>
SampleList.java
package com.example.helppeople;
public class SampleList {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public SampleList(String name) {
super();
this.name = name;
}
}
this is working code, hope it helps you
i am trying to filter the listview using edit text at the top but it providing null pointer exception in the adapter2.filter(text) of add text changed listener . please provide me some suggestion`
Here is my edit text`
friendsList.setAdapter(new FriendListAdapter(this));
search.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = search.getText().toString().toLowerCase(Locale.getDefault());
System.out.println("test=="+text);
adapter2.filter(text);
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
//adapter.getFilter().filter(arg0.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
Here is my adapter
public class FriendListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
FriendsList friendsList;
Context context;
ViewHolder holder;
private boolean userSelected = false;
private RadioButton mCurrentlyCheckedRB;
private int mResourceId = 0;
private LayoutInflater mLayoutInflater;
private RadioButton mSelectedRB;
private int mSelectedPosition = -1;
public FriendListAdapter(FriendsList friendsList) {
this.friendsList = friendsList;
if (Utility.model == null) {
Utility.model = new FriendsGetProfilePics();
}
Utility.model.setListener(this);
mInflater = LayoutInflater.from(friendsList.getBaseContext());
}
#Override
public int getCount() {
return jsonArray.length();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup viewgroup) {
JSONObject jsonObject = null;
Model model = (Model) getItem(position);
try {
jsonObject = jsonArray.getJSONObject(position);
} catch (JSONException e1) {
e1.printStackTrace();
}
View hView = convertView;
if (convertView == null) {
hView = mInflater.inflate(R.layout.friend_item, null);
ViewHolder holder = new ViewHolder();
holder.profile_pic = (ImageView) hView
.findViewById(R.id.profile_pic);
holder.name = (TextView) hView.findViewById(R.id.name);
holder.info = (TextView) hView.findViewById(R.id.info);
holder.radiobt = (RadioButton) hView.findViewById(R.id.radio);
hView.setTag(holder);
}
ViewHolder holder = (ViewHolder) hView.getTag();
if (position == getCount() - 1 && userSelected == false) {
holder.radiobt.setChecked(true);
mCurrentlyCheckedRB = holder.radiobt;
} else {
holder.radiobt.setChecked(false);
}
holder.radiobt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if((position != mSelectedPosition && mSelectedRB != null)){
mSelectedRB.setChecked(false);
}
mSelectedPosition = position;
mSelectedRB = (RadioButton)v;
System.out.println("onItemClick ");
try {
if (graph_or_fql.equals("graph")) {
System.out.println("in if loop ");
friendId = jsonArray.getJSONObject(position).getLong("id");
image = jsonArray.getJSONObject(position).getString("picture");
// sb.append(friendId).append(",");
freind_id = String.valueOf(friendId);
} else {
System.out.println("in else loop ");
friendId = jsonArray.getJSONObject(position).getLong("uid");
image = jsonArray.getJSONObject(position).getString(
"pic_square");
// sb.append(friendId).append(",");
freind_id = String.valueOf(friendId);
}
check = true;
name = jsonArray.getJSONObject(position).getString("name");
Toast.makeText(getApplicationContext(), "You Selected : " + name,
Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
e.getMessage();
}
}
});
if(mSelectedPosition != position){
holder.radiobt.setChecked(false);
}else{
holder.radiobt.setChecked(true);
if(mSelectedRB != null && holder.radiobt != mSelectedRB){
mSelectedRB = holder.radiobt;
}
}
try {
if (graph_or_fql.equals("graph")) {
holder.profile_pic.setImageBitmap(Utility.model.getImage(
jsonObject.getString("id"),
jsonObject.getString("picture")));
} else {
holder.profile_pic.setImageBitmap(Utility.model.getImage(
jsonObject.getString("uid"),
jsonObject.getString("pic_square")));
}
} catch (JSONException e) {
holder.name.setText("");
}
try {
holder.name.setText(jsonObject.getString("name"));
} catch (JSONException e) {
holder.name.setText("");
}
try {
if (graph_or_fql.equals("graph")) {
holder.info.setText(jsonObject.getJSONObject("location")
.getString("name"));
} else {
JSONObject location = jsonObject
.getJSONObject("current_location");
holder.info.setText(location.getString("city") + ", "
+ location.getString("state"));
}
} catch (JSONException e) {
holder.info.setText("");
}
return hView;
}
// Filter Class
public void filter(String charText) {
System.out.println("in adapter filter");
charText = charText.toLowerCase(Locale.getDefault());
System.out.println("1");
rowitems.clear();
System.out.println("2");
if (charText.length() == 0) {
System.out.println("3");
rowitems.addAll(listData);
} else {
for (Model wp : listData) {
if (wp.getName().toLowerCase(Locale.getDefault())
.contains(charText)) {
rowitems.add(wp);
}
}
}
notifyDataSetChanged();
}
private class ViewHolder {
ImageView profile_pic;
TextView name;
TextView info;
// CheckBox check;
RadioButton radiobt;
}
}
Here is my main activity
public class FriendsList extends Activity implements OnItemClickListener{
private Handler mHandler;
public static Long friendId;
public static String name = "";
protected ListView friendsList;
protected static JSONArray jsonArray;
protected String graph_or_fql;
public Button bt;
public static String image = "0";
public boolean check = false;
public static String freind_id = "";
public boolean select = false;
public RadioButton radiobtn;
public ListView friendList;
private List<Model> rowitems=null;
ArrayList<Model> listData;
AdapterList adapter;
EditText search;
FriendListAdapter adapter2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler();
setContentView(R.layout.friends_list);
//radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);
bt = (Button) findViewById(R.id.com_facebook_picker_done_button);
radiobtn = (RadioButton) findViewById(R.id.radio);
search=(EditText) findViewById(R.id.editText100);
Bundle extras = getIntent().getExtras();
String apiResponse = extras.getString("API_RESPONSE");
graph_or_fql = extras.getString("METHOD");
try {
if (graph_or_fql.equals("graph")) {
jsonArray = new JSONObject(apiResponse).getJSONArray("data");
} else {
jsonArray = new JSONArray(apiResponse);
}
} catch (JSONException e) {
e.printStackTrace();
e.getMessage();
return;
}
friendsList = (ListView) findViewById(R.id.friends_list);
// friendsList.setAdapter(new FriendListAdapter(this));
adapter2=new FriendListAdapter(this);
friendsList.setAdapter(adapter2);
friendsList.setOnItemClickListener(this);
search.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
adapter2.getFilter().filter(arg0.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
i am passing the facebook friend list to the listview.please provide some suggestion
Thanks in advance
For filter the listview using edit text at the top .
I used this code.
Make one list called searchResults than in onTextChanged method of edittext simply do this-
String searchString = `your edittext object`.getText().toString();
int textLength = searchString.length();
searchResults.clear();
for (int i = 0; i < `your main list of items`.size(); i++) {
String name = `your main list of items`.get(i).get("`your key`").toString();
System.out.println(" name " + name);
if (textLength <= title.length()) {
// compare the String in EditText with Names in the
// ArrayList
if (searchString.equalsIgnoreCase(name.substring(0, textLength))) {
searchResults.add(`your main list of items`.get(i));
System.out.println("the array list is "+ `your main list of items`.get(i));
mAdapter = new Adapter(this, searchResults);
`your ListView object`.setAdapter(mAdapter);
}
}
}
if (searchResults.isEmpty()) {
Toast toast = Toast.makeText(getApplicationContext(),"No Items Matched",Toast.LENGTH_SHORT);
toast.show();
mAdapter = new Adapter(this, searchResults);
`your ListView object`.setAdapter(mAdapter);
}
mAdapter.notifyDataSetChanged();
and on setOnItemClickListener just check searchResults.isEmpty() if true than use your your main list of items and if false than use searchResults list.
May be it will help you.try this.
change your filter with following code:
#Override
public Filter getFilter() {
//Log.d("in filter", "yes");
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
and set your list in this function and after set your list :
oReturn.values = YourList;
and finall
return oReturn;
and in Your search.addTextChangedListener(new TextWatcher()) just in onTextChanged add following line:
adapter2.getFilter().filter(s.toString());
Try this,
adapter2=new FriendListAdapter(this);
friendsList.setAdapter(adapter2);
i developing autocomplete textview and i used search from webservice used .but my problem is autocomplete textview set listview but i coudn't see listview updated.how to possible.my code below>please help me!!!
public class AddUserListActivity extends Activity{
// private SimpleSectionAdapter<String> sectionAdapter;
ListView listUser;
private List<String> lastName = new ArrayList<String>();
DtoUserDetail mApplication;
ArrayList<DtoUserList> ListArray;
private UserListAdapter objAdapter;
Button AddFriends;
DbServices Dbs = new DbServices();
Button btnBackAddUser;
Button btnAddFriends;
Button btnBackToMain;
RelativeLayout searchBar;
Button btnSearchSend;
AutoCompleteTextView editSearchText;
ArrayList<DtoSearchUser> searchUserList;
boolean searchStatus = false;
List<String> searchUserNameList;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add_user_list);
listUser = (ListView)findViewById(R.id.listView);
mApplication = (DtoUserDetail)AddUserListActivity.this.getApplicationContext();
btnBackToMain = (Button)findViewById(R.id.btnBackFromAddFriends);
searchBar = (RelativeLayout)findViewById(R.id.searchbar);
btnSearchSend = (Button)findViewById(R.id.btnSearchSend);
editSearchText =(AutoCompleteTextView)findViewById(R.id.editSearchText);
// objAdapter.notifyDataSetChanged();
btnSearchSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
searchUserList = new ArrayList<DtoSearchUser>();
searchUserNameList = new ArrayList<String>();
Log.v("adduserlist", "searchtext:" + editSearchText.getText().toString());
searchUserList = new DbServices().SendSearchText(editSearchText.getText().toString(),mApplication.getUserid()+"");
for(int i=0;i<searchUserList.size();i++)
{
searchUserNameList.add(searchUserList.get(i).getUsers());
}
Log.v("log", " search list userName " + searchUserNameList);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(AddUserListActivity.this, android.R.layout.simple_dropdown_item_1line, searchUserNameList);
editSearchText.setAdapter(adapter);
}
});
editSearchText.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
// TODO Auto-generated method stub
Log.v("log"," position in autocomplete " + pos);
String toUserId = searchUserList.get(pos).getUserid()+"";
Log.v("log"," autocomplete USERID " + searchUserList.get(pos).getUserid() + " " + searchUserList.get(pos).getLast_name());
String status= Dbs.addFriends(mApplication.getUserid()+"",toUserId);
Toast.makeText(AddUserListActivity.this, "ToUserId : " +toUserId + " status"+ status , Toast.LENGTH_LONG).show();
}
});
btnAddFriends=(Button)findViewById(R.id.btnAddFriends);
btnAddFriends.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(searchStatus==false)
{
searchBar.setVisibility(View.VISIBLE);
searchStatus = true;
}
else
{
searchBar.setVisibility(View.GONE);
searchStatus = false;
}
}
});
btnBackToMain.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AddUserListActivity.this.finish();
}
});
if (isNetworkAvailable()) {
new MyTask().execute();
} else {
showToast("No Netwrok Connection!!!");
//this.finish();
}
}
class MyTask extends AsyncTask<Void, Void, Void> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(AddUserListActivity.this);
pDialog.setMessage("Loading...");
pDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// ListArray = new DbServices().GetUserList(""+mApplication.getUserid());
ListArray = new DbServices().GetFriendsList(""+mApplication.getUserid());
return null;
}
#Override
protected void onPostExecute(Void result) {
if (null != pDialog && pDialog.isShowing()) {
pDialog.dismiss();
}
if (null == ListArray || ListArray.size() == 0) {
showToast("No data found from web!!!");
// AddUserListActivity.this.finish();
} else {
setAdapterToListview();
}
super.onPostExecute(result);
}
}
// setAdapter
public void setAdapterToListview() {
for(int i=0;i<ListArray.size();i++)
{
lastName.add(ListArray.get(i).getLast_name());
}
for(int j=0;j<SortingArraylist(ListArray).size();j++)
{
}
objAdapter = new UserListAdapter(AddUserListActivity.this,SortingArraylist(ListArray));
listUser.setAdapter(objAdapter);
listUser.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View arg1,
int position, long id) {
Log.v("log"," position of item " + position + " item first name " + ListArray.get(position).getFirst_name());
Intent i_options = new Intent(AddUserListActivity.this,friendsHoldActivity.class);
i_options.putExtra("pos", ListArray.get(position).getUserid());
//startActivity(i_options);
startActivity(i_options);
}
});
}
class ListSectionizer implements Sectionizer<String> {
#Override
public String getSectionTitleForItem(String itemName) {
return itemName.toUpperCase().substring(0, 1);
}
}
public static Comparator<String> StringComparator = new Comparator<String>() {
public int compare(String app1, String app2) {
String stringName1 = app1;
String stringName2 = app2;
return stringName1.compareToIgnoreCase(stringName2);
}
};
private List<String> Sorting(List<String> Names) {
Collections.sort(Names, StringComparator);
return Names;
}
public static Comparator<DtoUserList> StringArrayComparator = new Comparator<DtoUserList>() {
public int compare(DtoUserList app1, DtoUserList app2) {
DtoUserList stringName1 = app1;
DtoUserList stringName2 = app2;
return stringName1.getLast_name().compareToIgnoreCase(stringName2.getLast_name());
}
};
private ArrayList<DtoUserList> SortingArraylist(ArrayList<DtoUserList> userDetail){
Collections.sort(userDetail ,StringArrayComparator);
return userDetail;
}
// check internet connection
public boolean isNetworkAvailable() {
ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
// Toast is here...
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
}
Apply addTextChangedListener on editSearchText
the in onTextChanged method see if matching content is found in database or arrayList or whatever you have.....
like : arrayList.get(i).toString().toLowerCase().contains(editSearchText.getText().toString())
I have list with a check box in it and when i tick the check box by scrolling the list i get the values into an array.
But now the problem is i have a search box to search and tick.but when i search i get the element which is last ticked into array.
here is my code.
public class Person extends ListActivity {
private TreeMap<String, String> map = new TreeMap<String, String>();
String SEARCH_STRING = "";
private String METHOD_NAME;
private String SERVICENAME;
ArrayList<String[]> DISPLAY = new ArrayList<String[]>();
ArrayList<String[]> SEARCH = new ArrayList<String[]>();
ArrayList<Boolean> ok = new ArrayList<Boolean>();
SoapIntractions intractions;
public static ArrayList<String[]> dataList=new ArrayList<String[]>();
boolean FLAG;
EditText search;
Button search_btn, back_btn;
LinearLayout tab1, tab2;
public Context c;
static class Viewholder {
TextView name, number;
CheckBox check;
}
public class EfficientAdapter extends BaseAdapter {
LayoutInflater inflater;
Context c;
public EfficientAdapter(Context addNote, int itemadd, Object object,
int[] to) {
// TODO Auto-generated constructor stub
inflater = LayoutInflater.from(addNote);
c = addNote;
}
public int getCount() {
// TODO Auto-generated method stub
return SEARCH.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final Viewholder holder;
final int var = position;
if (convertView == null) {
convertView = inflater.inflate(R.layout.person, null);
holder = new Viewholder();
holder.name = (TextView) convertView
.findViewById(R.id.tv_name_prsnLI);
holder.number = (TextView) convertView
.findViewById(R.id.tv_nmbr_prsnLI);
holder.check = (CheckBox) convertView.findViewById(R.id.check);
convertView.setTag(holder);
} else {
holder = (Viewholder) convertView.getTag();
}
CheckBox box=new CheckBox(c);
String[] argg = SEARCH.get(var);
holder.name.setText(argg[0]);
holder.number.setText(argg[1]);
if (ok.get(position)){
holder.check.setChecked(true);
}
else{
holder.check.setChecked(false);
}
holder.check.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (ok.get(var)) {
ok.set(var, false);
} else {
ok.set(var, true);
}
}
});
return convertView;
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.person_list);
StateListDrawable bkBtn = new StateListDrawable(), srchBtn = new StateListDrawable();
bkBtn.addState(new int[] { android.R.attr.state_pressed },
getResources().getDrawable(R.drawable.back_click));
bkBtn.addState(new int[] {}, getResources()
.getDrawable(R.drawable.back));
srchBtn.addState(new int[] { android.R.attr.state_pressed },
getResources().getDrawable(R.drawable.srch_click));
srchBtn.addState(new int[] {},
getResources().getDrawable(R.drawable.srch));
search = (EditText) findViewById(R.id.et_search_prsnL);
search_btn = (Button) findViewById(R.id.btn_search_prsnL);
search_btn.setBackgroundDrawable(srchBtn);
back_btn = (Button) findViewById(R.id.btn_back_prsnL);
back_btn.setBackgroundDrawable(bkBtn);
tab1 = (LinearLayout) findViewById(R.id.lyt_tab1_prsnL);
tab2 = (LinearLayout) findViewById(R.id.lyt_tab2_prsnL);
tab1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
FLAG = false;
tab1.setBackgroundDrawable(getResources().getDrawable(
R.drawable.list_head_click));
tab2.setBackgroundDrawable(getResources().getDrawable(
R.drawable.list_head));
}
});
tab2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
FLAG = true;
tab2.setBackgroundDrawable(getResources().getDrawable(
R.drawable.list_head_click));
tab1.setBackgroundDrawable(getResources().getDrawable(
R.drawable.list_head));
}
});
search_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SEARCH_STRING = search.getText().toString();
SEARCH.clear();
SearchPageTask srch_task = new SearchPageTask();
srch_task.execute(new String[] { null });
Log.d("SEARCH", "Searchable");
}
});
back_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int len=ok.size();
for(int i=0;i<len;i++){
if(ok.get(i)){
dataList.add(new String[]{SEARCH.get(i)[0],SEARCH.get(i)[1],SEARCH.get(i)[2],SEARCH.get(i)[3] });
}
}
Intent in=new Intent(getApplicationContext(),Multiple_view.class);
in.putExtra("ARRAY", dataList);
setResult(RESULT_OK,in);
finish();
for (int i = 0; i < dataList.size(); i++) {
Log.d("ARRAY1", ""+dataList.get(i)[0]);
Log.d("ARRAY1", ""+dataList.get(i)[1]);
Log.d("ARRAY1", ""+dataList.get(i)[2]);
Log.d("ARRAY1", ""+dataList.get(i)[3]);
}
}
});
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
FLAG = false;
tab1.setBackgroundDrawable(getResources().getDrawable(
R.drawable.list_head_click));
tab2.setBackgroundDrawable(getResources().getDrawable(
R.drawable.list_head));
METHOD_NAME = "ZaplxTmrDisplayPernr";
SERVICENAME = "ZAPLX_WEB_TMR_DISPLAY_PERNR/ZaplxTmrDisplayPernrRequest";
map = new TreeMap<String, String>();
map.put("IDate", "2012-12-04");
intractions = new SoapIntractions(METHOD_NAME, SERVICENAME, map,
Person.this);
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { null });
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Log.d("POSITION", "" + position);
// CheckBox cb = (CheckBox)
// l.getChildAt(position).findViewById(R.id.check);
// if (cb.isChecked()) {
// cb.setChecked(false);
//
// }
// else
// {
// cb.setChecked(true);
// }
// Intent in1=new Intent();
// String[] argg1 = SEARCH.get(position);
//
// in1.putExtra("number", SEARCH.get(position)[0]);
// in1.putExtra("name", SEARCH.get(position)[1]);
// in1.putExtra("area", SEARCH.get(position)[2]);
// in1.putExtra("group", SEARCH.get(position)[3]);
// setResult(RESULT_OK,in1);
// finish();
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
String[][] data;
int value = 0;
ProgressBar pb;
public DownloadWebPageTask() {
// TODO Auto-generated constructor stub
// flag = string;
value = 0;
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
data = intractions.GetSoapData1();
String[][] subtypeData = data;
int n = subtypeData[0].length;
value = n;
for (int i = 0; i < value; i++) {
String Pernr = subtypeData[0][i];
String Ename = subtypeData[1][i];
String Earea = subtypeData[3][i];
String Egroup = subtypeData[5][i];
ok.add(false);
DISPLAY.add(new String[] { Pernr, Ename, Earea, Egroup });
}
for (int i = 0; i < DISPLAY.size(); i++)
SEARCH.add(DISPLAY.get(i));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
// pb = (ProgressBar) findViewById(R.id.pb);
// pb.setVisibility(View.VISIBLE);
search_btn.setClickable(false);
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
// pb = (ProgressBar) findViewById(R.id.pb);
// pb.setVisibility(View.INVISIBLE);
setListAdapter(new EfficientAdapter(Person.this, R.layout.person,
null, null));
search_btn.setClickable(true);
Log.d("POST_TIME", "Inside post");
super.onPostExecute(result);
}
}
private class SearchPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Log.d("SEARCH", "List Size" + DISPLAY.size());
Log.d("SEARCH", "List Size" + SEARCH.size());
int n = DISPLAY.size();
if (!FLAG) {
for (int i = 0; i < n; i++) {
if (DISPLAY.get(i)[1].toLowerCase().startsWith(
SEARCH_STRING.toLowerCase())) {
SEARCH.add(DISPLAY.get(i));
Log.d("SEARCH_ATSK", "result size " + SEARCH.size());
}
Log.d("SEARCH_ATSK", "" + i + " " + n);
}
} else {
for (int i = 0; i < n; i++) {
if (DISPLAY.get(i)[0].toLowerCase().endsWith(
SEARCH_STRING.toLowerCase())) {
SEARCH.add(DISPLAY.get(i));
Log.d("SEARCH_ATSK", "result size " + SEARCH.size());
}
Log.d("SEARCH_ATSK", "" + i + " " + n);
}
}
return null;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
setListAdapter(new EfficientAdapter(Person.this, R.layout.person,
null, null));
super.onPostExecute(result);
}
}
}