Button calles main activity from within the fragment - android

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 .

Related

how to add multi contact picker?

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.

Calling function from a Fragment ..No activity to handle error

I saw many question related to this one but none solved my problem yet so I apologize if it was duplicated.
I'm creating a contact book. I've created a fragment to display all contacts.
Now what I want to do is to created an imageview (Call Button) to enable calling the contact when clicked.
I keep getting the error (No Activity found to handle Intent { act android.intent.action.CALL }and when I run on my device it crashed although I've added the intent to the manifest.
What am I doing wrong ?
Fragment Class:
public class DetailFragment extends Fragment
implements LoaderManager.LoaderCallbacks<Cursor> {
public interface DetailFragmentListener {
void onContactDeleted();
void onEditContact(Uri contactUri);
}
private static final int CONTACT_LOADER = 0;
private DetailFragmentListener listener; // MainActivity
private Uri contactUri;
private TextView nameTextView;
private TextView phoneTextView;
private TextView emailTextView;
private TextView streetTextView;
private TextView cityTextView;
private TextView stateTextView;
private TextView zipTextView;
private ImageButton callButton; //The image View for the calling
#Override
public void onAttach(Context context) {
super.onAttach(context);
listener = (DetailFragmentListener) context;
}
#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);
streetTextView = (TextView) view.findViewById(R.id.streetTextView);
cityTextView = (TextView) view.findViewById(R.id.cityTextView);
stateTextView = (TextView) view.findViewById(R.id.stateTextView);
zipTextView = (TextView) view.findViewById(R.id.zipTextView);
callButton = (ImageButton) view.findViewById(R.id.callButton);/Get the image view
// load the contact
getLoaderManager().initLoader(CONTACT_LOADER, null, this);
addListenerOnButton(view);//Call the Listener
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);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_edit:
listener.onEditContact(contactUri);
return true;
case R.id.action_delete:
deleteContact();
return true;
}
return super.onOptionsItemSelected(item);
}
private void deleteContact() {
confirmDelete.show(getFragmentManager(), "confirm delete");
}
private final DialogFragment confirmDelete =
new DialogFragment() {
#Override
public Dialog onCreateDialog(Bundle bundle) {
AlertDialog.Builder builder =
new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.confirm_title);
builder.setMessage(R.string.confirm_message);
// provide an OK button that simply dismisses the dialog
builder.setPositiveButton(R.string.button_delete,
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog, int button) {
getActivity().getContentResolver().delete(
contactUri, null, null);
listener.onContactDeleted(); // notify listener
}
}
);
builder.setNegativeButton(R.string.button_cancel, null);
return builder.create(); // return the AlertDialog
}
};
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
CursorLoader cursorLoader;
switch (id) {
case CONTACT_LOADER:
cursorLoader = new CursorLoader(getActivity(),
contactUri,
null,
null,
null,
null);
break;
default:
cursorLoader = null;
break;
}
return cursorLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (data != null && data.moveToFirst()) {
// get the column index for each data item
int nameIndex = data.getColumnIndex(Contact.COLUMN_NAME);
int phoneIndex = data.getColumnIndex(Contact.COLUMN_PHONE);
int emailIndex = data.getColumnIndex(Contact.COLUMN_EMAIL);
int streetIndex = data.getColumnIndex(Contact.COLUMN_STREET);
int cityIndex = data.getColumnIndex(Contact.COLUMN_CITY);
int stateIndex = data.getColumnIndex(Contact.COLUMN_STATE);
int zipIndex = data.getColumnIndex(Contact.COLUMN_ZIP);
// fill TextViews with the retrieved data
nameTextView.setText(data.getString(nameIndex));
phoneTextView.setText(data.getString(phoneIndex));
emailTextView.setText(data.getString(emailIndex));
streetTextView.setText(data.getString(streetIndex));
cityTextView.setText(data.getString(cityIndex));
stateTextView.setText(data.getString(stateIndex));
zipTextView.setText(data.getString(zipIndex));
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
/////Add listener to the image view
public void addListenerOnButton(View v) {
callButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String phone_number = phoneTextView.getText().toString();//nUHA
Intent callIntent =new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse(phone_number));
startActivity(callIntent);
}
});
}
}
This is specifically the part of the on click method
#Override
public void onClick(View arg0) {
String phone_number = phoneTextView.getText().toString();//nUHA
Intent callIntent =new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse(phone_number));
startActivity(callIntent);
My main
public class MainActivity extends AppCompatActivity
implements ContactsFragment.ContactsFragmentListener,
DetailFragment.DetailFragmentListener,
AddEditFragment.AddEditFragmentListener {
public static final String CONTACT_URI = "contact_uri";
private ContactsFragment contactsFragment; // displays contact list
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (savedInstanceState == null &&
findViewById(R.id.fragmentContainer) != null) {
// create ContactsFragment
contactsFragment = new ContactsFragment();
// add the fragment to the FrameLayout
FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragmentContainer, contactsFragment);
transaction.commit(); // display ContactsFragment
}
else {
contactsFragment =
(ContactsFragment) getSupportFragmentManager().
findFragmentById(R.id.contactsFragment);
}
}
#Override
public void onContactSelected(Uri contactUri) {
if (findViewById(R.id.fragmentContainer) != null) // phone
displayContact(contactUri, R.id.fragmentContainer);
else { // tablet
getSupportFragmentManager().popBackStack();
displayContact(contactUri, R.id.rightPaneContainer);
}
}
#Override
public void onAddContact() {
if (findViewById(R.id.fragmentContainer) != null) // phone
displayAddEditFragment(R.id.fragmentContainer, null);
else // tablet
displayAddEditFragment(R.id.rightPaneContainer, null);
}
private void displayContact(Uri contactUri, int viewID) {
DetailFragment detailFragment = new DetailFragment();
Bundle arguments = new Bundle();
arguments.putParcelable(CONTACT_URI, contactUri);
detailFragment.setArguments(arguments);
FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();
transaction.replace(viewID, detailFragment);
transaction.addToBackStack(null);
transaction.commit(); // causes DetailFragment to display
}
private void displayAddEditFragment(int viewID, Uri contactUri) {
AddEditFragment addEditFragment = new AddEditFragment();
if (contactUri != null) {
Bundle arguments = new Bundle();
arguments.putParcelable(CONTACT_URI, contactUri);
addEditFragment.setArguments(arguments);
}
FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();
transaction.replace(viewID, addEditFragment);
transaction.addToBackStack(null);
transaction.commit(); // causes AddEditFragment to display
}
#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);
}
}
}
My Manifest
<uses-permission android:name="android.permission.CALL_PHONE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.CALL"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
<provider
android:name=".data.AddressBookContentProvider"
android:authorities="com.deitel.addressbook.data"
android:enabled="true"
android:exported="false" >
</provider>
</application>
</manifest>
Use
Uri.parse("tel:" + phone_number)
instead of
Uri.parse(phone_number)

Android Fragment initialization to various Custom Fragments, but only One at a time

I am trying to initialize a generic fragment in such manner that it can be used globally no matter what the instance of it is. For example:
public MainActivity extends Activity{
private Fragment fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first_layout);
FragmentManager fragManager = getFragmentManager();
FragmentTransaction transaction = fragManager.beginTransaction();
if(condition1){
fragment = new MyFirstFragment();
transaction
.add(R.id.registrationFragment, fragment); //registrationFragment is FrameLayout
transaction.commit();
}else if(condition2){
fragment = new MySecondFragment();
transaction
.add(R.id.registrationFragment, fragment); //registrationFragment is FrameLayout
transaction.commit();
}
//create intent filter
//create MyBroadcast object
//registerReceiver(receiverObject, intentFilter)
}
//Some action happens
class MyBroadcast extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(action1)) {
fragment.performAction();
}
}
}
public class MyFirstFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(
R.layout.fragment_holder_a, container, false);
//setWidgets etc...
// TODO Auto-generated method stub
return view;
}
//Used from main
public void performAction(String text){
//set some TextView's text from MainActivity event
//different from MySecondFragment performAction method
}
}
public class MySecondFragmentFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(
R.layout.fragment_holder_b, container, false);
//setWidgets etc...
// TODO Auto-generated method stub
return view;
}
//Used from main
public void performAction(String text){
//set some TextView's text from MainActivity event
//different from MyFirstFragment performAction method
}
}
The problem is that in my real application I may have more than 2 Fragments that the Fragment object could become an instance of. I am trying to avoid a lot of if statements to check which fragment instance was inflated with the FragmentManager. Also the problem I am facing is that When i declare the Fragment fragment = new MyFirstFragment(); I cannot access the fragment.performAction("Stringssss") method. This is not the solution I am looking for:
public MainActivity extends Activity{
private MyFirstFragment myFirstFrag;
private MySecondFragment mySecondFrag;
private MyThirdFragment myThirdFrag;
private MyNthFragment myNthFrag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first_layout);
FragmentManager fragManager = getFragmentManager();
FragmentTransaction transaction = fragManager.beginTransaction();
if(condition1){
myFirstFrag = new MyFirstFragment();
transaction
.add(R.id.registrationFragment, myFirstFrag); //registrationFragment is FrameLayout
transaction.commit();
}else if(condition2){
mySecondFrag = new MySecondFragment();
transaction
.add(R.id.registrationFragment, mySecondFrag); //registrationFragment is FrameLayout
transaction.commit();
}else if(condition3){
//...
}else if(conditionNth){
//...
}
//create intent filter
//create MyBroadcast object
//registerReceiver(receiverObject, intentFilter)
}
//Some action happens
class MyBroadcast extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(action1)) {
if(null != myFirstFrag)
myFirstFrag.performAction();
}else if(null != mySecondFrag){
mySecondFrag.performAction();
}else if(null != myThirdFrag){
myThirdFrag.performAction();
}else if(null != myNthFrag){
myNthFrag.performAction();
}
}else if(action.equals(actionNTH)){
if(null != myFirstFrag)
myFirstFrag.performAction();
}else if(null != mySecondFrag){
mySecondFrag.performAction();
}else if(null != myThirdFrag){
myThirdFrag.performAction();
}else if(null != myNthFrag){
myNthFrag.performAction();
}
}
}
}
As you can see in the BroadcastReceiver a lot of If-else statements start to pile up making the code clunky and dirty. I am looking for a clean solution that will not require me to have a bunch of if-else statements and keep the code simple.
Thank you.

Android ListFragment - onListItemClick start another fragment

Though it seems an easy problem, I've been stuck for quite a few hours. If anyone can help my out providing some code it'd be great. So there it goes my question.
There's a MainActivity which has an ActionBar with two buttons. Each button starts a ListFragment when it's clicked. Then each item of each ListFragment starts another fragment (that's what I'm not able to achieve). Here is the code for the MainActivity:
public class MainActivity extends Activity implements
DataListFragment.DataListSelectionListener {
private final String TAG = "MainActivity";
// Reference the buttons in the ActionBar
private Button actionBarData;
private Button actionBarElu;
private Button actionBarOptions;
// Reference the ListFragments
DataListFragment dataListFragment;
EluListFragment eluListFragment;
// Reference the fragments related to the listItems
SectionTypeFragment sectionTypeFragment;
SectionDimensionsFragment sectionDimensionsFragment;
MaterialsFragment materialsFragment;
ReinforcementFragment reinforcementFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Inflate the custom layout for the ActionBar
final ViewGroup actionBarLayout = (ViewGroup) getLayoutInflater().inflate(
R.layout.action_bar,
null);
// Set the custom ActionBar
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setCustomView(actionBarLayout);
// ActionBar Customization with buttons
final int actionBarColor = getResources().getColor(R.color.blue_2);
actionBar.setBackgroundDrawable(new ColorDrawable(actionBarColor));
actionBarData = (Button) findViewById(R.id.action_bar_data);
actionBarData.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
Log.i(TAG, "DATA button clicked.");
clickActionBarButton(v);
}
});
actionBarElu = (Button) findViewById(R.id.action_bar_elu);
actionBarElu.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(TAG, "ELU button clicked.");
clickActionBarButton(v);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_bar_data) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void clickActionBarButton(View v){
// Get a reference to the FragmentManager
FragmentManager fragmentManager = getFragmentManager();
// Begin a new FragmentTransaction
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// Create the fragment depending on the button pressed
if(v == actionBarData){
// If there is no FeedFragment instance, then create one
if(sectionTypeFragment == null)
dataListFragment = new DataListFragment();
// Replace the main_frame_layout with the sectionTypeFragment
fragmentTransaction.replace(R.id.main_frame_layoout, dataListFragment);
}else if(v == actionBarElu){
// If there is no FeedFragment instance, then create one
if(sectionTypeFragment == null)
eluListFragment = new EluListFragment();
// Replace the main_frame_layout with the sectionTypeFragment
fragmentTransaction.replace(R.id.main_frame_layout, eluListFragment);
}
// Commit the FragmentTransaction
fragmentTransaction.commit();
}
// Called when the user selects an item in the DataListFragment
public void onDataListSelection(int index){
// Get a reference to the FragmentManager
FragmentManager fragmentManager = getFragmentManager();
// Begin a new FragmentTransaction
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// Add the fragment related to the selected item in the List
switch (index){
case 0:
// If there is no SectionTypeFragment instance, then create one
if(sectionTypeFragment == null)
sectionTypeFragment = new SectionTypeFragment();
// Replace the main_frame_layout with the sectionTypeFragment
fragmentTransaction.replace(R.id.main_frame_layout, sectionTypeFragment);
// Add this FragmentTransaction to the backstack
fragmentTransaction.addToBackStack(null);
break;
case 1:
...
}
// Commit the FragmentTransaction
fragmentTransaction.commit();
}
}
Here is the code for one of the ListFragments (DataListFragment):
public class DataListFragment extends ListFragment {
private static final String TAG = "DataFragment";
// List items
private String[] listItems;
private DataListSelectionListener mListener = null;
// Callback interface that allows this Fragment to notify the MainActivity when
// user clicks on a DataList Item
public interface DataListSelectionListener {
public void onDataListSelection(int index);
}
// Called when the user selects an item from the DataList
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Indicates the selected item has been checked
getListView().setItemChecked(position, true);
// Inform the MainActivity that an item has been selected
mListener.onDataListSelection(position);
}
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
// Get the the items to show in the List from the strings.xml
listItems = getResources().getStringArray(R.array.data_list_array);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, listItems);
setListAdapter(adapter);
}
}
Here is the exception:
03-12 14:39:38.681 29515-29515/com.tari.rcsec E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:3459)
at android.view.ViewGroup.addView(ViewGroup.java:3330)
at android.view.ViewGroup.addView(ViewGroup.java:3275)
at android.view.ViewGroup.addView(ViewGroup.java:3251)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:840)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1035)
at android.app.BackStackRecord.run(BackStackRecord.java:635)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1397)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:426)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5022)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1032)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:790)
at dalvik.system.NativeStart.main(Native Method)

how to pass the data in between activity to fragment using bundle in android

I can store the value in one variable. Now I want pass that variable into a fragment
Using the code below, I am able to load fragments:
public class AndroidListFragmentActivity extends Activity {
Fragment2 f2;
public static String itemname;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.apetiserfragement);
itemname=getIntent().getStringExtra("itemname");
Bundle args=new Bundle();
args.putString("itemname", itemname);
f2=new Fragment2();
f2.setArguments(args);
}
} /* (Here I load fragment using xml page) itemname */
The output is splitted into 2 windows one for extend for listfragment (for listview) and one for fragments.
Fragment2.xml
public class Fragment2 extends Fragment {
String itemname;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
System.out.println(getArguments().getString("itemname"));
return inflater.inflate(R.layout.fragment2, container, false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
}
AndroidListFragmentActivity in this class itemname I want pass Fragment2.class.. please help me
If both fragment are on other activity then can use intent
if on same activity then can do operation on that particular activity
as in this link
see onListItemClick of class TitlesFragment
**
* Helper function to show the details of a selected item, either by
* displaying a fragment in-place in the current UI, or starting a
* whole new activity in which it is displayed.
*/
void showDetails(int index) {
mCurCheckPosition = index;
if (mDualPane) {//<---------------------f on same activity then can do operation on that particular fragment
// We can display everything in-place with fragments, so update
// the list to highlight the selected item and show the data.
getListView().setItemChecked(index, true);
// Check what fragment is currently shown, replace if needed.
DetailsFragment details = (DetailsFragment) //<------------------------see use getFragmentManager
getFragmentManager().findFragmentById(R.id.details);
if (details == null || details.getShownIndex() != index) {
// Make new fragment to show this selection.
details = DetailsFragment.newInstance(index);
// Execute a transaction, replacing any existing fragment
// with this one inside the frame.
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.details, details);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
} else { //<----------If both fragment are on other activity then can use intent
// Otherwise we need to launch a new activity to display
// the dialog fragment with selected text.
Intent intent = new Intent();
intent.setClass(getActivity(), DetailsActivity.class);
intent.putExtra("index", index);
startActivity(intent);
}
See this response here : data sharing between fragments and activity in android

Categories

Resources