How to Save the last Fragment? - java

I have three Fragments and I have two buttons on main Activity b1 called next button and b2 called previous button when app is starting its show me blank Fragment , when click on b1 its show me XFragment called page 1 ,when click on b1 its show me YFragment called page 2 , I want when re-open app its show me the last Fragment has been opend ,I know should use shareprefrences but I dont know how to add it to this code
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void b1(View view) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
XFragment fragment = new XFragment();
ft.replace(R.id.mainfragment,fragment);
ft.commit();
}
public void b2(View view) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
YFragment fragment = new YFragment();
ft.replace(R.id.mainfragment,fragment);
ft.commit();
}
}

Below is your required code using SharedPreference.
public class MainActivity extends AppCompatActivity {
SharedPreference pref;
Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
editor = pref.edit();
int fragment_number=pref.getInt("fragment_number", -1); // getting Integer
if(int==1){
//start first fragment
}
if(int==2){
//start second fragment
}
}
public void b1(View view) {
editor.putInt("fragment_number", 1);
editor.apply();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
XFragment fragment = new XFragment();
ft.replace(R.id.mainfragment,fragment);
ft.commit();
}
public void b2(View view) {
editor.putInt("fragment_number", 2);
editor.apply();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
YFragment fragment = new YFragment();
ft.replace(R.id.mainfragment,fragment);
ft.commit();
}
}

Related

How to replace fragment onclick of button inside if condition true?

fragment replacement not working if i put if condition in below code..
_doneButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View _view) {
Name(no.getText().toString(), pass.getText().toString());
if(loginsucess){
android.support.v4.app.FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
MainFragment mainFragment = new MainFragment();
ft.replace(R.id.content, mainFragment);
ft.addToBackStack(null);
ft.commit();
}
_doneButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View _view) {
if(true){
Name(no.getText().toString(), pass.getText().toString());
android.support.v4.app.FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
MainFragment mainFragment = new MainFragment();
ft.replace(R.id.content, mainFragment);
ft.addToBackStack(null);
ft.commit();
}
Try this
if(loginsucees){
android.support.v4.app.FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
MainFragment mainFragment = new MainFragment();
ft.replace(R.id.content, mainFragment);
ft.addToBackStack(null);
ft.commit();
}
else {
//Do Nothing
}
_doneButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View _view) {
if(loginsucees){
Name(no.getText().toString(), pass.getText().toString());
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
MainFragment mainFragment = new MainFragment();
ft.replace(R.id.content, mainFragment,"main_fragment");
ft.commitAllowingStateLoss();
}
}
});

ListFragment called from Button

This batch of code will place a ListFragment into a LinearLayout that I have selected, and it works fine. The problem I have is that this initiates from onCreate and I would like it to trigger from a Button.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TamInputListFragment lstfragment=(TamInputListFragment)getSupportFragmentManager().findFragmentByTag("lstfragment");
if(lstfragment==null){
lstfragment=new TamInputListFragment();
FragmentTransaction transact=getSupportFragmentManager().beginTransaction();
transact.add(R.id.fragment_container,lstfragment,"lstfragment");
transact.commit();
}
This batch of code worked for a previous tutorial that just interchanged two simple Fragment with two separate Button.
public void selectFrag(View view){
Fragment fr;
if (view == findViewById(R.id.button2)) {
fr = new FragmentTwo();
}
else {
fr = new FragmentOne();
}
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);
fragmentTransaction.commit();
}
But when I use this same batch of code and swap out FragmentOne() and FragmentTwo() for the two new ListFragment classes that I have made, TamInputListFragment and VerbInputListFragment, I get an "Incompatible Type" error saying that is wants a android.app.Fragment and not a com.example.petakirikiri.fragmenttest.Fragments.TamInputListFragment();
public void selectFrag(View view){
Fragment fr;
if (view == findViewById(R.id.verb_button) {
fr = new TamInputListFragment();
}
else {
fr = new VerbInputListFragment();
}
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fr);
fragmentTransaction.commit();
}

How To Make Tabs in Navigation Drawer

I create Navigation Drawer using fragments and Action Bar Tabs using Fragment. But when I compile it, I am having issue. My app unfortunately stop working. My code wasn't error, and I am so confused whats wrong?
MainActivity.java
public class MainActivity extends FragmentActivity {
// Within which the entire activity is enclosed
private DrawerLayout mDrawerLayout;
// ListView represents Navigation Drawer
private ListView mDrawerList;
// ActionBarDrawerToggle indicates the presence of Navigation Drawer in the action bar
private ActionBarDrawerToggle mDrawerToggle;
// Title of the action bar
private String mTitle = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = "Sistem Pakar Ayam";
getActionBar().setTitle(mTitle);
// Getting reference to the DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.drawer_list);
// Getting reference to the ActionBarDrawerToggle
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
/** Called when drawer is closed */
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
/** Called when a drawer is opened */
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle("Sistem Pakar Ayam");
invalidateOptionsMenu();
}
};
// Setting DrawerToggle on DrawerLayout
mDrawerLayout.setDrawerListener(mDrawerToggle);
// Creating an ArrayAdapter to add items to the listview mDrawerList
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(),
R.layout.drawer_list_item, getResources().getStringArray(R.array.menus));
// Setting the adapter on mDrawerList
mDrawerList.setAdapter(adapter);
// Enabling Home button
getActionBar().setHomeButtonEnabled(true);
// Enabling Up navigation
getActionBar().setDisplayHomeAsUpEnabled(true);
// Setting item click listener for the listview mDrawerList
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Getting an array of rivers
String[] menuItems = getResources().getStringArray(R.array.menus);
// Currently selected river
mTitle = menuItems[position];
if (mTitle.equals("Beranda")){
FragmentHome fragmenthome = new FragmentHome();
FragmentManager fragmentManager = getFragmentManager();
// Creating a fragment transaction
FragmentTransaction ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
ft.replace(R.id.content_frame, fragmenthome);
// Committing the transaction
ft.commit();
}
else if (mTitle.equals("Diagnosis")){
FragmentDiagnosis fragmentdiagnosis = new FragmentDiagnosis();
FragmentManager fragmentManager = getFragmentManager();
// Creating a fragment transaction
FragmentTransaction ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
ft.replace(R.id.content_frame, fragmentdiagnosis);
// Committing the transaction
ft.commit();
}
else if (mTitle.equals("Data Penyakit")){
FragmentPenyakit fragmentpenyakit = new FragmentPenyakit();
FragmentManager fragmentManager = getFragmentManager();
// Creating a fragment transaction
FragmentTransaction ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
ft.replace(R.id.content_frame, fragmentpenyakit);
// Committing the transaction
ft.commit();
}
else if (mTitle.equals("Bantuan")){
FragmentBantuan fragmentbantuan = new FragmentBantuan();
FragmentManager fragmentManager = getFragmentManager();
// Creating a fragment transaction
FragmentTransaction ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
ft.replace(R.id.content_frame, fragmentbantuan);
// Committing the transaction
ft.commit();
}
else if (mTitle.equals("Tentang")){
FragmentTentang fragmenttentang = new FragmentTentang();
FragmentManager fragmentManager = getFragmentManager();
// Creating a fragment transaction
FragmentTransaction ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
ft.replace(R.id.content_frame, fragmenttentang);
// Committing the transaction
ft.commit();
}
// Closing the drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
});
//Menampilkan Fragment Home yang Tampil Pertama Kali
FragmentHome fragmenthome = new FragmentHome();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.content_frame, fragmenthome);
ft.commit();
getActionBar().setTitle("Beranda");
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/** Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.menu_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Apa kalian ingin Keluar?")
.setCancelable(false)
.setPositiveButton("Ya", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.this.finish();
}
})
.setNegativeButton("Tidak", null)
.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
FragmentTentang.java
public class FragmentTentang extends Fragment {
ViewPager mViewPager;
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_fragment_tentang, container, false);
return v;
}
#Override
public void onCreate(Bundle savedInstanceState) {
final ActionBar actionBar = getActivity().getActionBar();
// Specify that tabs should be displayed in the action bar.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create a tab listener that is called when the user changes tabs.
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
};
// Add 3 tabs, specifying the tab's text and TabListener
for (int i = 0; i < 3; i++) {
actionBar.addTab(
actionBar.newTab()
.setText("Aplikasi" + (i + 1))
.setTabListener(tabListener));
}
for (int i = 1; i < 3; i++) {
actionBar.addTab(
actionBar.newTab()
.setText("Pengembang" + (i + 1))
.setTabListener(tabListener));
}
for (int i = 2; i < 3; i++) {
actionBar.addTab(
actionBar.newTab()
.setText("Coba" + (i + 1))
.setTabListener(tabListener));
}
}
}
I want my app like this image.
Tentang

How to add/remove Fragment on Button click?

At present I have got a "RELATIVE_LAYOUT" container which I am using for adding my fragment.
I am using OnClickListener on a button to load the fragment XML layout into the RelativeLayout container.
What I want to achieve is that when I press the button once, the fragment should load...and when I press it again the fragment should be removed. I've already tried using integer to identify if fragment is loaded, but failed.
Any help Appreciated...
CODE:
public class MainActivity extends Activity {
Button B1,B2;
int boolb1=0, boolb2=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
B1 = (Button)findViewById(R.id.btn1);
B2 = (Button)findViewById(R.id.btn2);
B1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
FragmentOne f1 = new FragmentOne();
if(boolb1==0)
{ft.add(R.id.frg1, f1);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
boolb1=1;}
else
{ft.remove(f1);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
boolb1=0;}
//ft.addToBackStack("f1");
ft.commit();
}
});
B2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
FragmentTwo f2 = new FragmentTwo();
if(boolb2==0) {
ft.add(R.id.frg2, f2);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
boolb2=1;
} else {
ft.remove(f2);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
boolb2=0;
}
//ft.addToBackStack("f2");
ft.commit();
}
});
}
Your issue is that you create a new Fragment everytime you click the Button. You need to get a reference to the currently added Fragment and then remove that one.
Furthermore, you no longer need to use the flag.
When adding the Fragment, you can tag it. Upon removing the Fragment, you can use the tag used for adding the Fragment to get a reference to the currently added Fragment.
Here is an example of how you should do it:
private Button B1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
B1 = (Button)findViewById(R.id.btn1);
B1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
FragmentOne f = (FragmentOne) fm.findFragmentByTag("tag");
if(f == null) { // not added
f = new FragmentOne();
ft.add(R.id.frg1, f, "tag");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
} else { // already added
ft.remove(f);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
}
ft.commit();
}
});
// and so on ...
}

SlidingMenu with ViewPager and ActionBarSherlock Tabs

In my calendar application, I am using ActionBarSherlock to display two tabs - 1) Calendar 2) Converter. On the click event of an ActionBar menu item, I'm using SlidingMenu drawer to display event summary for that month.
I want to use viewpager specifically for the Calendar tab and I have implemented it this way:
Main.java:
public class BaseActivity extends SlidingSherlockFragmentActivity
{
private ViewPager pager;
CalendarFragmentPagerAdapter mPagerAdapter;
private static final int MONTHS_LIMIT = 5;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.app_name);
setContentView(R.layout.main);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main, new CalendarFragment())
.commit();
setBehindContentView(R.layout.content_frame);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, new EventsSummary())
.commit();
setSlidingActionBarEnabled(false);
final ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setHomeButtonEnabled(true);
ActionBar.Tab calendar = bar.newTab();
ActionBar.Tab converter = bar.newTab();
calendar.setText(this.getResources().getString(R.string.calendar));
converter.setText(this.getResources().getString(R.string.converter));
calendar.setTabListener(new MyTabListener());
converter.setTabListener(new MyTabListener());
bar.addTab(calendar);
bar.addTab(converter);
// customize the SlidingMenu
SlidingMenu sm = getSlidingMenu();
sm.setShadowWidthRes(R.dimen.shadow_width);
sm.setShadowDrawable(R.drawable.shadow);
sm.setBehindOffsetRes(R.dimen.actionbar_home_width);
sm.setSlidingEnabled(false);
mPagerAdapter = new CalendarFragmentPagerAdapter(getSupportFragmentManager());
pager = (ViewPager) this.findViewById(R.id.viewpager);
pager.setAdapter(mPagerAdapter);
pager.setCurrentItem(MONTHS_LIMIT / 2);
}
private class MyTabListener implements ActionBar.TabListener
{
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if(tab.getPosition()==0)
{
CalendarFragment frag = new CalendarFragment();
ft.replace(R.id.main, frag);
}
else
{
ConverterFragment frag = new ConverterFragment();
ft.replace(R.id.main, frag);
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
public boolean onOptionsItemSelected(MenuItem item) {
Intent newActivity;
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_slidingmenu:
toggle();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public class CalendarFragmentPagerAdapter extends FragmentPagerAdapter {
public CalendarFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
CalendarFragment fragment = new CalendarFragment();
Bundle args = new Bundle();
args.putInt("offset", position - MONTHS_LIMIT / 2);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return MONTHS_LIMIT;
}
}
}
CalendarFragment.java:
public class CalendarFragment extends Fragment
{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
int offset = args.getInt("offset"); //throws NullPointerException
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.simple_calendar_view, container, false);
.....
return v;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("dummy", true);
}
}
The problem is at this line in the CalendarFragment:
int offset = args.getInt("offset");
It throws the error NullPointerException and debugging shows this is because Bundle args = getArguments() is null.
I tried to put the breakpoint at this line in the PagerAdapter:
Bundle args = new Bundle();
but it never reaches here and the application crashes throwing the NullPointerException.
Where am I going wrong?
Here
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main, new CalendarFragment())
.commit();
and here
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (tab.getPosition() == 0) {
CalendarFragment frag = new CalendarFragment();
ft.replace(R.id.main, frag);
} else {
ConverterFragment frag = new ConverterFragment();
ft.replace(R.id.main, frag);
}
}
you're just creating an empty CalendarFragment instance without any arguments.
So your activity launches, creating an empty Fragment without arguments, and then crashes when trying to get those

Categories