Am developing an application which require multiple contact picker with search option.
I tried http://sachindotg.blogspot.in/2013/11/android-simple-multi-contacts-picker.html
tutorial but it is not working.
public class Display extends Activity implements OnItemClickListener{
ArrayList<String> name1 = new ArrayList<String>();
ArrayList<String> phno1 = new ArrayList<String>();
ArrayList<String> id1 = new ArrayList<String>();
ArrayList<String> tempArrayList;
ArrayList<String> tempArrayList1;
MyAdapter ma ;
Button select;
UserSessionManager session;
StringBuilder checkedcontacts;
String email,name;
EditText inputSearch;
int isScheduled=0;
ListView lv;
public JSONParser jsonParser;
LoginActivity LActivity;
ContentResolver cr1;
private static String CALL_URL = "http://ec2-50-112-186-213.us-west-2.compute.amazonaws.com/outbound_dialer/save_recording.php";
private static String SCHEDULE_URL = "http://ec2-50-112-186-213.us-west-2.compute.amazonaws.com/outbound_dialer/store_recording.php";
private static String URL="h";
/********* for date time picker dialoge***********/
Button ShowDTPicker;
Button ShowDatePicker;
Button ShowTimePicker;
Button Set;
Button ReSet;
Button Cancel;
DatePicker DPic;
TimePicker TPic;
private ViewSwitcher switcher;
static final int DATE_TIME_DIALOG_ID = 999;
Dialog dialog;
final Calendar c = Calendar.getInstance();
SimpleDateFormat dfDate = new SimpleDateFormat("dd-MMM-yyyy hh:mm a");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
jsonParser = new JSONParser();
LActivity =new LoginActivity();
ShowDTPicker = ((Button) findViewById(R.id.button2));
inputSearch = (EditText) findViewById(R.id.inputSearch);
lv= (ListView) findViewById(R.id.lv);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
int textlength = arg0.length();
tempArrayList = new ArrayList<String>();
tempArrayList1=new ArrayList<String>();
for(String c: name1){
if (textlength <= c.length()) {
if (c.toLowerCase().contains(arg0.toString().toLowerCase())) {
tempArrayList.add(c);
int loc=name1.indexOf(c);
tempArrayList1.add(phno1.get(loc));
}
}
}
Log.d("",""+tempArrayList);
ma = new MyAdapter(tempArrayList,tempArrayList1);
lv.setAdapter(ma);
}
#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
}
});
session = new UserSessionManager(getApplicationContext()); // for session
Toast.makeText(getApplicationContext(),
"User Login Status: " + session.isUserLoggedIn(),
Toast.LENGTH_LONG).show();
// Check user login
// If User is not logged in , This will redirect user to LoginActivity.
if(session.checkLogin())
finish();
// get user data from session
HashMap<String, String> user = session.getUserDetails();
// get name
name = user.get(UserSessionManager.KEY_NAME);
// get email
email = user.get(UserSessionManager.KEY_EMAIL);
getAllContacts(this.getContentResolver());
cr1=this.getContentResolver();
// lv= (ListView) findViewById(R.id.lv);
if(tempArrayList==null){
ma = new MyAdapter(name1,phno1);
lv.setAdapter(ma);
}
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
// adding
select = (Button) findViewById(R.id.button1);
select.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
checkedcontacts= new StringBuilder();
for(int i = 0; i < phno1.size(); i++) //name1
{
if(ma.mCheckStates.get(i)==true)
{
//checkedcontacts.append(name1.get(i).toString()); //name1
//checkedcontacts.append(":");
checkedcontacts.append(phno1.get(i).toString()); //name1
checkedcontacts.append(",");
}
else
{
}
}
Toast.makeText(Display.this, checkedcontacts,1000).show();
callNumberAndFinish(checkedcontacts);
}
});
/******************************************date and time picker*******************/
dialog = new Dialog(this);
dialog.setContentView(R.layout.datetimepicker);
switcher = (ViewSwitcher) dialog.findViewById(R.id.DateTimePickerVS);
DPic = (DatePicker) dialog.findViewById(R.id.DatePicker);
TPic = (TimePicker) dialog.findViewById(R.id.TimePicker);
ShowDatePicker = ((Button) dialog.findViewById(R.id.SwitchToDate));
ShowDatePicker.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
switcher.showPrevious();
ShowDatePicker.setEnabled(false);
ShowTimePicker.setEnabled(true);
}
});
ShowTimePicker = ((Button) dialog.findViewById(R.id.SwitchToTime));
ShowTimePicker.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
switcher.showNext();
ShowDatePicker.setEnabled(true);
ShowTimePicker.setEnabled(false);
}
});
Set = ((Button) dialog.findViewById(R.id.SetDateTime));
Set.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
c.set(DPic.getYear(), DPic.getMonth(), DPic.getDayOfMonth(), TPic.getCurrentHour(), TPic.getCurrentMinute());
Toast.makeText(Display.this, ""+dfDate.format(c.getTime()),
Toast.LENGTH_LONG).show();
isScheduled=1;
//------------
checkedcontacts= new StringBuilder();
for(int i = 0; i < phno1.size(); i++) //name1
{
if(ma.mCheckStates.get(i)==true)
{
checkedcontacts.append(name1.get(i).toString()); //name1
checkedcontacts.append(":");
checkedcontacts.append(phno1.get(i).toString()); //name1
checkedcontacts.append(",");
}
else
{
}
}
Toast.makeText(Display.this, checkedcontacts,1000).show();
callNumberAndFinish(checkedcontacts);
//----------
dialog.cancel();
}
});
ReSet = ((Button) dialog.findViewById(R.id.ResetDateTime));
ReSet.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
DPic.updateDate(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
TPic.setCurrentHour(c.get(Calendar.HOUR_OF_DAY));
TPic.setCurrentMinute(c.get(Calendar.MINUTE));
}
});
Cancel = ((Button) dialog.findViewById(R.id.CancelDialog));
Cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.cancel();
}
});
ShowDTPicker.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
DPic.updateDate(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
TPic.setCurrentHour(c.get(Calendar.HOUR_OF_DAY));
TPic.setCurrentMinute(c.get(Calendar.MINUTE));
showDialog(DATE_TIME_DIALOG_ID);
}
});
dialog.setTitle("Select Date Time");
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
#Override
public void onBackPressed() {
LoginActivity.kill=1;
Display.this.finish();
// LActivity.finish();
};
private void callNumberAndFinish(CharSequence number) {
// if (number == null || number.length() == 0) {
// Toast.makeText(this, number, Toast.LENGTH_SHORT).show();
// return;
// }
if (isNetworkAvailable()) {
new CallNumber().execute();
final AlertDialog.Builder dialog = new AlertDialog.Builder(this).setTitle("EezyInvite").setMessage("Invitation Sent Sucessfully.!");
dialog.setPositiveButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
final AlertDialog alert = dialog.create();
alert.show();
// Hide after some seconds
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
#Override
public void run() {
if (alert.isShowing()) {
alert.dismiss();
}
}
};
alert.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
handler.removeCallbacks(runnable);
}
});
handler.postDelayed(runnable, 10000);
} else {
showNoConnectionDialog(Display.this);
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_TIME_DIALOG_ID:
return dialog;
}
return null;
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public void getAllContacts(ContentResolver cr) {
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null,ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC" );
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// String id=phones.getString(phones.getColumnIndex(ContactsContract.Contacts._ID));
String uri11=phones.getString(phones.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI));
name1.add(name);
phno1.add(phoneNumber);
id1.add(uri11);
}
// phones.close();
}
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{ private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1,tv;
ImageView img;
CheckBox cb;
ArrayList<String> tmpArray;
ArrayList<String> tmpArray2;
MyAdapter()
{
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater)Display.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
MyAdapter(ArrayList<String> s,ArrayList<String> s2)
{ tmpArray=s;
tmpArray2=s2;
mCheckStates = new SparseBooleanArray(s.size());
mInflater = (LayoutInflater)Display.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return tmpArray.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 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.row, null);
Drawable background = vi.getBackground();
background.setAlpha(40);
tv= (TextView) vi.findViewById(R.id.textView1);
tv1= (TextView) vi.findViewById(R.id.textView2);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
img =(ImageView)vi.findViewById(R.id.imageView2);
tv.setText(""+ tmpArray.get(position));
tv1.setText(""+ tmpArray2.get(position));
if (id1.get(position) != null) {
img.setImageURI(Uri.parse(id1.get(position)));
} else {
img.setImageResource(R.drawable.user);
}
//img.setImageURI(id1.get(position));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
Log.d("checked contact",""+name1.get(position));
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
Log.d("checked contact","clicked:::"+buttonView.getTag());
}
}
class CallNumber extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... paramVarArgs) {
Log.i(" session User Details", "Saving");
try { Log.d("checked contacts",""+checkedcontacts.toString());
String num = checkedcontacts.toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("numbers",num));
params.add(new BasicNameValuePair("email_id", name));
params.add(new BasicNameValuePair("sms", getIntent().getExtras().getString("getsms")));
Log.d("","scheduled"+isScheduled);
if(isScheduled==1){
params.add(new BasicNameValuePair("scheduled_time",dfDate.format(c.getTime())));
Log.d(" scheduled request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(SCHEDULE_URL, "GET",params);
isScheduled=0;
}else{
Log.d(" Login request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(CALL_URL, "GET",params);
//Log.i("json",""+json.toString());
}
//Log.i("json",""+json.toString());
return null;
} catch (Exception exception) {
//for (;;) {
exception.printStackTrace();
//}
}
return null;
}
}
public static void showNoConnectionDialog(Context ctx1) {
final Context ctx = ctx1;
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setCancelable(true);
builder.setMessage("Turn on your internet..!");
builder.setTitle("No Internet Conncetion");
builder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ctx.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
return;
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
return;
}
});
builder.show();
}
}
from the above code am able to pick contact from the list using checkboxes, but now i want to add search functionality also . i added edit text and on the text changed am able to get the sorted contacts but previously selected contacts were gone every time. so how to maintain the selected contacts remain selected.
Related
I am developing an apps. Where i Want to add a search functionality but i failed to do it. I try to search the whole list but my search is work only in one item in the list view.
Here is my MainActivity Code
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
private ProgressBar spinner;
ArrayList<HashMap<String, String>> arraylist;
private long lastPressedTime;
public static String imgURL = "url";
public static String VIDEO_ID = "videoId";
public static String TITLE = "title";
EditText editsearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
final boolean b=wifiManager.isWifiEnabled();
ConnectivityManager cManager=(ConnectivityManager)getSystemService(this.CONNECTIVITY_SERVICE);
final NetworkInfo nInfo=cManager.getActiveNetworkInfo();
if(nInfo!=null&& nInfo.isConnected()) {
Toast.makeText(this, "You are Connected to the Internet", Toast.LENGTH_LONG).show();
setContentView(R.layout.listview_main);
spinner = (ProgressBar)findViewById(R.id.progressBar1);
new DownloadJSON().execute();
}
else {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Your DATA Connection is Currently Unreachable")
.setMessage("Connect your WiFi or 2G/3G DATA Connection")
.setPositiveButton("WiFi ", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
final Intent mainIntent = new Intent(MainActivity.this, MainActivity.class);
MainActivity.this.startActivity(mainIntent);
MainActivity.this.finish();
}
}, 5000);
wifiManager.setWifiEnabled(true);
Toast.makeText(MainActivity.this, "WiFi Enabling in 5sec Please Wait", Toast.LENGTH_LONG).show();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
})
.setNegativeButton("3G/2G ", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//use here tablayout to work when 3G/2G connecion is available
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
final Intent mainIntent = new Intent(MainActivity.this, MainActivity.class);
MainActivity.this.startActivity(mainIntent);
MainActivity.this.finish();
}
}, 5000);
Intent myints = new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS);
Toast.makeText(MainActivity.this, "Your DATA Connection is NOW Connected", Toast.LENGTH_LONG).show();
startActivity(myints);
}
})
.setNeutralButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "To use this Application you have to Connected to the Internet", Toast.LENGTH_LONG).show();
finish();
}
})
.setCancelable(false)
.show();
}
}
public class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
spinner.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("https://www.googleapis.com/youtube/v3/search?part=id%2Csnippet&q=bangla+video+song&maxResults=50&key=api_key");
try {
// Locate the array name in JSON
JSONArray jsonarray = jsonobject.getJSONArray("items");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
JSONObject jsonObjId = jsonobject.getJSONObject("id");
map.put("videoId", jsonObjId.getString("videoId"));
JSONObject jsonObjSnippet = jsonobject.getJSONObject("snippet");
map.put("title", jsonObjSnippet.getString("title"));
//map.put("description", jsonObjSnippet.getString("description"));
// map.put("flag", jsonobject.getString("flag"));
JSONObject jsonObjThumbnail = jsonObjSnippet.getJSONObject("thumbnails");
String imgURL = jsonObjThumbnail.getJSONObject("high").getString("url");
map.put("url",imgURL);
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
spinner.setVisibility(View.GONE);
editsearch = (EditText) findViewById(R.id.search);
// Capture Text in EditText
editsearch.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#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) {
// TODO Auto-generated method stub
}
});
}
}
// Dialouge Box
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Handle the back button
if (keyCode == KeyEvent.KEYCODE_BACK) {
//Ask the user if they want to quit
new android.support.v7.app.AlertDialog.Builder (this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.quit)
.setMessage(R.string.really_quit)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Stop the activity
MainActivity.this.finish();
}
})
.setNeutralButton(R.string.neutral, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Rate This App", Toast.LENGTH_SHORT).show();
startActivity(new Intent("android.intent.action.VIEW", Uri.parse("https://play.google.com/store/apps/details?id=")));
}
})
.setNegativeButton(R.string.no, null)
.show();
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
and here is my list view adapter code.
// Declare Variables
MainActivity main;
private PublisherInterstitialAd mPublisherInterstitialAd;
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View view, ViewGroup parent) {
// Declare Variables
TextView country;
ImageView flag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
//rank = (TextView) itemView.findViewById(R.id.rank);
country = (TextView) itemView.findViewById(R.id.country);
// population = (TextView) itemView.findViewById(R.id.population);
// Locate the ImageView in listview_item.xml
flag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
// rank.setText(resultp.get(MainActivity.VIDEO_ID));
country.setText(resultp.get(MainActivity.TITLE));
// population.setText(resultp.get(MainActivity.DESCRIPTION));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.imgURL), flag);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, PlayerViewDemoActivity.class);
intent.putExtra("videoId", resultp.get(MainActivity.VIDEO_ID));
context.startActivity(intent);
mPublisherInterstitialAd.isLoaded();
mPublisherInterstitialAd.show();
requestNewInterstitial();
}
});
return itemView;
}
private void requestNewInterstitial() {
PublisherAdRequest adRequest = new PublisherAdRequest.Builder()
.addTestDevice("020AC93F90A14C29209AF3CA716FFBD4")
.build();
mPublisherInterstitialAd.loadAd(adRequest);
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
data.clear();
if (charText.length() == 0) {
data.add(resultp); // resultp is hashmap
} else {
if (resultp.get(MainActivity.TITLE).toLowerCase(Locale.getDefault())
.contains(charText)) {
data.add(resultp);
}
}
notifyDataSetChanged();
}
}
You should declare one more ArrayList name allData, it always store all objects.
ArrayList<HashMap<String, String>> allOriginalData; // always store all object
ArrayList<HashMap<String, String>> data; // use for store object that display in the ListView
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
allOriginalData = new ArrayList<HashMap<String, String>>(arraylist);
imageLoader = new ImageLoader(context);
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
data.clear();
if (charText.length() == 0) {
// search empty -> new data = all original data
data = new ArrayList<HashMap<String, String>>(allData);
} else {
// loop all original data
// check the condition and make the new data for display in ListView
for(int i = 0; i < allOriginalData.size(); i++){
HashMap<String, String> resultA = allOriginalData.get(i);
if (resultA.get(MainActivity.TITLE).toLowerCase(Locale.getDefault())
.contains(charText)) {
data.add(resultA);
}
}
}
notifyDataSetChanged();
}
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'm trying to use CheckBox in my ListView with an ArrayAdapter. When I select any CheckBox onlytime in the list, multiple entries are selected automatically in a random order. Can anyone please tell how I can avoid this.
Here's my code for your reference:
public class SearchListAdapterQ2 extends BaseAdapter {
int layoutId;
ArrayList<SearchListView> searchresultList = new ArrayList<SearchListView>();
public static int companyCpsId;
public static String companyCpsType = "", search_companyName = "",
search_countryName = "", handShakeStatus = "";
public static String handShakeCPSName = "";
public static boolean searchListAdapter_Q2 = false;
SharedPreferences sharedpreferences;
boolean markfavStatus = false;
ListView searchResults_listView;
Context context;
public SearchListAdapterQ2(Context context, int layoutId,
ArrayList<SearchListView> searchresultList,
ListView searchResults_listView) {
// TODO Auto-generated constructor stub
this.layoutId = layoutId;
this.searchresultList = searchresultList;
Log.i("inside searchListAdapter", "inside searchListAdapter");
this.context = context;
sharedpreferences = context.getSharedPreferences("MyPrefs",
Context.MODE_PRIVATE);
this.searchResults_listView = searchResults_listView;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
Log.i("searchresultList",
"searchresultList: " + searchresultList.size());
return searchresultList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return searchresultList.get(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) {
ViewHolder1 holder1;
// LayoutInflater inflater = (LayoutInflater)
// context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
char color;
String text = "";
String address = "";
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.qq_searchlist_repeat_items,
parent, false);
holder1 = new ViewHolder1();
holder1.companyName_textView = (TextView) convertView
.findViewById(R.id.companyName_textView);
holder1.companyLogo_textView = (TextView) convertView
.findViewById(R.id.companyLogo_textView);
holder1.companyAddress_textView = (TextView) convertView
.findViewById(R.id.companyAddress_textView);
holder1.handShakeIcon_imageView = (ImageView) convertView
.findViewById(R.id.handShakeIcon_imageView);
holder1.favouritesIcon_imageView = (ImageView) convertView
.findViewById(R.id.favouritesIcon_imageView);
holder1.referIcon_imageView = (ImageView) convertView
.findViewById(R.id.referIcon_imageView);
holder1.sendEnquiry_imageView = (ImageView) convertView
.findViewById(R.id.sendEnquiry_imageView);
holder1.icons_searchResultsPage_relLayout = (RelativeLayout) convertView
.findViewById(R.id.icons_searchResultsPage_relLayout);
holder1.chckbx1 = (CheckBox) convertView.findViewById(R.id.chckbx1);
if (SearchListActivity_Q2.broadcastMode) {
Log.i("icons_searchResultsPage_relLayout is visible",
"icons_searchResultsPage_relLayout is visible");
holder1.icons_searchResultsPage_relLayout
.setVisibility(View.GONE);
holder1.chckbx1.setVisibility(View.VISIBLE);
} else {
holder1.icons_searchResultsPage_relLayout
.setVisibility(View.VISIBLE);
holder1.chckbx1.setVisibility(View.GONE);
}
convertView.setTag(holder1);
} else {
holder1 = (ViewHolder1) convertView.getTag();
}
holder1.id = position;
search_companyName = searchresultList.get(position).getCpsName();
search_countryName = searchresultList.get(position).getCountryName();
try {
String ssearch_companyName = URLDecoder.decode(search_companyName,
"UTF-8");
holder1.companyName_textView.setText(ssearch_companyName);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (searchresultList.get(position).getCpsName().contains(" ")) {
String[] splitText = searchresultList.get(position).getCpsName()
.split("\\s+");
char a = splitText[0].charAt(0);
char b = splitText[1].charAt(0);
text = String.valueOf(a) + String.valueOf(b);
color = b;
} else {
text = searchresultList.get(position).getCpsName().substring(0, 1);
color = searchresultList.get(position).getCpsName().charAt(1);
}
holder1.companyLogo_textView.setText(text.toUpperCase());
if (searchresultList.get(position).getCpsAddress().isEmpty()) {
address = searchresultList.get(position).getCountryName();
} else {
if (searchresultList.get(position).getCpsAddress().length() > 1) {
address = searchresultList.get(position).getCpsAddress() + ", "
+ searchresultList.get(position).getCountryName();
} else {
address = searchresultList.get(position).getCountryName();
}
}
holder1.companyAddress_textView.setText(address);
holder1.companyName_textView
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
searchListAdapter_Q2 = true;
companyCpsId = searchresultList.get(position)
.getCpsId();
Log.i("$$$ companyCpsId", "companyCpsId" + companyCpsId);
companyCpsType = searchresultList.get(position)
.getCpsType();
Intent intent = new Intent(context,
CompanyProfile_Activity.class);
context.startActivity(intent);
}
});
holder1.referIcon_imageView
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
holder1.sendEnquiry_imageView
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<Q2_SendEnquiryList> sendEnquiry = new ArrayList<Q2_SendEnquiryList>();
sendEnquiry.add(new Q2_SendEnquiryList(searchresultList
.get(position).getCpsId(), searchresultList
.get(position).getCpsName()));
sendEnquiry.add(new Q2_SendEnquiryList(1, "abcdefgh"));
sendEnquiry.add(new Q2_SendEnquiryList(2, "abcdefg"));
sendEnquiry.add(new Q2_SendEnquiryList(3, "abcdef"));
sendEnquiry.add(new Q2_SendEnquiryList(4, "abcde"));
sendEnquiry.add(new Q2_SendEnquiryList(5, "abcd"));
sendEnquiry.add(new Q2_SendEnquiryList(6, "abc"));
sendEnquiry.add(new Q2_SendEnquiryList(7, "ab"));
Intent intent = new Intent(context,
Q2_SendEnquiryActivity.class);
intent.putParcelableArrayListExtra("sendEnquiry",
sendEnquiry);
context.startActivity(intent);
}
});
holder1.handShakeIcon_imageView
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
companyCpsId = searchresultList.get(position)
.getCpsId();
handShakeCPSName = searchresultList.get(position)
.getCpsName();
handShakeStatus = searchresultList.get(position)
.getHandShakeStatus();
ConstantVariables.handShakeFromAdapter = true;
if (sharedpreferences.getInt("userId_sp", 0) != 0) {
if (sharedpreferences.getInt("profileActiveStatus",
0) > 0) {
if (sharedpreferences.getInt("organizationId",
0) != 0) {
if (handShakeStatus.equalsIgnoreCase("d")) {
ConstantVariables
.handShakeRequest(
context,
companyCpsId,
0,
ConstantVariables.handShakeFromAdapter,
searchResults_listView,
position);
} else if (handShakeStatus
.equalsIgnoreCase("p")) {
ConstantVariables
.handShakeRequestAccept(
context,
companyCpsId,
1,
ConstantVariables.handShakeFromAdapter,
searchResults_listView,
position,
handShakeCPSName);
}
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
context);
// Setting Dialog Title
// alertDialog.setTitle("Please Add Company");
// Setting Dialog Message
alertDialog
.setMessage("Please add your company details");
// Setting Positive "Yes" Button
alertDialog
.setPositiveButton(
"Add",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
Intent intent = new Intent(
context,
Profile_Activity.class);
context.startActivity(intent);
}
});
// Setting Negative "NO" Button
alertDialog
.setNegativeButton(
"Later",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
} else {
ConstantVariables
.requestEmailVerification(context);
}
} else {
ConstantVariables.requestLogin(context);
}
}
});
holder1.favouritesIcon_imageView
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return convertView;
}
static class ViewHolder1 {
TextView companyName_textView, companyAddress_textView,
companyLogo_textView;
ImageView handShakeIcon_imageView, favouritesIcon_imageView,
referIcon_imageView, sendEnquiry_imageView;
CheckBox chckbx1;
int id;
RelativeLayout icons_searchResultsPage_relLayout;
}
}
in your adapter getView() method set the status of the clicked checkbox in model and call notify data set changed, try that
I added the following lines with my code and it started working fine:
ArrayList<Integer> checkedPositions = new ArrayList<Integer>();
final Integer index = new Integer(position);
holder1.chckbx1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
// if checked, we add it to the list
checkedPositions.add(index);
} else if (checkedPositions.contains(index)) {
// else if remove it from the list (if it is present)
checkedPositions.remove(index);
}
}
});
// set the state of the checbox based on if it is checked or not.
holder1.chckbx1.setChecked(checkedPositions.contains(index));
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 facing problem in listview i am getting data from server and after parsing this data i am using custom adpater for showing the data in listview.I want to update the listview item each after 3 seconds and add new data to list.how can it possible.
i am using adapter.notifyDataSetChanged() method but my listview is not updating it is showing the old data that i gets first time.how to show new data in listview that i got each after 3 seconds.i am using the update method like this.
private Handler handler = new Handler();
private Runnable updater = new Runnable() {
public void run() {
/*
* Update the list
*/
//list.clearTextFilter();
getVisitorDetailFromServer();
list.invalidateViews();
adapter.notifyDataSetChanged();
try {
Log.i("UPDATE", "Handler called");
// searchAdapter = getFeed(URL);
adapter.notifyDataSetChanged();
handler.postDelayed(this, 3000);
} catch(Exception e) {
Log.e("UPDATE ERROR", e.getMessage());
}
}
};
Using getVisitorDetailFromServer() i am getting the data.
adapter class code is
private class CustomAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public CustomAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public void setContext(Context context) {
// TODO Auto-generated method stub
//caching. notifyDataSetChanged();
}
public int getCount() {
return sizeoflist;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row1, null);
holder = new ViewHolder();
holder.IP = (TextView) convertView.findViewById(R.id.ip);
holder.duration = (TextView) convertView.findViewById(R.id.duration);
holder.status =(TextView) convertView.findViewById(R.id.status);
holder.noOfVisit = (TextView) convertView.findViewById(R.id.NoOfvisit);
holder.invite =(Button)convertView.findViewById(R.id.btnjoin);
holder.deny = (Button) convertView.findViewById(R.id.btndeny);
holder.deny.setVisibility(View.INVISIBLE);
holder.invite.setId(position);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
String result = response;
String delimiter = "<fld>";
String delimiter1 = "<ln>";
String delimiter2 = "<blk>";
String delimiter3 = "<fld><fld><blk>";
operatorDetail = result.split(delimiter1);
String[] operatorlist = result.split(delimiter3);
noofvisitors = operatorlist[1].split(delimiter2);
System.out.println("no of visitor================"+noofvisitors[0]);
for(int i=0;i<operatorDetail.length;i++){
operatorList = operatorDetail[i].split(delimiter);
operatorlist = result.split(delimiter2);
SessionText.add(operatorList[0]);
IPText.add(operatorList[1]);
DurationText.add(operatorList[4]);
StatusText.add(operatorList[3]);
NoOfVisit.add(operatorList[2]);
ButtonText.add(operatorList[6]);
iptext = IPText.get(i) ;
sessionid = SessionText.get(i);
//System.out.println("session value is"+SessionText.get(position));
//System.out.println("ip values are"+IPText.get(position));
//System.out.println("duration values are"+DurationText.get(position));
//System.out.println("status values are"+StatusText.get(position));
//System.out.println("no of visit"+NoOfVisit.get(position));
if(StatusText.get(position).equalsIgnoreCase("chat request")){
holder.deny.setVisibility(View.VISIBLE);
holder.invite.setText("Accept");
holder.invite.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
holder.invite.setText("Join");
holder.deny.setVisibility(View.INVISIBLE);
}
});
}
else{
holder.invite.setText("Invite");
holder.deny.setVisibility(View.INVISIBLE);
}
if(holder.invite.getText().equals("Join")){
holder.invite.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
chatRequest(iptext,sessionid);
}
});
}
holder.IP.setText(IPText.get(position));
holder.duration.setText(DurationText.get(position));
holder.status.setText(StatusText.get(position));
holder.noOfVisit.setText(NoOfVisit.get(position));
//---------------------When user click on invite Button---------------------
holder.invite.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
callToServer(SessionText.get(position));
}
});
//-----------------------------When user click on deny button------------------------
holder.deny.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
refuseToServer(sessionid);
holder.deny.setVisibility(View.INVISIBLE);
}
});
}
System.out.println("no of visitor================"+noofvisitors[0]);
convertView.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
Intent i=new Intent(Visitors.this,VisitorDetail.class);
i.putExtra("ID", id);
i.putExtra("Position",position);
i.putExtra("From", from);
i.putExtra("SessionText", SessionText.get(position));
i.putExtra("IPTEXT",IPText.get(position));
startActivity(i);
}});
//startService();
return convertView;
}
class ViewHolder {
TextView IP;
TextView duration;
Button deny;
TextView status;
TextView noOfVisit;
Button invite;
}
}
my class code is
public class Visitors extends Activity {
private ListView list;
private final int NOTIFICATION_ID = 1010;
private Timer timer = new Timer();
private String response,response1;
protected Dialog m_ProgressDialog;
String[] operatorList,operatorDetail,operatordetail,tempoperatordata;
String[] noofvisitors,opt;
private static final String DEB_TAG = "Error Message";
public static ArrayList<String> SessionText,IPText,DurationText;
private ArrayList<String> StatusText,NoOfVisit,ButtonText;
private int sizeoflist;
private String IP;
Context context;
public static String from,sessionid,id,text,iptext,status;
private int position,noofchat;
private boolean IsSoundEnable,IsChatOnly;
private Button logout;
private CustomAdapter adapter;
NotificationManager notificationManager;
final HashMap<String, String> postParameters = new HashMap<String, String>();
private String url;
private Handler handler = new Handler();
private Runnable updater = new Runnable() {
public void run() {
/*
* Update the list
*/
//list.clearTextFilter();
getVisitorDetailFromServer();
list.invalidateViews();
adapter.notifyDataSetChanged();
try {
adapter.notifyDataSetChanged();
handler.postDelayed(this, 3000);
} catch(Exception e) {
Log.e("UPDATE ERROR", e.getMessage());
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.visitor);
list = (ListView) findViewById(R.id.list01);
logout = (Button) findViewById(R.id.btnlogout);
adapter = new CustomAdapter(Visitors.this);
updater.run();
//-----------------Making the object of arrayList----------------
SessionText = new ArrayList<String>();
IPText = new ArrayList<String>();
DurationText = new ArrayList<String>();
StatusText = new ArrayList<String>();
NoOfVisit = new ArrayList<String>();
ButtonText = new ArrayList<String>();
Bundle extras = getIntent().getExtras();
if (extras != null) {
IsSoundEnable = Controls.IsSoundEnable;
IsChatOnly = Controls.IsChatOnly;
IsSoundEnable = extras.getBoolean("IsSoundOnly", Controls.IsSoundEnable);
IsChatOnly= extras.getBoolean("IsCOnlyhat", Controls.IsChatOnly);
extras.getString("From");
position=extras.getInt("Position");
}
}
#Override
protected void onStart() {
super.onStart();
//------------Getting the visitor detail-------------------------
getVisitorDetailFromServer();
//---------------When user click on logout button-----------------------------------
logout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
logoutFromServer();
}
});
}
//----------------------------Getting the detail from server of monitoring window-------------------------
private void getVisitorDetailFromServer() {
// TODO Auto-generated method stub
if(IsChatOnly){
url = "http://sa.live2support.com/cpn/wz1-allonlineu.php?";
postParameters.put("adminid",Main.loginId.getText().toString());
postParameters.put("sid",Main.siteId.getText().toString());
postParameters.put("nvar","Y");
postParameters.put("conly", "Y");
}
else{
url = "http://sa.live2support.com/cpn/wz1-allonlineu.php?";
postParameters.put("adminid",Main.loginId.getText().toString());
postParameters.put("sid",Main.siteId.getText().toString());
postParameters.put("nvar","Y");
postParameters.put("conly", "N");
}
Runnable searchThread = new Runnable(){
public void run() {
// TODO Auto-generated method stub
try {
response = CustomHttpClient.executeHttpPost1(url,postParameters);
Log.i(DEB_TAG, "Requesting to server"+response);
//CustomHttpClient.getResponseInString(response );
System.out.println("Output of httpResponse:"+response);
String result = response;
String delimiter1 = "<ln>";
String delimiter = "<fld>";
operatorDetail = result.split(delimiter1);
for(int i=0;i<operatorDetail.length;i++){
operatorList = operatorDetail[i].split(delimiter);
SessionText.add(operatorList[0]);
IPText.add(operatorList[1]);
DurationText.add(operatorList[4]);
StatusText.add(operatorList[3]);
NoOfVisit.add(operatorList[2]);
ButtonText.add(operatorList[6]);
}
//--------Getting the size of the list---------------------
sizeoflist = operatorDetail.length;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(response!=null){
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
playsound3();
noofchat =0;
System.out.println(response);
list.setAdapter(adapter);
list.getDrawingCache(false);
list.invalidateViews();
list.setCacheColorHint(Color.TRANSPARENT);
list.requestFocus(0);
list.setSelected(false);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = ((TextView)view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
}
});
if(IsChatOnly==false){
TimerTask timerTask = new TimerTask()
{
#Override
public void run()
{
//triggerNotification();
//playsound();
}
};
timer.schedule(timerTask, 3000);
}
else{
playsound();
}
}
});
}
else {
ShowAlert();
}
}
};
Thread thread = new Thread(null, searchThread, "MagentoBackground");
thread.start();
}
//--------------------When internet connection is failed show alert
private void ShowAlert() {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final AlertDialog alert = builder.create();
alert.setTitle("Live2Support");
alert.setMessage("Internet Connection failed");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//startActivity(new Intent(CreateAccount.this,CreateAccount.class));
alert.dismiss();
}
});
alert.show();
}
//--------------------Play sound when notification occurs-------------------
private void playsound() {
// TODO Auto-generated method stub
MediaPlayer mp = MediaPlayer.create(this, R.raw.newvisitsound);
mp.start();
}
Simple calling adapter.notifyDataSetChanged() will not work unless you actually update the dataset 'within the adapter class'.
I suspect you are not passing the updated information into your Adapter class. Check to see if the datastructure referenced by your Adapter's getCount() method is the same as the one being updated by the getVisitorDetailFromServer() server.
If that is not the problem, you'll need to post more code.
I was having the same problem. I cleared the list before adding the new data and it resolved