正在开发一个需要多个联系人选择器和搜索选项的应用程序。
我试过http://sachindotg.blogspot.in/2013/11/android-simple-multi-contacts-picker.html 教程,但它无法正常工作。
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();
}
}
从上面的代码我可以使用复选框从列表中选择联系人,但现在我也想添加搜索功能。我添加了编辑文本,并且在更改的文本上我能够获得已排序的联系人但以前选择的联系人每次都消失了。所以如何保持选定的联系人保持选中状态。