How to send data From activity to Fragment Activity? - android

I have referred many code on this question , but can not get any help for my problem.
This is My code from where I want to send data to previous FragmentActivity:
public class AddTask extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_task);
ImageButton position = (ImageButton) findViewById(R.id.select_position);
position.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent m = new Intent().setClass(getApplicationContext(),
MapActivity.class);
startActivity(m);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_add_task, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.accept:
FinishActivity();
finish();
break;
case R.id.cancle:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
protected void FinishActivity() {
EditText activity = (EditText) findViewById(R.id.activity_name);
EditText description = (EditText) findViewById(R.id.description);
EditText address = (EditText) findViewById(R.id.address);
Bundle bundle = new Bundle();
bundle.putString("activity", activity.getText().toString());
if (activity.toString().isEmpty() || description.toString().isEmpty()
|| address.toString().isEmpty()) {
Toast.makeText(this, "Field must not be empty", Toast.LENGTH_LONG)
.show();
}
}
}
Can anyone tell me What to use in this code to send data, I have used Fragment class to send it but it make error in Activity.

Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and in Fragment onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
return inflater.inflate(R.layout.fragment, container, false);
}

Related

Bundle from main activity to fragment

i m following some guide to pass parameter from login to one fragment.
I have this structure (login page, user area (main activity that cointain only a fragment and some fragment)
I try to do this :
public class UserAreaActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener{
ProgressDialog progressDialog;
#Override
public void onBackPressed() {
//super.onBackPressed();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.example.anto.fitfix.R.layout.activity_user_area);
Bundle b = getIntent().getExtras();
final String name = b.getString("name");
final String user = b.getString("id");
final String email = b.getString("email");
final String gender = b.getString("gender");
final String photourl= b.getString("photo");
final String birthday = b.getString("birthday");
final String p="null";
Log.d("nome",""+name);
// loadFragment(new fragment_home());
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt("name", 123);
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new fragment_home()).commit();
BottomNavigationView navigation = findViewById(R.id.navigationView);
navigation.setOnNavigationItemSelectedListener(this);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
fragment_home fragment = null;
switch (item.getItemId()) {
case R.id.action_home:
fragment = new fragment_home();
break;
case R.id.action_cron:
fragment = new fragment_home();
break;
case R.id.action_face:
// fragment = new NotificationsFragment();
break;
}
return loadFragment(fragment);
}
private boolean loadFragment(android.support.v4.app.Fragment fragment) {
//switching fragment
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
return true;
}
return false;
}
}
and this for fragment
public class fragment_home extends Fragment {
ProgressDialog progressDialog;
String name,email,user,p;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//just change the fragment_dashboard
//with the fragment you want to inflate
//like if the class is HomeFragment it should have R.layout.home_fragment
//if it is DashboardFragment it should have R.layout.fragment_dashboard
View view = inflater.inflate(R.layout.fragment_home, container, false);
TextView tResult = (TextView) view.findViewById(R.id.tResult);
TextView tMail = (TextView) view.findViewById(com.example.anto.fitfix.R.id.tMail);
TextView tAge = (TextView) view.findViewById(R.id.tAge);
Bundle bundle = this.getArguments();
if (bundle != null) {
int myInt = bundle.getInt("name");
Log.d("name",""+myInt);
tResult.setText(name);
}
BLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("wait..."); // Setting Message
progressDialog.setTitle("Logout"); // Setting Title
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner
progressDialog.show(); // Display Progress Dialog
progressDialog.setCancelable(false);
new Thread(new Runnable() {
public void run() {
try {
disconnectFromFacebook();
Thread.sleep(1600);
Intent fbIntent = new Intent(getActivity(), LoginActivity.class);
getActivity().startActivity(fbIntent);
} catch (Exception e) {
e.printStackTrace();
}
progressDialog.dismiss();
}
}).start();
}
});
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
} catch (JSONException e) {
e.printStackTrace();
}
}
};
/* FbActivity registerRequest = new FbActivity(name, user, p, email, responseListener);
RequestQueue queue = Volley.newRequestQueue(getActivity());
queue.add(registerRequest);*/
return view;
}
}
I recived the name from login , but i cant pass in fragment section..
Someone can give me the suggestion?
When you pass a bundle to fragment, you do not create an object of Fragment class, but instead you create the object of the fragment you created i.e fragment_home
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt("name", 123);
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new fragment_home()).commit();
Change the above code with the code below
fragment_home fragment = new fragment_home();
Bundle bundle = new Bundle();
bundle.putInt("name", 123);
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit();

Make back button returns from an activity to a fragment in Android

I'm developing an Android application and I have a fragment called "More", in this fragment I have such things as "About Us", "Terms and Conditions", that are normal activities. What I want to do is, when I click on the back button inside the, for example, the about us Activity I want to return to the "More" fragment. How can I do that? This is what I have in the aboutUs activity:
The "onBackPressed method was supposed to go back to the fragment once I click on the back button, but it is not working. The application crashes and in the log cat is says "Have you declare the MoreFragment Activity in the manifest?", but I tried to declare and it doesn't work.
public class AboutUs extends BaseActivity {
private ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about_us);
image = (ImageView) findViewById(R.id.imageView2);
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent launchactivity = new Intent(AboutUs.this, StartScreenActivity.class);
startActivity(launchactivity);
}
});
}
#Override
public void onBackPressed()
{
Intent intent = new Intent(this,MoreFragment.class);
startActivity(intent);
}
}
This is the fragment that calls the Activity:
public class MoreFragment extends Fragment implements View.OnClickListener {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_more, null, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView lbl1 = (TextView) view.findViewById(R.id.lbl1);
TextView lbl2 = (TextView) view.findViewById(R.id.lbl2);
TextView lbl3 = (TextView) view.findViewById(R.id.lbl3);
TextView lbl4 = (TextView) view.findViewById(R.id.lbl4);
TextView lbl5 = (TextView) view.findViewById(R.id.lbl5);
TextView lbl6 = (TextView) view.findViewById(R.id.lbl6);
TextView lbl7 = (TextView) view.findViewById(R.id.lbl7);
TextView lbl8 = (TextView) view.findViewById(R.id.lbl8);
TextView lbl9 = (TextView) view.findViewById(R.id.lbl9);
ImageView imv1 = (ImageView) view.findViewById(R.id.imv1);
ImageView imv2 = (ImageView) view.findViewById(R.id.imv2);
ImageView imv3 = (ImageView) view.findViewById(R.id.imv3);
ImageView imv4 = (ImageView) view.findViewById(R.id.imv4);
ImageView imv5 = (ImageView) view.findViewById(R.id.imv5);
ImageView imv6 = (ImageView) view.findViewById(R.id.imv6);
ImageView imv7 = (ImageView) view.findViewById(R.id.imv7);
ImageView imv8 = (ImageView) view.findViewById(R.id.imv8);
ImageView imv9 = (ImageView) view.findViewById(R.id.imv9);
ImageView imv10 = (ImageView) view.findViewById(R.id.imv10);
TextView btnSignOut = (TextView) view.findViewById(R.id.lbl10);
lbl1.setOnClickListener(this);
lbl2.setOnClickListener(this);
lbl3.setOnClickListener(this);
lbl4.setOnClickListener(this);
lbl5.setOnClickListener(this);
lbl6.setOnClickListener(this);
lbl7.setOnClickListener(this);
lbl8.setOnClickListener(this);
lbl9.setOnClickListener(this);
imv1.setOnClickListener(this);
imv2.setOnClickListener(this);
imv3.setOnClickListener(this);
imv4.setOnClickListener(this);
imv5.setOnClickListener(this);
imv6.setOnClickListener(this);
imv7.setOnClickListener(this);
imv8.setOnClickListener(this);
imv9.setOnClickListener(this);
btnSignOut.setOnClickListener(this);
View view9 = view.findViewById(R.id.view9);
View view8 = view.findViewById(R.id.view8);
if (!PrefernceHelper.getBoolean(getActivity(), Commons.Constants.USERLOGGEDIN)) {
imv8.setVisibility(View.INVISIBLE);
lbl8.setVisibility(View.INVISIBLE);
imv10.setVisibility(View.INVISIBLE);
btnSignOut.setVisibility(View.INVISIBLE);
view9.setVisibility(View.INVISIBLE);
view8.setVisibility(View.INVISIBLE);
}
}
private void callAllMoreScreen(String type, Class<?> className) {
Intent intent = new Intent();
intent.setClass(getActivity(), className);
intent.putExtra(Commons.Constants.LOAD_TYPE_URL, type);
getActivity().startActivity(intent);
}
private void callAllMoreScreen1(Class<?> className) {
Intent intent = new Intent();
intent.setClass(getActivity(), className);
getActivity().startActivity(intent);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.lbl1:
callAllMoreScreen1(AboutUs.class);
break;
case R.id.lbl2:
callAllMoreScreen("contact-us", AllMoreScreenActivity.class);
break;
case R.id.lbl3:
callAllMoreScreen1(TermsConditions.class);
break;
case R.id.lbl4:
callAllMoreScreen1(PrivacyPolicy.class);
break;
case R.id.lbl5:
callAllMoreScreen("faqs", AllMoreScreenActivity.class);
break;
case R.id.lbl6:
callAllMoreScreen("how-it-work", AllMoreScreenActivity.class);
break;
case R.id.lbl7:
callAllMoreScreen("about-foodlebee", AllMoreScreenActivity.class);
break;
case R.id.lbl8:
callAllMoreScreen(" ", PredefinedAddressActivity.class);
break;
case R.id.lbl9:
callAllMoreScreen(" ", TrackyourorderActivity.class);
break;
case R.id.imv1:
callAllMoreScreen1(AboutUs.class);
break;
case R.id.imv2:
callAllMoreScreen("contact-us", AllMoreScreenActivity.class);
break;
case R.id.imv3:
callAllMoreScreen1(TermsConditions.class);
break;
case R.id.imv4:
callAllMoreScreen1(PrivacyPolicy.class);
break;
case R.id.imv5:
callAllMoreScreen("faqs", AllMoreScreenActivity.class);
break;
case R.id.imv6:
callAllMoreScreen("how-it-work", AllMoreScreenActivity.class);
break;
case R.id.imv7:
callAllMoreScreen("about-foodlebee", AllMoreScreenActivity.class);
break;
case R.id.imv8:
callAllMoreScreen(" ", PredefinedAddressActivity.class);
break;
case R.id.imv9:
callAllMoreScreen(" ", TrackyourorderActivity.class);
break;
case R.id.lbl10:
PrefernceHelper.clearAll(getActivity());
callAllMoreScreen("", SignInActivity.class);
getActivity().finish();
break;
}
}
}
And this is the Activity that call the fragment:
public class TabLayoutScreenActivity extends BaseActivity {
private TabLayout tabLayout;
private Bundle bundle;
//Bundle bundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_screen);
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar); // actionBarSetUp(true);
// getSupportActionBar().setIcon(R.drawable.small_bee);
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// getSupportActionBar().setIcon(R.drawable.ic_launcher);
viewPager.setAdapter(new SectionPagerAdapter(getSupportFragmentManager()));
tabLayout.setupWithViewPager(viewPager);
ImageView foodlebee = (ImageView) findViewById(R.id.imageView2);
foodlebee.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent launchactivity = new Intent(TabLayoutScreenActivity.this,StartScreenActivity.class);
startActivity(launchactivity);
}
});
// bundle = getIntent().getExtras();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_login, menu);
if (PrefernceHelper.getBoolean(this, Commons.Constants.USERLOGGEDIN)) {
MenuItem item = menu.findItem(R.id.user_login);
item.setVisible(false);
invalidateOptionsMenu();
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.user_login) {
intentCall(SignInActivity.class, null, 0);
return true;
} else if (item.getItemId() == R.id.home) {
intentCall(StartScreenActivity.class, null, 0);
finish();
return true;
}
return false;
}
#Override
protected void onStart() {
super.onStart();
bundle = getIntent().getExtras();
int tabPostion = 0;
if (bundle != null)
tabPostion = bundle.getInt(Commons.Constants.TAB_POSITION, 0);
TabLayout.Tab tab = tabLayout.getTabAt(tabPostion);
tab.select();
}
public class SectionPagerAdapter extends FragmentPagerAdapter {
public SectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new ChefFragment();
case 1:
return new OrderFragment();
case 2:
return new BasketFragment();
case 3:
return new MoreFragment();
default:
return new ChefFragment();
}
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Chefs";
case 1:
return "Orders";
case 2:
return "Cart";
case 3:
return "More";
default:
return "Chef";
}
}
}
}
Just finish() the current activity in onbackpressed hence you will return to the more fragment because the previous activity is already on the back stack. You don't need to launch the previous activity again.
Moreover your code is wrong.. you are trying to launch a fragment which is not possible. This is why this exception is thrown.
Change your code like this :
#Override
public void onBackPressed()
{
finish();
}

Is it possible to start a fragment a new fragment activity after a button is pressed?

Just a small question, maybe hard, maybe not.
But just like the title says, is it possible to start a new fragmentActivity after a button pressed?
Now I have been researching this on my own and I rather not start a new activity again, unless I have to ofcourse.
So far I am happy with my results, as I try to make three different fragment packages in one class for 3 different buttons I have.
Thus for short, There are 3 buttons and they need to activate their own Fragment Package.
Here's my current code I want try to fix:
MainActivity:
public class MainActivity extends Activity {
//ViewPager viewpager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* viewpager = (ViewPager)findViewById(R.id.pager);
PagerAdapter padater = new PagerAdapter(getSupportFragmentManager());
viewpager.setAdapter(padater);*/
}
public boolean contentSwitch = false;
#Override
public void onBackPressed() {
if(contentSwitch) {
finish();
Log.i("BtnHandleEvent", "BackButton Pressed!");
Intent startIntent = new Intent(MainActivity.this, MainActivity.class);
startActivity(startIntent);
contentSwitch = false;
} else {
Log.i("Event Handler", "Terminating app!");
Runtime.getRuntime().runFinalization(); //No idea why I did this
Runtime.getRuntime().gc(); //No idea why I did this too
Runtime.getRuntime().exit(1); //Doesn't cleanup?
}
}
//start fragment activity
public void btn1(View v) {
contentSwitch = true;
}
public void btn2(View v) {
contentSwitch = true;
}
public void btn3(View v) {
contentSwitch = true;
}}
FragmentPackage:
public class FragmentPackage extends FragmentPagerAdapter {
public static boolean ViewPackOne = false; //Still to do
//Still need to fix
public FragmentPackage(FragmentManager fm) {
super(fm);
}
public Fragment getItem(int arg0) {
switch(arg0) {
case 0:
if(ViewPackOne) {
return new FragmentOne();
}
case 1:
if(ViewPackOne){
return new FragmentTwo();
}
case 2:
if(ViewPackOne) {
return new FragmentThree();
}
default:
break;
}
return null;
}
public int getCount() {
return 3;
}
public static class FragmentOne extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance){
return inflater.inflate(R.layout.fragment_one_layout, container, false);
}
}
public static class FragmentTwo extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance){
return inflater.inflate(R.layout.fragment_two_layout, container, false);
}
}
public static class FragmentThree extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance){
return inflater.inflate(R.layout.fragment_one_layout, container, false);
}
}
}
FragmentActivity is a sub class of activity so it also has the startActivity() method
Suppose we want to start ActivityB from a Fragment
Intent intent = new Intent(getActivity(), ActivityB.class);
startActivity(intent);
And to start it from the FragmentActivity
Intent intent = new Intent(this, ActivityB.class);
startActivity(intent);

how to set different fragments upon different button clicks

I am using sherlock library. My problem is i am unable to change fragments on different button clicks.
Here is my code:
public class AmecmainActivity extends FragmentActivity {
private ImageButton legislativebutton;
private ImageButton About;
private ImageButton OutageReport;
private ImageButton ViewPageReportLeft;
private ImageView ViewPageReportRight;
private ImageButton actionnetwork;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.amecmain);
actionnetwork=(ImageButton)findViewById(R.id.Actionnetwork);
actionnetwork.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Bundle b = new Bundle();
b.putString("action", "actionnetwork");
Intent intent = new Intent(v.getContext(),
FragmentChangeActivity.class);
intent.putExtras(b);
startActivity(intent);
}
});
ViewPageReportLeft.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Bundle b = new Bundle();
b.putString("html", "htmlcontent");
Intent intent = new Intent(v.getContext(),
FragmentChangeActivity.class);
intent.putExtras(b);
startActivity(intent);
}
});
}
In this I'm using a common functionality
public class FragmentChangeActivity extends SlidingFragmentActivity {
private Fragment mContent;
public FragmentChangeActivity() {
super();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent in = getIntent();
Bundle b = in.getExtras();
String name= b.getString("action");
//Here i am getting the values through intent so that i can give that name
// set the fragment.
// set the Above View
if (savedInstanceState != null)
mContent = getSupportFragmentManager().getFragment(b, "action");
if (mContent==name)// Here i am setting fragments i dnot know to check the
// condition here mContent is fragment and i am giving
// string how to check the condition.
mContent = new Fragment1(); //here i am setting fragment
// set the Above View
setContentView(R.layout.content_frame);
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, mContent).commit();
// set the Behind View
setBehindContentView(R.layout.menu_frame);
getSupportFragmentManager().beginTransaction()
.replace(R.id.menu_frame, new ColorMenuFragment()).commit();
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, "mContent", mContent);
}
public void switchContent(Fragment fragment) // Here is switchcontent method which
// will change the fragment content
{
mContent = fragment;
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, fragment).commit();
getSlidingMenu().showContent();
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.menuIcon:
toggle();
break;
case android.R.id.home:
getFragmentManager().executePendingTransactions();
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

Android: fragment restore after screen orientation change

I'm starting with fragments and I'm facing a problem. I wan't to restore my fragment after a screen rotation.
My app looks like this: on landscape I have a button on the left area, which updates the a label on the right area. If on portrait mode, I'm navigating to a new activity. However, I wan't to maintain the fragment state after rotating.
Code looks like this:
Left area fragment:
public class ListFragment extends Fragment implements OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list, container, false);
Button button = (Button) view.findViewById(R.id.button1);
button.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
updateDetail();
break;
}
}
public void updateDetail() {
String newTime = String.valueOf(System.currentTimeMillis());
DetailFragment fragment = (DetailFragment) getFragmentManager()
.findFragmentById(R.id.detailFragment);
if (fragment != null && fragment.isInLayout()) {
fragment.setText(newTime);
} else {
Intent intent = new Intent(getActivity().getApplicationContext(),
DetailActivity.class);
intent.putExtra("value", newTime);
startActivity(intent);
}
}
}
Right area activity:
public class DetailActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
finish();
return;
}
if (savedInstanceState == null) {
setContentView(R.layout.activity_detail);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String s = extras.getString("value");
TextView view = (TextView) findViewById(R.id.detailsText);
view.setText(s);
}
}
}
}
Right area fragment:
public class DetailFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater
.inflate(R.layout.fragment_detail, container, false);
return view;
}
public void setText(String item) {
TextView view = (TextView) getView().findViewById(R.id.detailsText);
view.setText(item);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
FragmentManager fm = getFragmentManager();
DetailFragment fragment = (DetailFragment)fm.findFragmentById(R.id.detailFragment);
if (fragment == null) {
fragment = new DetailFragment();
fragment.setTargetFragment(this, 0);
fm.beginTransaction().add(R.id.detailFragment, fragment).commit();
}
}
}
What can I possibly be doing wrong?
You have a few options you can use the Bundle in a couple of methods to save and restore the state of the fragments.
Or you can possibly use the setRetainInstance method:
onCreate(Bundle save)
{
super.onCreate(save);
setRetainInstance(true);
}
Keep in mind that the setRetainInstance method doesn't work for fragments in the backstack.
#Override
public void onConfigurationChanged(Configuration newConfig) {
int orientation = getResources().getConfiguration().orientation;
switch (orientation) {
case Configuration.ORIENTATION_LANDSCAPE:
getSupportFragmentManager().beginTransaction().replace(R.id.detailFragment, new DetailFragment()).commitAllowingStateLoss();
getSupportFragmentManager().beginTransaction().remove(new DetailFragment()).commitAllowingStateLoss();
break;
case Configuration.ORIENTATION_PORTRAIT:
getSupportFragmentManager().beginTransaction().replace(R.id.detailFragment, new DetailFragment()).commitAllowingStateLoss();
getSupportFragmentManager().beginTransaction().remove(new DetailFragment()).commitAllowingStateLoss();
break;
}
super.onConfigurationChanged(newConfig);
}
You can check on the onConfigurationChange and ensure that your fragment state is not lost by doing a commitAllowingStateLoss

Categories

Resources