I am creating a listview from the contents of my api, if I click on a listview item I want to show a new view with more details for that clicked item, currently the listview gets shown properly but if I click on an item the app crashed and I get this error message:
> java.lang.RuntimeException: Unable to start activity
> ComponentInfo{de.dev.app/de.dev.app.ui.quote.ArticleDetailActivity}:
> java.lang.NullPointerException: Attempt to invoke virtual method
> 'java.lang.String de.dev.app.jokeapp.entities.Joke.getTitle()' on a null
> object reference ... Caused by: java.lang.NullPointerException:
> Attempt to invoke virtual method 'java.lang.String
> de.dev.app.entities.Joke.getTitle()' on a null object reference
> at
> de.dev.app.ui.quote.ArticleDetailFragment.onCreateView(ArticleDetailFragment.java:100)
The error points to this lines in my ArticleDetailFragment.java:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflateAndBind(inflater, container, R.layout.fragment_article_detail);
if (!((BaseActivity) getActivity()).providesActivityToolbar()) {
((BaseActivity) getActivity()).setToolbar((Toolbar) rootView.findViewById(R.id.toolbar));
}
collapsingToolbar.setTitle(jokeItem.getTitle()); // points here
author.setText(jokeItem.getTitle());
quote.setText(jokeItem.getTitle());
jokeHeader.setText(jokeItem.getTitle());
jokeContent.setText(jokeItem.getContent());
return rootView;
}
This is my onAttach method:
#Override
public void onAttach(Context context) {
super.onAttach(context);
Bundle bundle = getArguments();
if(bundle == null) {
getActivity().finish();
return;
}
jokeItem = (Joke)bundle.getSerializable("joke");
}
This is my ArticleDetailFragment looks like:
public class ArticleDetailFragment extends BaseFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments().containsKey(ARG_ITEM_ID)) {
// load dummy item by using the passed item ID.
dummyItem = DummyContent.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID));
}
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
tokenManager = TokenManager.getInstance(preferences);
service = RetrofitBuilder.createServiceWithAuth(ApiService.class, tokenManager);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflateAndBind(inflater, container, R.layout.fragment_article_detail);
if (!((BaseActivity) getActivity()).providesActivityToolbar()) {
// No Toolbar present. Set include_toolbar:
((BaseActivity) getActivity()).setToolbar((Toolbar) rootView.findViewById(R.id.toolbar));
}
collapsingToolbar.setTitle(jokeItem.getTitle());
author.setText(jokeItem.getTitle());
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.sample_actions, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
// your logic
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
Bundle bundle = getArguments();
if(bundle == null) {
getActivity().finish();
return;
}
jokeItem = (Joke)bundle.getSerializable("joke");
}
}
My ArticleDetailActivity
public class ArticleDetailActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
ArticleDetailFragment fragment = ArticleDetailFragment.newInstance(getIntent().getStringExtra(ArticleDetailFragment.ARG_ITEM_ID));
getFragmentManager().beginTransaction().replace(R.id.article_detail_container, fragment).commit();
}
#Override
public boolean providesActivityToolbar() {
return false;
}
}
Calling the ArticleDetailActivity in my ListActivit like this:
public class ListActivity extends BaseActivity implements ArticleListFragment.Callback {
...
#Override
public void onItemSelected(Joke joke) {
Intent detailIntent = new Intent(this, ArticleDetailActivity.class);
// detailIntent.putExtra(ArticleDetailFragment.ARG_ITEM_ID, id);
startActivity(detailIntent);
}
...
Call DetailActivity like this from your ListActvity,
Intent detailIntent = new Intent(this, ArticleDetailActivity.class);
// detailIntent.putExtra(ArticleDetailFragment.ARG_ITEM_ID, id);
Bundle bundle = new Bundle();
bundle.putSerializable("joke", joke);
detailIntent.putExtras(bundle);
startActivity(detailIntent);
and change your ArticleDetailActivity change like this, we need to send data to fragment
public class ArticleDetailActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
// Show the Up button in the action bar.
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
ArticleDetailFragment fragment = new ArticleDetailFragment();
fragment.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().replace(R.id.article_detail_container, fragment).commit();
}
#Override
public boolean providesActivityToolbar() {
return false;
}
}
Add this line of code to your ArticleDetailFragment class
#BindView(R.id.title)
TextView title;
Related
I created my test project where i code to communicate between two fragments but actully I want to access activity from fragment.
Here is code to connect fragment to fragment, its working absolutely right without any error but now i want to change this code to connect activity from fragment instead of fragment to fragment communication.
So Please change this code to access activities from fragment. I stuck on this issue for than a week.So Guys please resolve this.
here is my mainaactivity:
public class MainActivity extends AppCompatActivity implements FragmentA.FragmentAListener, FragmentB.FragmentBListener {
private FragmentA fragmentA;
private FragmentB fragmentB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentA = new FragmentA();
fragmentB = new FragmentB();
getSupportFragmentManager().beginTransaction()
.replace(R.id.container_a, fragmentA)
.replace(R.id.container_b, fragmentB)
.commit();
}
#Override
public void onInputASent(CharSequence input) {
fragmentB.updateEditText(input);
}
#Override
public void onInputBSent(CharSequence input) {
fragmentA.updateEditText(input);
}
Here is my FragmentA.java:
public class FragmentA extends Fragment {
private FragmentAListener listener;
private EditText editText;
private Button buttonOk;
public interface FragmentAListener {
void onInputASent(CharSequence input);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_a, container, false);
editText = v.findViewById(R.id.edit_text);
buttonOk = v.findViewById(R.id.button_ok);
buttonOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CharSequence input = editText.getText();
listener.onInputASent(input);
}
});
return v;
}
public void updateEditText(CharSequence newText) {
editText.setText(newText);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof FragmentAListener) {
listener = (FragmentAListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement FragmentAListener");
}
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
}
Here is my FragmentB.java:
public class FragmentB extends Fragment {
private FragmentBListener listener;
private EditText editText;
private Button buttonOk;
public interface FragmentBListener {
void onInputBSent(CharSequence input);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_b, container, false);
editText = v.findViewById(R.id.edit_text);
buttonOk = v.findViewById(R.id.button_ok);
buttonOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CharSequence input = editText.getText();
listener.onInputBSent(input);
}
});
return v;
}
public void updateEditText(CharSequence newText) {
editText.setText(newText);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof FragmentBListener) {
listener = (FragmentBListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement FragmentBListener");
}
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
}
Here is my Fertilizers.java file which i want to access from FragmentA.:
public class Fertilizers extends AppCompatActivity {
RecyclerView mRecyclerView;
List<FertilizerData> myFertilizersList;
FertilizerData mFertilizersData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fertilizers);
mRecyclerView = (RecyclerView)findViewById(R.id.recyclerView);
GridLayoutManager gridLayoutManager;
gridLayoutManager = new GridLayoutManager(Fertilizers.this, 1);
mRecyclerView.setLayoutManager(gridLayoutManager);
myFertilizersList = new ArrayList<>();
mFertilizersData = new FertilizerData("Urea Fertilizer","Urea is a concent","Rs.1900",R.drawable.urea);
myFertilizersList.add(mFertilizersData);
myFertilizersList.add(mFertilizersData); }
}
please write here a block of code to call Fertilzers Activity from FragmentA, I,ll be very thankful to you.
Calling getActivity() in your fragment gives you the calling activity so if MainActivity started your fragment then you would do
(MainActivity(getActivity())).something_from_your_main_activity
Solution found by itself regarding this issue.
FragmentHome.java class should look like this:
public class FragmentHome extends Fragment {
private Button button;
public FragmentHome(){
}
public interface OnMessageReadListener
{
public void onMessageRead(String message);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home, container, false);
button = (Button)v.findViewById(R.id.bn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), Fertilizers.class);
intent.putExtra("some"," some data");
startActivity(intent);
}
});
return v;
}
}
FertilizersActivity.java should look like this:
public class Fertilizers extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fertilizers);
Bundle bundle = getIntent().getExtras();
if (bundle != null){
if(bundle.getStringArrayList("some") !=null){
Toast.makeText(getApplicationContext(),"data:" + bundle.getStringArrayList("some"),Toast.LENGTH_LONG).show();
}
}
}
}
I've read countless topics regarding saving and retrieving the state of Fragments by now. Unfortunately nothing has worked for me and Bundle savedInstanceState is always returning null. What i wanna do is implement a "shopping cart" which remembers the items the user selected. To make that possible I just want to save one variable of the Fragment and retrieve it once the Fragment is called again.
Not only do I want to make the fragment retain it's state when called from the backstack, but also when opening it from the BottomNavigationView. Or does it even make any difference?
Here is the parent Activity class of all the Fragments:
public class ShopMainViewScreen extends AppCompatActivity implements ShopFragment.OnFragmentInteractionListener, SearchFragment.OnFragmentInteractionListener, ... {
Fragment mContent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity_layout);
loadFragment(new ShopFragment());
mContent = getSupportFragmentManager().findFragmentById(R.id.fragmentplace);
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment;
switch (item.getItemId()) {
case R.id.navigation_home:
fragment = new ShopFragment();
loadFragment(fragment);
return true;
case R.id.navigation_search:
fragment = new SearchFragment();
loadFragment(fragment);
return true;
case R.id.navigation_shoppingCart:
fragment = new CartFragment();
loadFragment(fragment);
return true;
case R.id.navigation_settings:
fragment = new SettingsFragment();
loadFragment(fragment);
return true;
}
return false;
}
};
private boolean loadFragment(Fragment fragment) {
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragmentplace, fragment)
.addToBackStack(null)
.commit();
}
return false;
}
This is the Fragment containing the variable (mShoppingCart which ought to be stored and retrieved).
public class CartFragment extends Fragment {
private String mTitle;
private int mQuantity;
ArrayList < String > mShoppingCart;
private OnFragmentInteractionListener mListener;
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
Log.i("onSaveInstanceState", "entered");
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putStringArrayList("CART", mShoppingCart);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
Log.i("onActivityCreated", "entered");
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
Log.i("SavedInstanceState", " not null");
mShoppingCart = savedInstanceState.getStringArrayList("CART");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i("onCreate", "entered");
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mTitle = getArguments().getString("PRODUCTTITLE");
mQuantity = getArguments().getInt("QUANTITY");
}
if (savedInstanceState == null) {
Log.i("InstanceState", "is null");
mShoppingCart = new ArrayList < > ();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
validateCart(mTitle, mQuantity);
return inflater.inflate(R.layout.shoppingcart_fragment_layout, container, false);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString() +
" must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
Any help is appreciated.
savedInstanceState is only hydrated during configuration changes or when the app is backgrounded & brought back to the foreground. To save the state of a shopping cart throughout a user's session consider using a view model attached to the parent activity. You could also try persisting the cart in SQLite if you'd like that data to be retained across multiple sessions.
Could guys hep me integrate Startapp network in this activity, this is my code it has not the oncreate method i tried to integrate it but i failed. Please help me. You can find below the code and it does not contain the oncreate method.Im new to coding and i tried lot of time to solve this problem it's easy for me if the oncreate method is there i can integrate the ad network easy. Pleas guys any idea to deal with will help me. Thank you
public class MainFragment extends Fragment {
public MainFragment() {
// Required empty public constructor
}
private final String TAG = "MainFragment";
Activity activity;
AdView bannerAdView;
boolean isAdLoaded;
CardView cardVideoToGIF, cardImagesToGIF, cardCaptureImage, cardVideoToAudio, cardVideoCutter, cardGallery;
LinearLayout linearRow2;
private String SELECTED_TYPE = Constants.TYPE_GIF;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onResume() {
super.onResume();
if (bannerAdView != null) {
bannerAdView.resume();
}
((MainActivity) activity).setTitle("");
((MainActivity) activity).setDrawerState(true);
if (!MyApplication.isFFmpegSupports) {
linearRow2.setVisibility(View.GONE);
}
}
#Override
public void onPause() {
if (bannerAdView != null) {
bannerAdView.pause();
}
super.onPause();
}
#Override
public void onDestroy() {
if (bannerAdView != null) {
bannerAdView.destroy();
}
super.onDestroy();
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initViews(view);
cardVideoToGIF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPopupMenu(cardVideoToGIF);
SELECTED_TYPE = Constants.TYPE_GIF;
}
});
Replace your code with the following
public class MainFragment extends Fragment {
// Add these lines of code which is the onCreate method of your Fragment
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// put your integration code here
Log.i("MainFragment", "onCreate()");
}
public MainFragment() {
// Required empty public constructor
}
private final String TAG = "MainFragment";
Activity activity;
AdView bannerAdView;
boolean isAdLoaded;
CardView cardVideoToGIF, cardImagesToGIF, cardCaptureImage, cardVideoToAudio, cardVideoCutter, cardGallery;
LinearLayout linearRow2;
private String SELECTED_TYPE = Constants.TYPE_GIF;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onResume() {
super.onResume();
if (bannerAdView != null) {
bannerAdView.resume();
}
((MainActivity) activity).setTitle("");
((MainActivity) activity).setDrawerState(true);
if (!MyApplication.isFFmpegSupports) {
linearRow2.setVisibility(View.GONE);
}
}
#Override
public void onPause() {
if (bannerAdView != null) {
bannerAdView.pause();
}
super.onPause();
}
#Override
public void onDestroy() {
if (bannerAdView != null) {
bannerAdView.destroy();
}
super.onDestroy();
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initViews(view);
cardVideoToGIF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPopupMenu(cardVideoToGIF);
SELECTED_TYPE = Constants.TYPE_GIF;
}
});
I have a MainActivity, and I want to attach a fragment with 3 buttons in it to that activity. On clicking button 1 it should replace this fragment with another fragment. But when I change orientation the current fragment and the old fragment are both getting attached. Can someone help me solve this ?
Following is my MainActivity.java:
public class MainActivity extends AppCompatActivity implements OnButtonsClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction()
.add(R.id.mainactivity, new FragmentHomepage(), "aboutMe")
.commit();
}
#Override
public void button1Action() {
FragmentAboutMe fragmentAboutMe=new FragmentAboutMe();
getSupportFragmentManager().beginTransaction()
.add(R.id.mainactivity,fragmentAboutMe)
.commit();
}
#Override
public void button2Action() {
Intent intent =new Intent(this,ActivityMasterDetail.class);
startActivity(intent);
}
#Override
public void button3Action() {
Intent intent =new Intent(this,ActivityViewPager.class);
startActivity(intent);
}
}
This is my FragmentHomepage.java:
public class FragmentHomepage extends Fragment {
private static final String ARG_SECTION_NUMBER ="section number";
OnButtonsClickListener onButtonsClickListener;
public static FragmentHomepage newInstance(int sectionNumber){
FragmentHomepage fragmentHomepage=new FragmentHomepage();
Bundle args=new Bundle();
args.putInt(ARG_SECTION_NUMBER,sectionNumber);
fragmentHomepage.setArguments(args);
return fragmentHomepage;
}
public FragmentHomepage(){}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
onButtonsClickListener= (OnButtonsClickListener) context;
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final Button button1= (Button) getActivity().findViewById(R.id.aboutMe);
final Button button2= (Button) getActivity().findViewById(R.id.task2);
final Button button3= (Button) getActivity().findViewById(R.id.task3);
button1.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
onButtonsClickListener.button1Action();
}
});
button2.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
onButtonsClickListener.button2Action();
}
});
button3.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
onButtonsClickListener.button3Action();
}
});
}
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View rootView=null;
rootView =inflater.inflate(R.layout.fragment_homepage,container,false);
return rootView;
}
}
and my second activity is as follows
(in FragmentAboutMe.java):
public class FragmentAboutMe extends Fragment {
int counters=0;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState==null)counters=0;
else counters=savedInstanceState.getInt("count");
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("count",13);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_aboutme,container,false);
}
}
In your onCreate() method put a check whether the fragment is already present. Android automatically restores the fragment manager state upon orientation change and hence upon orientation change, the fragment which you added on button click would automatically be added. Thus if you will add new fragment in onCreate() without check, this would result in adding the 2 fragments. This is causing the issue.
FragmentManager fm = getSupportFragmentManager();
if (fm.findfragmentById(R.id.mainactivity) == null) {
FragmentHomepage fragment = new FragmentHomepage ();
fm.beginTransaction().add (R.id.mainactivity, fragment).commit();
}
You would want to save the state. You would need to extend Fragment to store the objects that need saving.
Override the onConfigurationChanged(..) and it should work out.
When I had to handle screen orientation changes, I recall having used this reference [link].
There are two ways.
Either you need to save the state in the bundle in onSaveInstanceState() method. Also save the states of fragment.
When activity recreate itself then check the value of bundle inside onCreate() or onRestoreInstanceState() method. Now initialize all the objects as before.
Else
set the value of activity inside manifest file as
android:configChanges="layoutDirection|orientation|screenLayout|screenSize"
and override the method.
#Override
public void onConfigurationChanged(Configuration newConfig) {
}
Second technique will not allow the activity to restart on orientation change.
I am doing an Android app using fragments but i haven't previously experience with fragments.
I have a main FragmentActivity where i load a main view and i call my fragment class:
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_view);
FragmentTransaction FT = getFragmentManager().beginTransaction();
if (findViewById(R.id.fragmentAction) != null) {
FT.replace(R.id.fragmentAction, MainMenuFragment.newInstance(
getString(R.string.main_menu), getApplicationContext()));
}
FT.addToBackStack(null);
FT.commit();
}
#Override
public void onBackPressed() {
}
And this is my fragmet classm where when i push button call to other fragment:
public class MainMenuFragment extends Fragment {
private static String my_description = "";
private static Context my_context = null;
public static MainMenuFragment newInstance(String description,
Context context) {
my_description = description;
my_context = context;
MainMenuFragment f = new MainMenuFragment();
return f;
}
public MainMenuFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = null;
if (my_description.compareTo(getString(R.string.main_menu)) == 0) {
view = inflater.inflate(R.layout.main_menu, container, false);
}
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (my_description.compareTo(getString(R.string.main_menu)) == 0) {
Button new_user = (Button) getView().findViewById(
R.id.button_newUser);
new_user.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction FT = getFragmentManager()
.beginTransaction();
FT.replace(R.id.fragmentAction, LdapFragment.newInstance(
getString(R.string.new_user), my_context));
FT.commit();
}
});
}
}
}
My question is: how can i do to return to previously fragment when i push back key? I add onBackPressed function in my FragmentActivity and capture the event, but what have i to do?
Use this code
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
this.finish();
} else {
getSupportFragmentManager().popBackStack();
removeCurrentFragment();
}
}
public void removeCurrentFragment() {
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
Fragment currentFrag = getSupportFragmentManager().findFragmentById(
R.id.fragment_container);
setFragName("NONE");
if (currentFrag != null) {
setFragName(currentFrag.getClass().getSimpleName());
}
if (currentFrag != null) {
transaction.remove(currentFrag);
}
transaction.commit();
}
following is the code that i use. You need not do anything. Android system handles backpress and shows the appropriate fragment in the navigation order
#Override
public void onBackPressed() {
super.onBackPressed();
if (getFragmentManager().getBackStackEntryCount() == 0)
finish();
}
you missed the super.onBackPressed(); call. Try adding that to your code.
Just create method for add and back to fragment .
for example,
public void setFragment(Fragment fragment, boolean backStack, String tag) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = manager.beginTransaction();
if (backStack) {
fragmentTransaction.addToBackStack(tag);
}
fragmentTransaction.replace(R.id.fragmentAction, MainMenuFragment.newInstance(
getString(R.string.main_menu), tag);
fragmentTransaction.commit();
}
call method from onCreate() or onResume()of your Activity.
setFragment(Your FragmentClass object, true, "tag");