In ListView here i have all my contacts with check box. When i select 2 contacts from list and hit a button then selected list's value should be display in next activity. How can i do this?
Its my Activity class :
public class ContactListActivity extends Activity implements OnItemClickListener {
private ListView listView;
private List<ContactBean> list = new ArrayList<ContactBean>();
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.list);
listView.setOnItemClickListener(this);
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (phones.moveToNext()) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
ContactBean objContact = new ContactBean();
objContact.setName(name);
objContact.setPhoneNo(phoneNumber);
list.add(objContact);
}
phones.close();
ContanctAdapter objAdapter = new ContanctAdapter(ContactListActivity.this, R.layout.alluser_row, list);
listView.setAdapter(objAdapter);
if (null != list && list.size() != 0) {
Collections.sort(list, new Comparator<ContactBean>() {
#Override
public int compare(ContactBean lhs, ContactBean rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});
AlertDialog alert = new AlertDialog.Builder(ContactListActivity.this).create();
alert.setTitle("");
alert.setMessage(list.size() + " Contact Found!!!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
} else {
showToast("No Contact Found!!!");
}
}
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onItemClick(AdapterView<?> listview, View v, int position, long id) {
ContactBean bean = (ContactBean) listview.getItemAtPosition(position);
showCallDialog(bean.getName(), bean.getPhoneNo());
}
private void showCallDialog(String name, final String phoneNo) {
AlertDialog alert = new AlertDialog.Builder(ContactListActivity.this).create();
alert.setTitle("Call?");
alert.setMessage("Are you sure want to call " + name + " ?");
alert.setButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.setButton2("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String phoneNumber = "tel:" + phoneNo;
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(phoneNumber));
startActivity(intent);
}
});
alert.show();
}
And My Adapter Class to Hold Data is
public class ContanctAdapter extends ArrayAdapter<ContactBean> {
private Activity activity;
private List<ContactBean> items;
private int row;
private LayoutInflater inflater = null;
public ContanctAdapter(Activity act, int row, List<ContactBean> items) {
super(act, row, items);
this.activity = act;
this.row = row;
this.items = items;
this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(row, null);
holder.tvname = (TextView) convertView.findViewById(R.id.tvname);
holder.tvPhoneNo = (TextView) convertView.findViewById(R.id.tvphone);
holder.checkbox = (ImageView) convertView.findViewById(R.id.img_checkbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if ((items == null) || ((position + 1) > items.size()))
return convertView;
ContactBean objBean = items.get(position);
holder.checkbox.setSelected((objBean.getIsSelected() == 1) ? true : false);
if (holder.tvname != null && null != objBean.getName() && objBean.getName().trim().length() > 0) {
holder.tvname.setText(Html.fromHtml(objBean.getName()));
}
if (holder.tvPhoneNo != null && null != objBean.getPhoneNo() && objBean.getPhoneNo().trim().length() > 0) {
holder.tvPhoneNo.setText(Html.fromHtml(objBean.getPhoneNo()));
}
holder.checkbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
items.get(position).isSelected = (v.isSelected()) ? 0 : 1;
notifyDataSetChanged();
}
});
return convertView;
}
public class ViewHolder {
public TextView tvname, tvPhoneNo;
private ImageView checkbox;
}
}
There is multiple ways to achieve that :
Method 1:
Use static class setter and getter method:
create static class and set values from first activity and get value from second activity
Method 2:
Post your values through the intent
Method 3:
Use database to store data from one activity and get data from other activity
Method 4:
Use Shared preference
Example:
Post values using Intent like this
Post values in Shared preference
Another tutorial for Shared preference
Try this, It may Help you
Add this code in your onitemClicklistener Listview Page
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
String TVNameitem = ((TextView) view.findViewById(R.id.tvname)).getText().toString();
String TVPhoneitem = ((TextView) view.findViewById(R.id.tvphone)).getText().toString();
Intent intent1 = new Intent(this,NextActivity.class);
intent1.putExtra("STRING_I_NEED_From_TVNAME", TVNameitem );
intent1.putExtra("STRING_I_NEED_From_TVPHONE",TVPhoneitem );
startActivity(intent1);
}
Add this code in your Nextactivty Oncreate for Getting Values, Then Show in Textview
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.find);
Bundle extras = getIntent().getExtras();
String VALUE_1= extras.getString("STRING_I_NEED_From_TVNAME");
String Value_2 =extras.getString("STRING_I_NEED_From_TVPHONE");
TextView Textview1=(TextView)findViewById(R.id.CompanyText);
Textview1.setText(VALUE_1+":"+Value_2);
}
Create getter and setter to share contact details.
public class GetContacts {
private String contactNumber;
private String contactName;
GetContacts(){}// constructor without parameter.
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
}
Now set contact values to the setters in GetContact class
create an instance of GetContact class in your first Activity.
GetContact getContact= new GetContact();
And Set Parameters.
getContact.setContactNumber(phoneNumber);
getContact.setContactName(name);
Now its time to get those values in second activity.
create an instance of GetContact class in your second Activity like you did before.
And Get Parameters, and display into TextView.
textView1.setText(getContact.getContactNumber(phoneNumber));
textView2.setText(getContact.getContactName(name));
Related
I have a code that calls a fragment as an activity. From that fragment I select a data then give it back to the activity caller and here is my code.
Heres how I open the dialog
fragment_customer_list dialog = new fragment_customer_list();
dialog.show(getFragmentManager(),"CustomerList");
And here is how I return the value
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView position1 = (TextView) view.findViewById(R.id.list_name);
TextView position2 = (TextView) view.findViewById(R.id.list_address);
String customer_name = position1.getText().toString();
String customer_address = position2.getText().toString();
add callingActivity = (add_activity ) getActivity();
callingActivity.onUserSelectValue(customer_name, customer_address);
getDialog().dismiss();
}
});
I will call a function from the activity that calls the dialog to update the edittext.
public void onUserSelectValue(String selectedValue1 ,String selectedValue2) {
//Toast.makeText(getBaseContext(), ""+ selectedValue1 + selectedValue2, Toast.LENGTH_LONG).show();
EditText customer_name = (EditText) findViewById(R.id.cusname);
customer_name.setText(selectedValue1);
EditText customer_address = (EditText) findViewById(R.id.address);
customer_address.setText(selectedValue2);
}
The problem is the dialog is fixed in one activity. My question is how can I return the data from the activity caller? Since this fragment will be used by many activity
============================updated=============================
Here is how I open my fragment and i open it as a dialog
/* Open Customer List */
final EditText show_customer_list = (EditText) findViewById(R.id.cusname);
show_customer_list.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragment_customer_list dialog = new fragment_customer_list();
dialog.setOnClickItemListener(new fragment_customer_list.OnClickItemListener()
{
#Override
public void value(String name, String address)
{
show_customer_list.setText(name + " " + address);
}
});
dialog.show(getFragmentManager(),"CustomerList");
}
});
And here is the whole code fragment_customer_list
public class fragment_customer_list extends DialogFragment {
private static final String TAG = "CustomerList";
DatabaseHelper myDb;
String pattern_email;
SimpleAdapter adapter;
private DialogInterface.OnClickListener listener;
private OnClickItemListener mListener;
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, #Nullable final ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_customer_list, container, false);
final ListView listView = (ListView) view.findViewById(R.id.customer_list);
myDb = new DatabaseHelper(getActivity());
pattern_email = credentials.email;
final ArrayList<String> result = new ArrayList<>();
Cursor data = myDb.get_customer(pattern_email);
if (data.getCount() == 0) {
Toast.makeText(getActivity(), "Please sync to check your customers", Toast.LENGTH_LONG).show();
} else {
List<Map<String, String>> data1 = new ArrayList<Map<String, String>>();
while (data.moveToNext()) {
Map<String, String> datum = new HashMap<String, String>(2);
datum.put("Customer Name", data.getString(1));
datum.put("Address", data.getString(2));
data1.add(datum);
}
adapter = new SimpleAdapter(getActivity(), data1,
R.layout.customer_listview,
new String[]{"Customer Name", "Address"},
new int[]{R.id.list_name,
R.id.list_address});
listView.setAdapter(adapter);
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView position1 = (TextView) view.findViewById(R.id.list_name);
TextView position2 = (TextView) view.findViewById(R.id.list_address);
String customer_name = position1.getText().toString();
String customer_address = position2.getText().toString();
// add_activity callingActivity = (add_activity ) getActivity();
// callingActivity.onUserSelectValue(customer_name, customer_address);
if (mListener != null) {
mListener.value(customer_name, customer_address);
}
getDialog().dismiss();
}
});
android.widget.Button clickButton = (android.widget.Button) view.findViewById(R.id.close);
clickButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getDialog().dismiss();
}
});
/* Search customer */
EditText customer_search = (EditText) view.findViewById(R.id.search_customer);
customer_search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
final ArrayList<String> result = new ArrayList<>();
Cursor data = myDb.get_customer_search(cs.toString(),pattern_email);
if (data.getCount() == 0) {
//Toast.makeText(getActivity(), "Please sync to check your customers", Toast.LENGTH_LONG).show();
} else {
List<Map<String, String>> data1 = new ArrayList<Map<String, String>>();
while (data.moveToNext()) {
Map<String, String> datum = new HashMap<String, String>(2);
datum.put("Customer Name", data.getString(1));
datum.put("Address", data.getString(2));
data1.add(datum);
}
adapter = new SimpleAdapter(getActivity(), data1,
R.layout.customer_listview,
new String[]{"Customer Name", "Address"},
new int[]{R.id.list_name,
R.id.list_address});
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
#Override
public void afterTextChanged(Editable arg0) {
}
});
return view;
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new Dialog(getActivity(), R.style.WideDialog);
}
public void setOnClickItemListener(OnClickItemListener l) {
mListener = l;
}
interface OnClickItemListener {
void value(String name, String address);
}
}
As you can see on the code above there is Listview that has a code that same as this
add_activity callingActivity = (add_activity ) getActivity();
callingActivity.onUserSelectValue(customer_name, customer_address);
getDialog().dismiss();
The code above will get the value from listview and call the onUserSelectValue from add_activity then close the dialog
and this is onUserSelectValue and it is located at add_activity
public void onUserSelectValue(String selectedValue1 ,String selectedValue2) {
//Toast.makeText(getBaseContext(), ""+ selectedValue1 + selectedValue2, Toast.LENGTH_LONG).show();
EditText customer_name = (EditText) findViewById(R.id.cusname);
customer_name.setText(selectedValue1);
EditText customer_address = (EditText) findViewById(R.id.address);
customer_address.setText(selectedValue2);
}
Here is my question.
How can I return the value of the listview to the textfield of the activity who opens the fragment(where the list view is located).
UPDATED CODE
I created a class called DialogHelper.java and this is the code
public class DialogHelper {
private static WeakReference<fragment_customer_list> wr;
public static void userSelectValue(Activity context, fragment_customer_list.OnClickItemListener listener) {
if (wr == null || wr.get() == null) {
fragment_customer_list dialog = new fragment_customer_list();
wr = new WeakReference<>(dialog);
}
fragment_customer_list dialog = wr.get();
dialog.OnClickItemListener(listener);
dialog.show(context.getFragmentManager(),"CustomerList");
}
// dialog dismiss
public static void dismiss() {
if (wr == null || wr.get() == null) return;
wr.get().dismiss();
}
}
In my customer_fragment_list.java I have a listview listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView position1 = (TextView) view.findViewById(R.id.list_name);
TextView position2 = (TextView) view.findViewById(R.id.list_address);
TextView position3 = (TextView) view.findViewById(R.id.list_code);
String customer_name = position1.getText().toString();
String customer_address = position2.getText().toString();
String customer_code = position3.getText().toString();
if (listener != null) {
listener.click(customer_name, customer_address,customer_code );
}
}
});
together with this
public void setOnClickListener(OnClickListener l) {
this.listener = l;
}
interface OnClickListener {
void click(String name, String address,String KUNNR);
}
public interface OnClickItemListener { void value(String name, String address, String code); }
and on my Activity this the code on how i open the dialog
/* Open Customer List */
DialogHelper.userSelectValue(add_covplan.this, new fragment_customer_list.OnClickItemListener()
{
#Override
public void value(String name, String address)
{
EditText customer_name = (EditText) findViewById(R.id.cusname);
customer_name.setText(name);
EditText customer_address = (EditText) findViewById(R.id.address);
customer_address.setText(address);
}
});
you can do this. Don't know if you mean this?
public class DialogHelper {
private static WeakReference<fragment_customer_list> wr;
private static WeakReference<Activity> wrActivity;
public static void userSelectValue(Activity context, fragment_customer_list.OnClickItemListener listener) {
if (wr == null || wr.get() == null || wrActivity == null || wrActivity.get() == null || wrActivity.get() != context) {
fragment_customer_list dialog = new fragment_customer_list();
wr = new WeakReference<>(dialog);
wrActivity = new WeakReference<>(context);
}
fragment_customer_list dialog = wr.get();
dialog.setOnClickItemListener(listener);
dialog.show(context.getFragmentManager(),"CustomerList");
}
// dialog dismiss
public static void dismiss() {
if (wr == null || wr.get() == null || !wr.get().isShowing()) return;
wr.get().dismiss();
}
}
use
final EditText show_customer_list = (EditText) findViewById(R.id.cusname);
DialogHelper.userSelectValue(this, new fragment_customer_list.OnClickItemListener()
{
#Override
public void value(String name, String address)
{
show_customer_list.setText(name + " " + address);
}
});
edit answer
// Suppose this is a FragmentDialog
public class FragmentList {
private OnClickListener listener;
private ListView listView;
// Suppose this has your list listener
public void onResume() {
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView position1 = (TextView) view.findViewById(R.id.list_name);
TextView position2 = (TextView) view.findViewById(R.id.list_address);
String customer_name = position1.getText().toString();
String customer_address = position2.getText().toString();
if (listener != null) {
listener.click(customer_name, customer_address);
}
}
});
}
public void setOnClickListener(OnClickListener l) {
this.listener = l;
}
interface OnClickListener {
void click(String name, String address);
}
}
// Suppose this is a Activity
class YourActivity extends Activity
{
private FragmentList fragmentList;
EditText customer_address;
EditText customer_name;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
fragmentList = new FragmentList();
customer_address = (EditText) findViewById(R.id.address);
customer_name = (EditText) findViewById(R.id.cusname);
fragmentList.setOnClickListener(new FragmentList.OnClickListener()
{
#Override
public void click(String name, String address)
{
// ...
customer_name.setText(name);
customer_address.setText(address);
}
});
}
}
You can use a ViewModel class implementation to share resources between Activity and Fragment. Share the single context across multiple usages of ViewModel, each sharing a the same ViewModel. It works with the observer and observable pattern and perfect for this use case. You can check details on how to implement it here
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.
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.
sir, how do i refresh my listview if i pressed the back button in android emulator? i've clicked an item on activityA then goes to an edit form in activityB. after saving updates, if i pressed the back button, it should refresh the list.
here is my activityA
public class CustomListView extends Activity {
final Context context = this;
public static String name;
public static String number;
int REQUEST_CODE = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GroupDb info = new GroupDb(this);
info.open();
ArrayList<Contact> searchResults = info.getView();
MyCustomBaseAdapter mcba = new MyCustomBaseAdapter(CustomListView.this, searchResults);
mcba.updateResults(searchResults);
final ListView lv = (ListView) findViewById(R.id.srListView);
lv.setAdapter(new MyCustomBaseAdapter(this, searchResults));
info.close();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
// TODO Auto-generated method stub
Object o = lv.getItemAtPosition(position);
final Contact fullObject = (Contact)o;
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder
.setMessage("Select action")
.setCancelable(false)
.setPositiveButton("Edit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Toast.makeText(getApplicationContext(), "Edit ", Toast.LENGTH_LONG).show();
name = fullObject.getName();
number = fullObject.getPhoneNumber();
Intent intent = new Intent();
intent.setClass(CustomListView.this, EditDetails.class);
startActivityForResult(intent, REQUEST_CODE);
}
})
.setNeutralButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Toast.makeText(getApplicationContext(), "Delete ", Toast.LENGTH_LONG).show();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
public void onResume()
{ // After a pause OR at startup
super.onResume();
//Refresh your stuff here
GroupDb info = new GroupDb(this);
info.open();
ArrayList<Contact> searchResults = info.getView();
MyCustomBaseAdapter mcba = new MyCustomBaseAdapter(CustomListView.this, searchResults);
mcba.updateResults(searchResults);
info.close();
}
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == REQUEST_CODE) {
GroupDb info = new GroupDb(this);
info.open();
ArrayList<Contact> searchResults = info.getView();
MyCustomBaseAdapter mcba = new MyCustomBaseAdapter(CustomListView.this, searchResults);
mcba.updateResults(searchResults);
info.close();
}
}
//edit or delete list when clicked
public void deleteEditOption()
{
}//end deleteEditOption()
}
and here is my activityB
public class EditDetails extends Activity{
public String nameChanged;
public String numChanged;
public String name;
public String num;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editdetails);
final EditText sqlName = (EditText)findViewById(R.id.editName);
final EditText sqlNumber = (EditText)findViewById(R.id.editNumber);
name = CustomListView.name;
num = CustomListView.number;
Button bUpdate = (Button)findViewById(R.id.editUpdate);
Button bView = (Button)findViewById(R.id.editView);
sqlName.setText(name);
sqlNumber.setText(num);
bUpdate.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
nameChanged = sqlName.getText().toString();
numChanged = sqlNumber.getText().toString();
GroupDb info = new GroupDb(EditDetails.this);
info.open();
long rowid = info.getRowId(name, num);
info.updateNameNumber(rowid+1, nameChanged, numChanged);
Toast.makeText(getApplicationContext(), rowid+" "+nameChanged+" "+numChanged, Toast.LENGTH_LONG).show();
ArrayList<Contact> searchResults = info.getView();
MyCustomBaseAdapter mcba = new MyCustomBaseAdapter(EditDetails.this, searchResults);
mcba.updateResults(searchResults);
Toast.makeText(getApplicationContext(), "Update Successful!", Toast.LENGTH_LONG).show();
info.close();
}
});
bView.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setClass(EditDetails.this, CustomListView.class);
startActivityForResult(intent, 0);
}
});
}
}
if i clicked this bView button in my activityB, it updates the listview. but pressing the back button just shows my previous unupdated listview. thanks for help in advance
edit
public class MyCustomBaseAdapter extends BaseAdapter {
private static ArrayList<Contact> searchArrayList;
private LayoutInflater mInflater;
public MyCustomBaseAdapter(Context context, ArrayList<Contact> results) {
searchArrayList = results;
mInflater = LayoutInflater.from(context);
}
public void updateResults(ArrayList<Contact> results) {
searchArrayList = results;
//Triggers the list update
notifyDataSetChanged();
}
public int getCount() {
return searchArrayList.size();
}
public Object getItem(int position) {
return searchArrayList.get(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.custom_row_view, null);
holder = new ViewHolder();
holder.txtName = (TextView) convertView.findViewById(R.id.name);
holder.txtPhone = (TextView) convertView.findViewById(R.id.phone);
holder.status = (TextView) convertView.findViewById(R.id.status);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtName.setText(searchArrayList.get(position).getName());
holder.txtPhone.setText(searchArrayList.get(position).getPhoneNumber());
holder.status.setText(searchArrayList.get(position).getStatus());
return convertView;
}
static class ViewHolder {
TextView txtName;
TextView txtPhone;
TextView status;
}
}
Rewrite
While I recommend customizing a CursorAdapter to work with your database. Let's change a couple points with your current code:
First create a field variable for mbca, (just like name and number).
MyCustomBaseAdapter mcba;
Second update how you initialize mbca in onCreate():
mcba = new MyCustomBaseAdapter(EditDetails.this, searchResults);
//mcba.updateResults(searchResults); this line isn't necessary here
Third make a small change to onResume():
public void onResume()
{ // After a pause OR at startup
super.onResume();
//Refresh your stuff here
GroupDb info = new GroupDb(this);
info.open();
mcba.updateResults(info.getView());
info.close();
}
This works because updateResults() calls notifyDataSetChanged() and this updates the ListView automatically.
My ListView consist an ImageView and a TextView I need to get the Text from the TextView.
int the position of my list where I press (onItemClick).
How can I do that?
The 1 class have a Button then when you press I moving to the next activity (CountryView)
and expect to get back from the next activity with a text (name of the selected Country)
The 2 classes have a ListView (ImageView and TextView) the data is getting from a database and showing on the ListView.
My problem is to get back to the 1 class the selected name of the country.
Thanks so much for helping!!!
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
// final int recquestCode = 0;
final Button btnCountry = (Button) findViewById(R.id.fromButton);
btnCountry.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent pingIntent = new Intent("CountryView");
pingIntent.putExtra("btnText", " ");
pingIntent.setClass(Travel.this, CountryView.class);
startActivityForResult(pingIntent, RECEIVE_MESSAGE);
}
});
/* Button btnSearch = (Button) findViewById(R.id.searchButton);
btnSearch.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(v.getContext(), ResultView.class);
startActivityForResult(intent, 0);
}
});*/
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (data.hasExtra("response")){
Button b = (Button)findViewById(R.id.fromButton);
CharSequence seq = data.getCharSequenceExtra("response");
b.setText(seq);
}
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.country);
mListUsers = getCountry();
lvUsers = (ListView) findViewById(R.id.countrylistView);
lvUsers.setAdapter(new ListAdapter(this, R.id.countrylistView, mListUsers));
// lvUsers.setTextFilterEnabled(true);
// String extraMsg1 = getIntent().getExtras().getString("extra1");
lvUsers.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
// When clicked, show a toast with the TextView text
//textItem=view;
// Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
// Toast.LENGTH_SHORT).show();
Intent pongIntent = new Intent();
// lvUsers.getItemAtPosition(position);
t = (TextView) view;
Log.v("fffvd"+t, null);
t.setText(getIntent().getStringExtra("btnText"));
String strText = t.getText().toString();
//((TextView) view).getText().toString()
pongIntent.putExtra("response",strText);
setResult(Activity.RESULT_OK,pongIntent);
finish();
// startActivity(new Intent(CountryView.this,TravelPharmacy.class));
}
});
}
public ArrayList<Country> getCountry(){
DBHelper dbAdapter=DBHelper.getDBAdapterInstance(this);
try {
dbAdapter.createDataBase();
} catch (IOException e) {
Log.i("*** select ",e.getMessage());
}
dbAdapter.openDataBase();
String query="SELECT * FROM Pays;";
ArrayList<ArrayList<String>> stringList = dbAdapter.selectRecordsFromDBList(query, null);
dbAdapter.close();
ArrayList<Country> countryList = new ArrayList<Country>();
for (int i = 0; i < stringList.size(); i++) {
ArrayList<String> list = stringList.get(i);
Country country = new Country();
try {
//country.id = Integer.parseInt(list.get(0));
country.pays = list.get(1);
// country.age = Long.parseLong(list.get(2));
} catch (Exception e) {
Log.i("***" + TravelPharmacy.class.toString(), e.getMessage());
}
countryList.add(country);
}
return countryList;
}
#Override
public void onDestroy()
{
// adapter.imageLoader.stopThread();
lv.setAdapter(null);
super.onDestroy();
}
public OnClickListener listener=new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// adapter.imageLoader.clearCache();
((BaseAdapter) adapter).notifyDataSetChanged();
}
};
CountryAdapter Class
public class CountryAdapter extends BaseAdapter {
private Activity activity;
private String[] data;
private LayoutInflater inflater=null;
// public ImageLoader imageLoader;
public CountryAdapter(Activity a, String[] d)
{
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public class ViewHolder
{
public TextView text;
public ImageView image;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View vi=convertView;
ViewHolder holder;
if(convertView==null)
{
vi = inflater.inflate(R.layout.singlecountry, null);
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.text);;
holder.image=(ImageView)vi.findViewById(R.id.image);
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
holder.text.setText("item "+data[position]);
holder.image.setTag(data[position]);
return vi;
}
}
ListAdapter Class
private class ListAdapter extends ArrayAdapter<Country> { // --CloneChangeRequired
private ArrayList<Country> mList; // --CloneChangeRequired
private Context mContext;
public ListAdapter(Context context, int textViewResourceId,ArrayList<Country> list) { // --CloneChangeRequired
super(context, textViewResourceId, list);
this.mList = list;
this.mContext = context;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View view = convertView;
try{
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.singlecountry, null); // --CloneChangeRequired(list_item)
}
final Country listItem = mList.get(position); // --CloneChangeRequired
if (listItem != null) {
// setting singleCountry views
// ( (TextView) view.findViewById(R.id.tv_id) ).setText( listItem.getId()+"");
( (TextView) view.findViewById(R.id.text) ).setText( listItem.getPays() );
//((ImageView)view.findViewById(R.id.image)).setImageDrawable(drawable.world);
//( (TextView) view.findViewById(R.id.tv_age) ).setText( listItem.getAge()+"" );
}}catch(Exception e){
Log.i(CountryView.ListAdapter.class.toString(), e.getMessage());
}
return view;
}
}
When you add things to the list, you can add hashmaps to the arraylist which the adapter looks at. Then you can grab the values which are name value pairs.
I think you want to get the position of the list you clicked, Its simple you can use OnItemClickListener as follows
YourList.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
int position=arg2;
// where position is the clicked position
} }
If you stored your data in String array pass this position say array[position] to string array you can get the Text..