how to add multi contact picker? - android

I am following this library to add contact picker https://github.com/codinguser/android_contact_picker, and I am able to get numbers successfully from adding to my EditTextBox but, I want to add multiple contacts selected from contact and add only number in particular EditTextView this is my contact picker activity, I am stuck about that where to add adapter to complete that, any help?:
public class ContactsPickerActivity extends AppCompatActivity implements OnContactSelectedListener {
public static final String SELECTED_CONTACT_ID = "contact_id";
public static final String KEY_PHONE_NUMBER = "phone_number";
public static final String KEY_CONTACT_NAME = "contact_name";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
FragmentManager fragmentManager = this.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ContactsListFragment fragment = new ContactsListFragment();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle("Select contact");
}
}
#Override
public void onContactNameSelected(long contactId) {
/* Now that we know which Contact was selected we can go to the details fragment */
Fragment detailsFragment = new ContactDetailsFragment();
Bundle args = new Bundle();
args.putLong(ContactsPickerActivity.SELECTED_CONTACT_ID, contactId);
detailsFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, detailsFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
/**
* Callback when the contact number is selected from the contact details view
* Sets the activity result with the contact information and finishes
*/
#Override
public void onContactNumberSelected(String contactNumber, String contactName) {
Intent intent = new Intent();
intent.putExtra(KEY_PHONE_NUMBER, contactNumber);
intent.putExtra(KEY_CONTACT_NAME, contactName);
setResult(RESULT_OK, intent);
finish();
}

Try this library https://github.com/1gravity/Android-ContactPicker it will help you to pick multiple contacts. You will get selected contacts in onActivityResult() method, from here you can display it in editText.

Related

Button calles main activity from within the fragment

I 've added a button to the menu which is suppose to take me from the fragment to the main activity but I don't now how to implement it?
I put a switch statement inside onOptionsItemSelected.
Fragment wehre I will call main activity:
public class DetailFragment extends Fragment
implements LoaderManager.LoaderCallbacks<Cursor> {
//Fragment detailFragment= new Fragment(this);
// callback methods implemented by MainActivity
public interface DetailFragmentListener {
void onContactDeleted(); // called when a contact is deleted
// pass Uri of contact to edit to the DetailFragmentListener
void onEditContact(Uri contactUri);
}
private static final int CONTACT_LOADER = 0; // identifies the Loader
private DetailFragmentListener listener; // MainActivity
private Uri contactUri; // Uri of selected contact
private TextView nameTextView; // displays contact's name
private TextView phoneTextView; // displays contact's phone
private TextView emailTextView; // displays contact's email
private TextView specialtyTextView; // displays contact's
private TextView cityTextView; // displays contact's city
private TextView chargeTextView; // displays contact's state
private TextView noteTextView; // displays contact's zip
private Button callButton; //Nuha
private Button emailButton;
private Button smsButton;
// set DetailFragmentListener when fragment attached
#Override
public void onAttach(Context context) {
super.onAttach(context);
listener = (DetailFragmentListener) context;
}
// remove DetailFragmentListener when fragment detached
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
// called when DetailFragmentListener's view needs to be created
#Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
setHasOptionsMenu(true); // this fragment has menu items to display
// get Bundle of arguments then extract the contact's Uri
Bundle arguments = getArguments();
if (arguments != null)
contactUri = arguments.getParcelable(MainActivity.CONTACT_URI);
// inflate DetailFragment's layout
View view =
inflater.inflate(R.layout.fragment_detail, container, false);
// get the EditTexts
nameTextView = (TextView) view.findViewById(R.id.nameTextView);
phoneTextView = (TextView) view.findViewById(R.id.phoneTextView);
emailTextView = (TextView) view.findViewById(R.id.emailTextView);
specialtyTextView = (TextView) view.findViewById(R.id.specialtyTextView);
cityTextView = (TextView) view.findViewById(R.id.cityTextView);
chargeTextView = (TextView) view.findViewById(R.id.chargeTextView);
noteTextView = (TextView) view.findViewById(R.id.noteTextView);
callButton = (Button) view.findViewById(R.id.callbutton);//nuha
emailButton=(Button) view.findViewById(R.id.sendEmailbutton);
smsButton=(Button)view.findViewById(R.id.smsbutton);
// load the contact
getLoaderManager().initLoader(CONTACT_LOADER, null, this);
addListenerOnButton(view);//Nuha buttons
Animation animation = AnimationUtils.loadAnimation(getContext(),R.anim.pop_enter);//Animate details Nuha
nameTextView.startAnimation(animation);
phoneTextView.startAnimation(animation);
emailTextView.startAnimation(animation);
emailButton.startAnimation(animation);
specialtyTextView.startAnimation(animation);
cityTextView.startAnimation(animation);
chargeTextView.startAnimation(animation);
noteTextView.startAnimation(animation);
callButton.startAnimation(animation);
emailButton.startAnimation(animation);//till here
return view;
}
// display this fragment's menu items
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_details_menu, menu);
}
// handle menu item selections
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_edit:
listener.onEditContact(contactUri); // pass Uri to listener
return true;
case R.id.action_home:////home button
//What should I put here ??
return true;
case R.id.action_delete:
deleteContact();
return true;
}
return super.onOptionsItemSelected(item);
}
My mainactivity :
public class MainActivity extends AppCompatActivity
implements ContactsFragment.ContactsFragmentListener,
DetailFragment.DetailFragmentListener,
AddEditFragment.AddEditFragmentListener {
// key for storing a contact's Uri in a Bundle passed to a fragment
public static final String CONTACT_URI = "contact_uri";
private ContactsFragment contactsFragment; // displays contact list
// display ContactsFragment when MainActivity first loads
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// if layout contains fragmentContainer, the phone layout is in use;
// create and display a ContactsFragment
if (savedInstanceState == null &&
findViewById(R.id.fragmentContainer) != null) {
// create ContactsFragment
//Nuha animation
// add the fragment to the FrameLayout
///Nuha try animation
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.pop_enter, R.anim.pop_exit);
contactsFragment = new ContactsFragment();
transaction.replace(R.id.fragmentContainer, contactsFragment);
transaction.addToBackStack(null);
transaction.commit();
}
else {
contactsFragment =
(ContactsFragment) getSupportFragmentManager().
findFragmentById(R.id.contactsFragment);
}
}
// display DetailFragment for selected contact
#Override
public void onContactSelected(Uri contactUri) {
if (findViewById(R.id.fragmentContainer) != null) // phone
displayContact(contactUri, R.id.fragmentContainer);
else { // tablet
// removes top of back stack
getSupportFragmentManager().popBackStack();
displayContact(contactUri, R.id.rightPaneContainer);
}
}
// display AddEditFragment to add a new contact
#Override
public void onAddContact() {
if (findViewById(R.id.fragmentContainer) != null) // phone
displayAddEditFragment(R.id.fragmentContainer, null);
else // tablet
displayAddEditFragment(R.id.rightPaneContainer, null);
}
// display a contact
private void displayContact(Uri contactUri, int viewID) {
DetailFragment detailFragment = new DetailFragment();
// specify contact's Uri as an argument to the DetailFragment
Bundle arguments = new Bundle();
arguments.putParcelable(CONTACT_URI, contactUri);
detailFragment.setArguments(arguments);
// use a FragmentTransaction to display the DetailFragment
FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();
transaction.replace(viewID, detailFragment);
transaction.addToBackStack(null);
transaction.commit(); // causes DetailFragment to display
}
// display fragment for adding a new or editing an existing contact
private void displayAddEditFragment(int viewID, Uri contactUri) {
AddEditFragment addEditFragment = new AddEditFragment();
// if editing existing contact, provide contactUri as an argument
if (contactUri != null) {
Bundle arguments = new Bundle();
arguments.putParcelable(CONTACT_URI, contactUri);
addEditFragment.setArguments(arguments);
}
// use a FragmentTransaction to display the AddEditFragment
FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();
transaction.replace(viewID, addEditFragment);
transaction.addToBackStack(null);
transaction.commit(); // causes AddEditFragment to display
}
// return to contact list when displayed contact deleted
#Override
public void onContactDeleted() {
// removes top of back stack
getSupportFragmentManager().popBackStack();
contactsFragment.updateContactList(); // refresh contacts
}
// display the AddEditFragment to edit an existing contact
#Override
public void onEditContact(Uri contactUri) {
if (findViewById(R.id.fragmentContainer) != null) // phone
displayAddEditFragment(R.id.fragmentContainer, contactUri);
else // tablet
displayAddEditFragment(R.id.rightPaneContainer, contactUri);
}
// update GUI after new contact or updated contact saved
#Override
public void onAddEditCompleted(Uri contactUri) {
// removes top of back stack
getSupportFragmentManager().popBackStack();
contactsFragment.updateContactList(); // refresh contacts
if (findViewById(R.id.fragmentContainer) == null) { // tablet
// removes top of back stack
getSupportFragmentManager().popBackStack();
// on tablet, display contact that was just added or edited
displayContact(contactUri, R.id.rightPaneContainer);
}
}
//
}
Can you please help ?
Edit: This fragment is associated with the main activity.. I want to return to the main activity with the original fragment.
If I get your question correctly, this is what you need to put in your switch statement,
Intent mainActivityIntent = new Intent(getActivity(),MainActivity.class);
startActivity(mainActivityIntent);
brief explanation of the constructor of Intent
getActivity() returns the activity associated with the fragment.
The activity is a context (since Activity extends Context).
MainActivity.class is the activity you want to return to.
Hope this helps! :)
-After you updated the question-
I think this is what you are looking for How to get a Fragment to remove itself?
Try this.(inside fragment)
Intent intent = new Intent (getApplicationContext(),MainActivity.class);
startActivity(intent);
you have to use this in your itenselected option
Intent intent = new Intent(context, ActivityName.class);
startActivity(intent);
where context is the fragment that you are using , and the next is the activity that you want to go .

Saving Fragment State/Data from Fragment to Fragment

I'm trying to figure out how to save user inputted data on a fragment if they leave it and come back. I have one Activity that several Fragments work off of. All the examples I find are saving the state when leaving the Fragment and Activity. I'm never leaving the Activity; therefore onSaveInstanceState within the Fragment is never called. onPause is called, but I'm unable to figure out how to save the state within there.
This app displays a list of tickets. When the user taps a ticket, it grabs preliminary information from the local DB for read only fields and allows the user to input the ticket information before submitting. I'm trying to allow a user to tap on a ticket, enter data, leave and come back to that ticket without losing information entered.
Out of all the examples I've studied on this, it seems to me I can use Fragmenttransaction to save the Fragment's ID. Below is the main Activity that all fragments are attached to:
public class Activity_Main extends Activity
implements Fragment_OpenTickets.INT_OnOpenTicketSelectedListener,
Fragment_SubTickets.INT_OnSubTicketSelectedListener,
Fragment_Ticket.INT_SubmitNewTicket {
DBController dbc;
Fragment fr;
boolean gps_enabled = false;
boolean network_enabled = false;
HashMap<String, String> addInfo;
RadioButton btn_radio_open;
RadioButton btn_radio_submitted;
RadioButton btn_radio_settings;
String ticketDate, ticketTime;
int m, d, y, hr, min;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_radio_open = (RadioButton)findViewById(R.id.radio_open);
btn_radio_submitted = (RadioButton)findViewById(R.id.radio_submitted);
btn_radio_settings = (RadioButton)findViewById(R.id.radio_settings);
dbc = new DBController(this);
if (dbc.checkCredentials() != null) {
fr = new Fragment_OpenTickets();
} else {
fr = new Fragment_Settings();
btn_radio_open.setChecked(false);
btn_radio_submitted.setChecked(false);
btn_radio_settings.setChecked(true);
}
FragmentManager fm = getFragmentManager();
final FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragment_place, fr);
ft.addToBackStack(null); // For back button action.
ft.commit();
// Start scheduler service.
this.startService(new Intent(this, Service_Send.class));
// Start GPS service.
startGPS();
}
/**
* Top menu buttons.
*/
public void selectFrag(View view) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
switch (view.getId()) {
case R.id.radio_open:
//fr = new Fragment_OpenTickets();
ft.replace(R.id.fragment_place, new Fragment_OpenTickets());
ft.addToBackStack(null);
btn_radio_submitted.setChecked(false);
btn_radio_settings.setChecked(false);
ft.commit();
break;
case R.id.radio_submitted:
//fr = new Fragment_SubTickets();
ft.replace(R.id.fragment_place, new Fragment_SubTickets());
ft.addToBackStack(null);
btn_radio_open.setChecked(false);
btn_radio_settings.setChecked(false);
ft.commit();
break;
case R.id.radio_settings:
//fr = new Fragment_Settings();
ft.replace(R.id.fragment_place, new Fragment_Settings());
ft.addToBackStack(null);
btn_radio_open.setChecked(false);
btn_radio_submitted.setChecked(false);
ft.commit();
break;
}
}
/**
* Open ticket selection action.
*/
public void onOpenTicketSelected(HashMap position) {
// Create fragment and give it an argument for the selected ticket.
fr = new Fragment_Ticket();
Bundle args = new Bundle();
args.putSerializable("HashMap", position);
fr.setArguments(args);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragment_place, fr);
ft.addToBackStack(null); // For back button action.
ft.commit();
}
/**
* Submitted ticket selection action.
*/
public void onSubTicketSelected(HashMap position) {
// Create fragment and give it an argument for the selected ticket.
fr = new Fragment_SubTicket();
Bundle args = new Bundle();
args.putSerializable("HashMap", position);
fr.setArguments(args);
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);
fragmentTransaction.addToBackStack(null); // For back button action.
fragmentTransaction.commit();
}
Any help will be very appreciated. If I need to post more code then please let me know. Thank you!
I think you should store ticket info in your Activity when users leave the fragment and get the info back and display it when you come back.
In Activity_Main class, you create 2 methods:
public void saveTicketInfo(TicketInfo info) {
// save info here
}
And:
public TicketInfo getTicketInfo() {
// get info here
}
In your fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
// get ticket info and display it
Activity_Main mainActivity = (Activity_Main)getActivity();
TicketInfo info = mainActivity.getTicketInfo();
if (info != null) {
// handle display info here
}
...
}
#Override
public void onDestroyView() {
TicketInfo info = new TicketInfo();
// get info from view and store in the object
Activity_Main mainActivity = (Activity_Main)getActivity();
mainActivity.saveTicketInfo(info)
super.onDestroyView();
}
I posted a lengthy detailed answer on SO # Passing data between fragments contained in an activity. Search for my answer on it. This is a safe way to pass data from Fragment to Activity. And then you can easily pass that data from Activity to the Fragment's constructor or public method.

Adding and replacing Fragments , is not working as expected in android

I was trying out android fragments, and i could not understand this; please help
public class MainActivity extends FragmentActivity {
private static final String TAG = "MyActivity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (findViewById(R.id.fragment_container) !=null) {
if(savedInstanceState!=null){
return ;
}
ArticleFragment first_fragment = new ArticleFragment();
HeadlineFragment second_fragment = new HeadlineFragment();
first_fragment.setArguments(getIntent().getExtras());
second_fragment.setArguments(getIntent().getExtras());
FragmentTransaction manager=getSupportFragmentManager().beginTransaction();
manager.add(R.id.fragment_container, first_fragment,"first");
manager.add(R.id.yo, second_fragment,"second");
manager.commit();
}
}
now i want to remove second_fragment at a button press and replace it with another. So i tried this
if(getSupportFragmentManager().findFragmentByTag("second")!=null) {
Log.d(TAG,"found");
abc newFragment = new abc();
Bundle args = new Bundle();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.remove(getSupportFragmentManager().findFragmentByTag("second"));
transaction.add(R.id.fragment_container,newFragment,"third");
transaction.addToBackStack(null);
transaction.commit();
}
but when i press that button again and again, the if condition passes.
What is wrong here?
Don't Do removing and adding. Simply Replace second fragment with the new one. You will be done.

Android passing object to fragment

I have a message class
class Message
{
public String message, sender;
public Message (String msg, String from)
{
message = msg;
sender = from;
}
public String toString () { return sender+":"+message; }
}
I defined a table variable for use this class in main activity:
Hashtable<String, ArrayList<Message>> table = new Hashtable<String, ArrayList<Message>>();
I am adding data in main activity to message class with this code:
table.put("user01", new ArrayList<Message>());
table.get("user01").add(new Message("message","sender"));
And I want to use this table variable in another fragment.I am passing with this code to fragment.
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ConversationFragment conv = new ConversationFragment();
fragmentTransaction.add(R.id.container, conv);
ConversationFragment frgObj=ConversationFragment.newInstance(table.get("user01"));
fragmentTransaction.replace(R.id.container, frgObj,"ConversationFragment");
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
And this is newInstance function in Conversation fragment
static int myData;
public static ConversationFragment newInstance(ArrayList<Message> _extractedMessages){
ConversationFragment fragment = new ConversationFragment();
myData=_extractedMessages.size();
return fragment;
}
But I am getting nullpointer exception,for _extractedMessages.size().
This code is working
System.out.println(_extractedMessages);
But this is not working
System.out.println(_extractedMessages.size());
Ps:I can use size function in main activity,I can't use only in conversation fragment.
How can I fix it ?
Typically you pass parameters to the fragment in the Bundle (and make sure the Message class implements Parcelable):
public static ConversationFragment newInstance(ArrayList<Message> _extractedMessages){
ConversationFragment fragment = new ConversationFragment();
Bundle bundle = new Bundle();
bundle.putParcelable(KEY_MESSAGES, _extractedMessages);
fragment.setArguments(bundle);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myData = getArguments().getParcelable(KEY_MESSAGES);
}

Fragments Behave Weirdly When Using addToBackStack()

An SSCCE for this issue is available on GitHub.
For future readers, the original example is on a branch of the same project, and the fix is available in this diff.
This SSCCE has a ListView and a row of buttons. The buttons are supposed to change the data in the ListView, and the listView rows (when clicked) are supposed to open a new fragment and advance the backstack while staying in the same activity.
If do the following things, it produces the following result:
Open the app.
Tap the ListView. - FragmentTransaction.replace(...) with addToBackStack(true)
Tap any of the buttons. - FragmentTransaction.replace(...) with addToBackStack(false)
Tap the back button.
Result:
Both fragments become visible, but I only want the first loaded fragment (ListTwoFragment in code) to display. Is this how fragments are supposed to work? If so, how can I get the desired effect?
MainActivity.java:
public class MainActivity extends FragmentActivity implements ListTwoFragment.Callbacks,
ListThreeFragment.Callbacks {
public static final String KEY_ARGS = "args";
private String curUri = "";
private String curArgs = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectContent(false);
}
private void selectContent(boolean addToBackStack) {
Fragment fragment;
if (curUri.isEmpty()) {
// Use default fragment
fragment = new ListTwoFragment();
curUri = ListTwoFragment.class.getName();
}
else {
try {
Class<Fragment> fragmentClass = (Class<Fragment>) Class.forName(curUri);
fragment = fragmentClass.newInstance();
}
catch (Exception e) { // ClassNotFound, IllegalAccess, etc.
return;
}
}
// Configure fragment
Bundle args = new Bundle();
args.putString(KEY_ARGS, curArgs);
fragment.setArguments(args);
attachFragment(fragment, addToBackStack, curUri + ";" + curArgs, R.id.fragment_container);
}
protected void attachFragment(Fragment fragment, boolean addToBackStack, String tag, int replaceId) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(replaceId, fragment, tag);
if (addToBackStack) transaction.addToBackStack(tag);
transaction.commit();
}
#Override
public void onTwoButtonClick(String title) {
curUri = ListTwoFragment.class.getName();
curArgs = title;
selectContent(false);
}
#Override
public void onTwoListClick() {
curUri = ListThreeFragment.class.getName();
curArgs = "";
selectContent(true);
}
#Override
public void onThreeButtonClick(String title) {
curUri = ListThreeFragment.class.getName();
curArgs = title;
selectContent(false);
}
}
I'm working with Fragments to, and the way I'm doing it:
to go forward (add to stack), and backwords (remove from stack) are two different functions
to Add to Stack and change Fragment:
public void changeFragmentAddToStack(Fragment myNewFragment) {
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
t.add(R.id.main_fragment, myNewFragment);
t.addToBackStack(null);
t.commit();
}
To go back Stack:
public void goBackStackMain() {
FragmentManager man = getSupportFragmentManager();
if(man.getBackStackEntryCount()>0){
man.popBackStack(man.getBackStackEntryAt(0).getName(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
}
And if you want to do both: To go back stack and change fragment:
public void goBackStackAndReplaceFragment(Fragment myNewFragment) {
FragmentManager man = getSupportFragmentManager();
if(man.getBackStackEntryCount()>0){
int n = man.getBackStackEntryCount();
man.popBackStack(man.getBackStackEntryAt(n-1).getName(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
t.replace(R.id.main_fragment, myNewFragment);
t.commit();
}
I hope to help you !

Categories

Resources