I have read and tried to follow some other threads from stackoverflow and I am not understanding how to get this to work.
Brief description. I have an activity that loads the contact list into a custom list view. I can select the contacts using a check box. I also have a done button and a cancel button. When the done button is selected it will take all the check box items and display the contacts in a new activity with its own custom list view.
My issue is how to set up my button click to display just the selected contacts.
here is my done button code very rough:
private Button mDoneButton, mCancelButton;
ListView guestListView;
ProgressDialog guestProgressDialog;
ArrayList<String> guestAA = new ArrayList<String>();
ArrayList<String> guestNum = new ArrayList<String>();
//ArrayList<String> guestEmail = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts);
guestListView = (ListView) findViewById(R.id.ListView);
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
guestProgressDialog = ProgressDialog.show(contactDisplayActivity.this, "Loading...", "Please Wait", true, false);
} //end of on PreExecute method
#Override
protected Void doInBackground(Void... params) {
getGuestContacts();
return null;
} //end of doInBackground method
#Override
protected void onPostExecute(Void result) {
//getGuestContacts();
guestProgressDialog.dismiss();
CustomAdapter guestCustomAdapter = new CustomAdapter(contactDisplayActivity.this);
guestListView.setAdapter(guestCustomAdapter);
} //end of onPostExecute Method
} .execute((Void[]) null);
//Done Button
mDoneButton = (Button)findViewById(R.id.doneButton);
mDoneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
long [] guestIds = guestListView.getCheckedItemIds();
for (long guestId : guestIds ) {
getGuestContacts();
}
Intent myIntent = new Intent(contactDisplayActivity.this, GuestList.class);
startActivity(myIntent);
}
});
//Cancel Button
mCancelButton = (Button)findViewById(R.id.cancelButton);
mCancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//mListener.onFragmentInteraction();
//((PlanMeMainActivity) getActivity()).newActivityToLaunch(1);
Intent myIntent = new Intent(contactDisplayActivity.this, EventDetails.class);
startActivity(myIntent);
}
});
}
private void getGuestContacts() {
ContentResolver guestContactResolver = getContentResolver();
Cursor guestCursor = guestContactResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (guestCursor.getCount() > 0) {
while (guestCursor.moveToNext()) {
String guestId = guestCursor.getString(guestCursor.getColumnIndex(ContactsContract.Contacts._ID));
String guestName = guestCursor.getString(guestCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
//String guestEmail = guestCursor.getString(guestCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS));
guestAA.add(guestName);
if (Integer.parseInt(guestCursor.getString(guestCursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor phoneCursor = guestContactResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{guestId}, null);
while (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
guestNum.add(phoneNumber);
}
//while (phoneCursor.moveToNext()) {
// String email = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS));
//guestEmail.add(email);
//}
phoneCursor.close();
}
}
}
}
public class CustomAdapter extends BaseAdapter {
private Context mContext;
public CustomAdapter(Context context) {
mContext = context;
}
public int getCount() {
return guestNum.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
final int pos = position;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.contacts_display, null);
holder.textviewName = (TextView) convertView.findViewById(R.id.contactsTextView1);
holder.textviewNumber = (TextView) convertView.findViewById(R.id.contactsTextView2);
//holder.textViewEmail = (TextView) convertView.findViewById(R.id.contactsTextView3);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.contactsCheckBox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.checkbox.setId(position);
holder.textviewName.setId(position);
holder.textviewNumber.setId(position);
//holder.textViewEmail.setId(position);
holder.textviewName.setText(guestAA.get(position));
holder.textviewNumber.setText("No. " + guestNum.get(position));
//holder.textViewEmail.setText(guestEmail.get(position));
holder.id = position;
return convertView;
}
}
static class ViewHolder {
TextView textviewName;
TextView textviewNumber;
//TextView textViewEmail;
CheckBox checkbox;
int id;
}
}
the getGuestContacts method displays the contact list.
Any help or direction would be great. Thanks.
Related
I am deleting the title 2 list item item
But the last title gets deleted that is the title 8 gets deleted
When I then go back to the previous screen and reopen the list. The correct that is the 2nd item title 2 had been deleted.
Here is the DataAdapter
public class DataAdapter extends BaseAdapter {
String a[];
Context ctx;
View.OnClickListener onClickListener;
MyDBHandler dbHelper;
AlertDialog alertDialog;
ArrayList<Calendars> arrayList;
public DataAdapter(Context reminderList, ArrayList<Calendars> arrayList, MyDBHandler dbHelper) {
this.ctx = reminderList;
this.arrayList = arrayList;
this.dbHelper = dbHelper;
}
public void Swap(ArrayList<Calendars> arrayList) {
this.arrayList.clear();
this.arrayList.addAll(arrayList);
this.notifyDataSetChanged();
Log.e("arraylist", arrayList.toString());
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflate = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflate.inflate(R.layout.activity_view_record, parent, false);
final ViewHolder holder = new ViewHolder();
holder.dateTextView = (TextView) convertView.findViewById(R.id.datelist);
holder.timeTextView = (TextView) convertView.findViewById(R.id.timelist);
holder.titleTextView = (TextView) convertView.findViewById(R.id.titlelist);
holder.idTextview = (TextView) convertView.findViewById(R.id.idlist);
holder.deleteButton = (Button) convertView.findViewById(R.id.deletelist);
holder.dateTextView.setText(arrayList.get(position).get_reminderdate());
holder.timeTextView.setText(arrayList.get(position).get_remindertime());
holder.titleTextView.setText(arrayList.get(position).get_remindertitle());
holder.idTextview.setText(arrayList.get(position).get_id() + "");
holder.deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder adb = new AlertDialog.Builder(v.getRootView().getContext());
adb.setTitle("Delete");
adb.setMessage("Are you sure you want to delete this reminder?");
//final int positionToRemove = view.getId();
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dbHelper.remove(arrayList.get(position).get_id());
Log.e("position", position + "");
arrayList.remove(position);
arrayList = dbHelper.databaseToArrayList();
notifyDataSetInvalidated();
notifyDataSetChanged();
//Swap(dbHelper.databaseToArrayList());
}
});
adb.show();
}
});
}
return convertView;
}
class ViewHolder {
TextView titleTextView, dateTextView, timeTextView, idTextview;
Button deleteButton;
}
}
Here is the ListActivity
public class ReminderList extends ActionBarActivity {
Calendars calendars;
Button deleteButton;
private MyDBHandler dbHelper;
private ListView listView;
private ArrayList<Calendars> arrayList;
private SimpleCursorAdapter adapter;
int pos;
DataAdapter dataAdapter;
final String[] from = new String[]{MyDBHandler.COLUMN_REMINDER_TITLE,
MyDBHandler.COLUMN_REMINDER_DATE, MyDBHandler.COLUMN_REMINDER_TIME, MyDBHandler.COLUMN_ID,
MyDBHandler.COLUMN_REMINDER_DESCRIPTION, MyDBHandler.COLUMN_REMINDER_SNOOZE, MyDBHandler.COLUMN_REMINDER_REPEAT, MyDBHandler.COLUMN_ID};
final int[] to = new int[]{R.id.titlelist, R.id.datelist, R.id.timelist, R.id.idlist,
R.id.descriptionlist, R.id.snoozelist, R.id.repeatlist, R.id.deletelist};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reminder_list);
deleteButton = (Button) findViewById(R.id.deletelist);
// adapter=new DataAdapter(ReminderList.this,from);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onStart() {
arrayList = new ArrayList<Calendars>();
dbHelper = new MyDBHandler(this);
Cursor cursor = dbHelper.fetch();
arrayList = dbHelper.databaseToArrayList();
listView = (ListView) findViewById(R.id.list_view);
listView.setEmptyView(findViewById(R.id.empty));
dataAdapter = new DataAdapter(this, arrayList, dbHelper);
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long viewId) {
String title = arrayList.get(position).get_remindertitle();
Log.d("title", title);
String date = arrayList.get(position).get_reminderdate();
String time = arrayList.get(position).get_remindertime();
String id = arrayList.get(position).get_id() + "";
String description = arrayList.get(position).get_reminderdescription();
String snooze = arrayList.get(position).get_remindersnooze();
String repeat = arrayList.get(position).get_reminderrepeat();
Intent modify_intent = new Intent(getApplicationContext(), AlarmActivity.class);
modify_intent.putExtra("id", id);
modify_intent.putExtra("title", title);
modify_intent.putExtra("time", time);
modify_intent.putExtra("date", date);
modify_intent.putExtra("description", description);
modify_intent.putExtra("snooze", snooze);
modify_intent.putExtra("repeat", repeat);
startActivity(modify_intent);
dataAdapter.notifyDataSetChanged();
listView.invalidateViews();
}
});
super.onStart();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
NavUtils.navigateUpFromSameTask(this);
return true;
}
case R.id.add_record: {
Intent add_mem = new Intent(this, AlarmActivity.class);
startActivity(add_mem);
}
default:
return super.onOptionsItemSelected(item);
}
}
}
DatabasetoArraylist function
public ArrayList<Calendars> databaseToArrayList() {
ArrayList<Calendars> arrayList = new ArrayList();
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_REMINDER;
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex("_reminderdate")) != null) {
Calendars calendars = new Calendars();
calendars.set_id(c.getInt(c.getColumnIndex(COLUMN_ID)));
calendars.set_reminderdate(c.getString(c.getColumnIndex(COLUMN_REMINDER_DATE)));
calendars.set_remindertime(c.getString(c.getColumnIndex(COLUMN_REMINDER_TIME)));
calendars.set_remindertitle(c.getString(c.getColumnIndex(COLUMN_REMINDER_TITLE)));
calendars.set_reminderdescription(c.getString(c.getColumnIndex(COLUMN_REMINDER_DESCRIPTION)));
calendars.set_reminderrepeat(c.getString(c.getColumnIndex(COLUMN_REMINDER_REPEAT)));
calendars.set_remindersnooze(c.getString(c.getColumnIndex(COLUMN_REMINDER_SNOOZE)));
arrayList.add(calendars);
}
c.moveToNext();
}
c.close();
db.close();
return arrayList;
}
Change your getView() method of adapter by below code:
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
final Calendars calendars = arrayList.get(position);
if (convertView == null)
{
LayoutInflater inflate = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflate.inflate(R.layout.activity_view_record, parent, false);
holder = new ViewHolder();
holder.dateTextView = (TextView) convertView.findViewById(R.id.datelist);
holder.timeTextView = (TextView) convertView.findViewById(R.id.timelist);
holder.titleTextView = (TextView) convertView.findViewById(R.id.titlelist);
holder.idTextview = (TextView) convertView.findViewById(R.id.idlist);
holder.deleteButton = (Button) convertView.findViewById(R.id.deletelist);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.dateTextView.setText(calendars.get_reminderdate());
holder.timeTextView.setText(calendars.get_remindertime());
holder.titleTextView.setText(calendars.get_remindertitle());
holder.idTextview.setText(calendars.get_id() + "");
holder.deleteButton.setTag(calendars);
holder.deleteButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
AlertDialog.Builder adb = new AlertDialog.Builder(v.getRootView().getContext());
adb.setTitle("Delete");
adb.setMessage("Are you sure you want to delete this reminder?");
//final int positionToRemove = view.getId();
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
final selectedCalendar = (Calendars) holder.deleteButton.getTag();
dbHelper.remove(selectedCalendar.get_id());
arrayList = dbHelper.databaseToArrayList();
notifyDataSetInvalidated();
notifyDataSetChanged();
//Swap(dbHelper.databaseToArrayList());
}
});
adb.show();
}
});
}
return convertView;
}
I have a list view populated threw an SQlitedatabase but I need to pass to a detail activity from the list view. The problem is in passing the details from the listview activity to the detail activity because when I click the detail activity it gives me blank edit texts
Here is my listview activity:
public class consulter_note extends Activity implements AdapterView.OnItemClickListener{
ListView list;
SQLiteDatabase sqLiteDatabase;
DataBaseOperationstwo dataBaseOperationstwo;
Cursor cursor;
ListDataAdapter listDataAdapter;
String titre,objet;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_consulter_note);
list = (ListView) findViewById(R.id.listView);
listDataAdapter = new ListDataAdapter(getApplicationContext(),R.layout.notelist_row);
list.setAdapter(listDataAdapter);
list.setOnItemClickListener(this);
dataBaseOperationstwo = new DataBaseOperationstwo(getApplicationContext());
sqLiteDatabase = dataBaseOperationstwo.getReadableDatabase();
cursor = dataBaseOperationstwo.getInformations(sqLiteDatabase);
if (cursor.moveToFirst())
{
do
{
titre = cursor.getString(0);
objet = cursor.getString(1);
DataProvider dataProvider = new DataProvider(titre,objet);
listDataAdapter.add(dataProvider);
}while (cursor.moveToNext());
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(this, note_details.class);
startActivity(intent);
intent.putExtra("titre", titre);
intent.putExtra("objet", objet);
}
}
And here is my array adapter:
public class ListDataAdapter extends ArrayAdapter{
List list = new ArrayList();
public ListDataAdapter(Context context, int resource) {
super(context, resource);
}
static class LayoutHandler
{
TextView TITRE,OBJET;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.notelist_row,parent,false);
layoutHandler = new LayoutHandler();
layoutHandler.TITRE = (TextView) row.findViewById(R.id.titredemo);
layoutHandler.OBJET = (TextView) row.findViewById(R.id.objetdemo);
row.setTag(layoutHandler);
}
else
{
layoutHandler = (LayoutHandler) row.getTag();
}
DataProvider dataProvider = (DataProvider) this.getItem(position);
layoutHandler.TITRE.setText(dataProvider.getTitre());
layoutHandler.OBJET.setText(dataProvider.getObjet());
return row;
}
}
The data provider class used in the array adapter:
public class DataProvider {
private String titre,objet;
public DataProvider(String titre,String objet)
{
this.titre = titre;
this.objet = objet;
}
public String getTitre() {
return titre;
}
public void setTitre(String titre) {
this.titre = titre;
}
public String getObjet() {
return objet;
}
public void setObjet(String objet) {
this.objet = objet;
}
}
And finally my details activity. I'm only interested in the intent part; the rest has nothing to do with my problem:
public class note_details extends Activity {
ImageButton Del;
EditText PASSTITRE,USEROBJET;
String Passtitre,Userobjet;
DataBaseOperationstwo DOP;
Context CTX = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent =getIntent();
if(intent != null)
{
String objet = intent.getStringExtra("objet");
String titre= intent.getStringExtra("titre");
PASSTITRE.setText(objet);
USEROBJET.setText(objet);
}
setContentView(R.layout.activity_note_details);
Del = (ImageButton) findViewById(R.id.suppnote);
PASSTITRE = (EditText) findViewById(R.id.titree);
USEROBJET = (EditText) findViewById(R.id.objett);
Del.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Passtitre = PASSTITRE.getText().toString();
Userobjet = USEROBJET.getText().toString();
DOP = new DataBaseOperationstwo(CTX);
DOP.deleteNote(DOP,Passtitre,Userobjet);
Toast.makeText(getBaseContext(),"note supprimé",Toast.LENGTH_LONG).show();
finish();
}
});
}
public void liste(View v)
{
Intent i = new Intent(this, consulter_note.class);
startActivity(i);
}
public void supprimer(View v)
{
}
}
My logcat doesn’t show any errors but the details activity shows with empty edittexts.
You should first add extras to the Intent and then fire it:
Intent intent = new Intent(this, note_details.class);
intent.putExtra("titre", titre);
intent.putExtra("objet", objet);
startActivity(intent);
Another thing worth mentioning is that you should avoid doing DB queries on the main thread, as it will slow down your app. Use Loaders, or just run queries on worker threads.
im new to android and java programming. Im having trouble getting my custom layout (currently with only one textview in it to work with my code. I have followed many tutorials and look and many examples but still Im getting confused as to how I would integrate it with my existing code.
Any help would be appreciated.
Here is my code:
public class checkListActivity extends MainActivity {
static String filename = "checkList";
String currentList;
SharedPreferences checkListData;
SharedPreferences.Editor checkListEditor;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.checklist);
Button bAddItem = (Button) findViewById(R.id.bAddItem);
final EditText etItemName = (EditText) findViewById(R.id.etItemName);
final TextView tvTitle = (TextView) findViewById(R.id.tvTitle);
final ListView lvCheckList = (ListView) findViewById(R.id.lvCheckLists);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String selectedItem = extras.getString("selectedItem");
// get the value based on the key
currentList = selectedItem;
}
tvTitle.setText(currentList);
checkListData = getSharedPreferences(filename, 0);
updateListView();
// Button Click Listener
bAddItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String checkListStringData = etItemName.getText().toString();
checkListData = getSharedPreferences(filename, 0);
SharedPreferences.Editor checkListEditor = checkListData.edit();
checkListEditor.putString(currentList + "ItemName",
checkListStringData);
checkListEditor.commit();
String checkListDataReturned = checkListData.getString(
currentList + "ItemName", currentList);
tvTitle.setText(checkListDataReturned);
updateListView();
etItemName.setText("");
};
});
}
private void updateListView() {
final ListView lvCheckList = (ListView) findViewById(R.id.lvCheckList);
Map<String, ?> keys = checkListData.getAll();
ArrayList<String> checkListStrings = new ArrayList<String>();
for (Map.Entry<String, ?> entry : keys.entrySet()) {
if (entry.getValue() instanceof String) {
if (entry.getKey().equals(currentList + "ItemName")) {
checkListStrings.add((String) entry.getValue());
}
}
ArrayAdapter<String> checkListArrayAdapter = new ArrayAdapter<String>(
this, R.layout.single_listview_item);
lvCheckList.setAdapter(checkListArrayAdapter);
}
}
}
first create this custom adapter class...
private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public Context con;
public String[] sms;
public EfficientAdapter(Context context,String[] rssFeed) {
mInflater = LayoutInflater.from(context);
this.con=context;
this.sms=rssFeed;
}
public int getCount() {
return sms.length;
}
public Object getItem(int position) {
return sms[position];
}
public long getItemId(int position) {
return position;
}
#SuppressLint({ "SdCardPath", "InflateParams", "ResourceAsColor" })
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list, null);
holder = new ViewHolder();
holder.text2 = (TextView) convertView.findViewById(R.id.text_list_f);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text2.setText(sms[position]);
}
return convertView;
}
}
static class ViewHolder {
TextView text2;
}
then use it in your activity ...
list.setAdapter(new EfficientAdapter(this, your array));
I had tried to to put checkbox in listview through layout inflator and I got success but the problem is when I select the multiple contacts there is no problem but when I deselect it & when I scroll down & then go back to that deselected checkbox its get automatically selected...
public class Contactlist_selfActivity extends ListActivity {
/** Called when the activity is first created. */
private ArrayList<contact> contact_list = null;
private ProgressDialog mProgressDialog = null;
private contactAdapter mContactAdapter = null;
private Runnable mViewcontacts = null;
private SparseBooleanArray mSelectedContacts = new SparseBooleanArray();
private ArrayList<contact> items;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
contact_list = new ArrayList<contact>();
this.mContactAdapter = new contactAdapter(this, R.layout.listview,
contact_list);
ListView lv = getListView();
setListAdapter(this.mContactAdapter);
lv.setItemsCanFocus(false);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
// }
mViewcontacts = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
getContacts();
}
};
Thread thread = new Thread(null, mViewcontacts, "ContactReadBackground");
thread.start();
mProgressDialog = ProgressDialog.show(Contactlist_selfActivity.this,
"Please Wait...", "Retriving Contacts...", true);
}
#SuppressWarnings("unused")
private void getContacts() {
// TODO Auto-generated method stub
try {
String[] projection = new String[] {
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
ContactsContract.Contacts._ID };
Cursor mCursor = managedQuery(
ContactsContract.Contacts.CONTENT_URI, projection,
ContactsContract.Contacts.HAS_PHONE_NUMBER + "=?",
new String[] { "1" },
ContactsContract.Contacts.DISPLAY_NAME);
while (mCursor.moveToNext()) {
contact contact = new contact();
String contactId = mCursor.getString(mCursor
.getColumnIndex(ContactsContract.Contacts._ID));
contact.setContactName(mCursor.getString(mCursor
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
contact_list.add(contact);
}
mCursor.close();
runOnUiThread(returnRes);
} catch (Exception e) {
// TODO: handle exception
Log.d("getContacts", e.getMessage());
}
}
public class contactAdapter extends ArrayAdapter<contact> {
private int[] isChecked;
public contactAdapter(Context context, int textViewResourceId,
ArrayList<contact> items1) {
super(context, textViewResourceId, items1);
items = items1;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
final int position_clicked = 0;
// Log.i("asd", "getView :" + getItem(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.listview, parent, false);
}
contact contacts = items.get(position);
isChecked = new int[items.size()];
if (contacts != null) {
final CheckBox nameCheckBox = (CheckBox) convertView
.findViewById(R.id.checkBox);
nameCheckBox.setChecked(mSelectedContacts.get(position));
for (int i = 0; i < isChecked.length; i++) {
}
if (nameCheckBox != null) {
nameCheckBox.setText(contacts.getContactName());
}
nameCheckBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
isChecked[position_clicked] = position;
Log.d("position", String.valueOf(position));
}
});
}
return convertView;
}
}
private Runnable returnRes = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
mContactAdapter.notifyDataSetChanged();
}
};
}
i found the answer....
i had just taken a new variable in contact class...
public class PlanetsActivity extends Activity {
private ListView mainListView;
private Contact[] contact_read;
private Cursor mCursor;
private ArrayAdapter<Contact> listAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Find the ListView resource.
mainListView = (ListView) findViewById(R.id.mainListView);
mainListView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View item,
int position, long id) {
Contact planet = listAdapter.getItem(position);
planet.toggleChecked();
ContactViewHolder viewHolder = (ContactViewHolder) item
.getTag();
viewHolder.getCheckBox().setChecked(planet.isChecked());
}
});
// Throw Query and fetch the contacts.
String[] projection = new String[] { Contacts.HAS_PHONE_NUMBER,
Contacts._ID, Contacts.DISPLAY_NAME };
mCursor = managedQuery(Contacts.CONTENT_URI, projection,
Contacts.HAS_PHONE_NUMBER + "=?", new String[] { "1" },
Contacts.DISPLAY_NAME);
if (mCursor != null) {
mCursor.moveToFirst();
contact_read = new Contact[mCursor.getCount()];
// Add Contacts to the Array
int j = 0;
do {
contact_read[j] = new Contact(mCursor.getString(mCursor
.getColumnIndex(Contacts.DISPLAY_NAME)));
j++;
} while (mCursor.moveToNext());
} else {
System.out.println("Cursor is NULL");
}
// Add Contact Class to the Arraylist
ArrayList<Contact> planetList = new ArrayList<Contact>();
planetList.addAll(Arrays.asList(contact_read));
// Set our custom array adapter as the ListView's adapter.
listAdapter = new ContactArrayAdapter(this, planetList);
mainListView.setAdapter(listAdapter);
}
/** Holds Contact data. */
#SuppressWarnings("unused")
private static class Contact {
private String name = "";
private boolean checked = false;
public Contact() {
}
public Contact(String name) {
this.name = name;
}
public Contact(String name, boolean checked) {
this.name = name;
this.checked = checked;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public String toString() {
return name;
}
public void toggleChecked() {
checked = !checked;
}
}
/** Holds child views for one row. */
#SuppressWarnings("unused")
private static class ContactViewHolder {
private CheckBox checkBox;
private TextView textView;
public ContactViewHolder() {
}
public ContactViewHolder(TextView textView, CheckBox checkBox) {
this.checkBox = checkBox;
this.textView = textView;
}
public CheckBox getCheckBox() {
return checkBox;
}
public void setCheckBox(CheckBox checkBox) {
this.checkBox = checkBox;
}
public TextView getTextView() {
return textView;
}
public void setTextView(TextView textView) {
this.textView = textView;
}
}
/** Custom adapter for displaying an array of Contact objects. */
private static class ContactArrayAdapter extends ArrayAdapter<Contact> {
private LayoutInflater inflater;
public ContactArrayAdapter(Context context, List<Contact> planetList) {
super(context, R.layout.simplerow, R.id.rowTextView, planetList);
// Cache the LayoutInflate to avoid asking for a new one each time.
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Contact to display
Contact planet = (Contact) this.getItem(position);
System.out.println(String.valueOf(position));
// The child views in each row.
CheckBox checkBox;
TextView textView;
// Create a new row view
if (convertView == null) {
convertView = inflater.inflate(R.layout.simplerow, null);
// Find the child views.
textView = (TextView) convertView
.findViewById(R.id.rowTextView);
checkBox = (CheckBox) convertView.findViewById(R.id.CheckBox01);
// Optimization: Tag the row with it's child views, so we don't
// have to
// call findViewById() later when we reuse the row.
convertView.setTag(new ContactViewHolder(textView, checkBox));
// If CheckBox is toggled, update the Contact it is tagged with.
checkBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Contact contact = (Contact) cb.getTag();
contact.setChecked(cb.isChecked());
}
});
}
// Reuse existing row view
else {
// Because we use a ViewHolder, we avoid having to call
// findViewById().
ContactViewHolder viewHolder = (ContactViewHolder) convertView
.getTag();
checkBox = viewHolder.getCheckBox();
textView = viewHolder.getTextView();
}
// Tag the CheckBox with the Contact it is displaying, so that we
// can
// access the Contact in onClick() when the CheckBox is toggled.
checkBox.setTag(planet);
// Display Contact data
checkBox.setChecked(planet.isChecked());
textView.setText(planet.getName());
return convertView;
}
}
public Object onRetainNonConfigurationInstance() {
return contact_read;
}
}
The cause of this is that when you call nameCheckBox.setChecked() in code OnClickListener() awakes and run its code. I had the same problem an solved in just setting OnClickListener(null) before set a checkbox checked or not.
nameCheckBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
isChecked[position_clicked] = position;
Log.d("position", String.valueOf(position));
}
});
this code in add more one arre list in stores all position and add or remove both said
fast add ,second remove.
and used to list in position your other method
I've got a ListView with a 'show next results' button. The list is filled by a custom adapter extending BaseAdapter. Using it as shown below, only the new results are shown.
How can I append the new results to the list?
ListView listView = (ListView)findViewById(android.R.id.list);
// Show next results button
View footerView = ((LayoutInflater)ItemList.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_listview, null, false);
listView.addFooterView(footerView);
footerView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = getIntent();
i.putExtra("firstIndex", mFirstIndex + NRES_PER_PAGE);
i.putExtra("itemCount", NRES_PER_PAGE);
startActivity(i);
}
});
mItems = json.getJSONArray("data");
setListAdapter(new ItemAdapter(ItemList.this, mType, mItems));
FIX
ListActivity
public class ItemList extends MenuListActivity{
ItemAdapter mItemAdapter;
Integer mFirstIndex = 0;
JSONArray mItems = new JSONArray();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.item_list);
// Set data adapter
mItemAdapter = new ItemAdapter(ItemList.this, mType, mItems);
ListView listView = (ListView)findViewById(android.R.id.list);
View footerView = ((LayoutInflater)ItemList.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_listview, null, false);
listView.addFooterView(footerView);
footerView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
progressDialog = MyProgressDialog.show(ItemList.this, null, null);
mFirstIndex = mFirstIndex + ITEM_COUNT;
new GetItemInfoList().execute();
}
});
setListAdapter(mItemAdapter);
new GetItemInfoList().execute();
}
private class GetItemInfoList extends AsyncTask<Void, Void, JSONObject> {
protected JSONObject doInBackground(Void... params) {
// Set POST data to send to web service
List<NameValuePair> postData = new ArrayList<NameValuePair>(2);
postData.add(new BasicNameValuePair("firstindex", Integer.toString(mFirstIndex)));
postData.add(new BasicNameValuePair("itemscount", Integer.toString(ITEM_COUNT)));
JSONObject json = RestJsonClient.getJSONObject(URL_ITEMINFOLIST, postData);
return json;
}
protected void onPostExecute(JSONObject json) {
try {
// Get data from json object and set to list adapter
JSONArray jsonArray = json.getJSONArray("data");
for(int i=0; i<jsonArray.length(); i++)
mItems.put(jsonArray.get(i));
mItemAdapter.notifyDataSetChanged();
ListView listView = (ListView)findViewById(android.R.id.list);
View footerView = ((LayoutInflater)ItemList.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_listview, null, false);
listView.addFooterView(footerView);
footerView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
progressDialog = MyProgressDialog.show(ItemList.this, null, null);
mFirstIndex = mFirstIndex + ITEM_COUNT;
new GetItemInfoList().execute();
}
});
} catch (JSONException e) {
}
}
}
}
Adapter
public class ItemAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflater;
private JSONArray mItems;
private ImageLoader mImageLoader;
private int mCategory;
public ItemAdapter(Context context, int category, JSONArray items) {
mContext = context;
mInflater = LayoutInflater.from(context);
mItems = items;
mCategory = category;
this.mImageLoader = new ImageLoader(context, true);
}
public int getCount() {
return mItems.length();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item_row, null);
holder = new ViewHolder();
holder.listitem_pic = (ImageView) convertView.findViewById(R.id.listitem_pic);
holder.listitem_desc = (TextView) convertView.findViewById(R.id.listitem_desc);
holder.listitem_title = (TextView) convertView.findViewById(R.id.listitem_title);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
JSONObject item = mItems.getJSONObject(position);
String listitem_pic = item.getString("picture");
holder.listitem_pic.setTag(listitem_pic);
mImageLoader.DisplayImage(listitem_pic, (Activity)mContext, holder.listitem_pic);
holder.listitem_title.setText(item.getString("title"));
holder.listitem_desc.setText(item.getString("desc"));
}
catch (JSONException e) {
}
return convertView;
}
static class ViewHolder {
TextView listitem_title;
ImageView listitem_pic;
TextView listitem_desc;
}
}
It depends on your implementation of ItemAdapter, I'd recommend holding a reference to ItemAdapter, then updating the data set behind it and then calling notifyDataSetChanged() on it. something like:
ItemAdapter ia = new ItemAdapter(ItemList.this, mType, mItems);
setListAdapter(ia);
footerView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mItems.append(newItems);
ia.notifyDataSetChanged();
}
});
It is tricky without knowing what data you are using or whether you have the entire data set available at the start.