How to get context for Gilde from interface - android

I'm trying to use Glide to load a picture. Glide needs context/fragment/activity/view...
I have fragment, and in the fragment i implenet interface. The data that i receive is from the MainActivity and it transfer by the interface.
The data that i transfer is image path, and with this image path i want to load with Glide.
The problem is that i need context/fragment/activity/view for the Glide.
For example
public class MyAccountFragment extends Fragment implements View.OnClickListener,
ChangeProfileImgDialog.OnPhotoReceivedListener{
#Override
public void getImagePath(Uri imagePath) {
if( !imagePath.toString().equals("")){
mSelectedImageUri = imagePath;
mSelectedImageBitmap = null;
Log.d(TAG, "getImagePath: got the image uri: " + mSelectedImageUri);
Glide.with(**What should i do here **).load(imagePath).into(cvUserProfileImage);
}
}
#Override
public void getImageBitmap(Bitmap bitmap,Context context) {
if(bitmap != null){
mSelectedImageUri = null;
mSelectedImageBitmap = bitmap;
Log.d(TAG, "getImageBitmap: got the image bitmap: " + mSelectedImageBitmap);
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_my_account, container, false);
return v;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
Well thats the code, i have tried several things but nothing worked.
I always got null. How can i resolve that problem?

Just use the fragment's getContext() method to get your context. This will be the host activity (same as calling getActivity(), it's just cast as a context).
Neither of these methods will work if called before the fragment's onAttach method has been called. onAttach will be called when the fragment is attached to your activity. Before this, it cannot get a context. I would recommend having your interface method save the uri to a local variable and then you can make the call to load it after or inside of onAttach.
However, if cvUserProfileImage is a part of your fragment, you'll need to do this after you inflate your layout in onCreateView. Otherwise, it won't have been created yet. I am not sure where you are getting that variable from.
Code would look something like:
public class MyAccountFragment extends Fragment implements View.OnClickListener,
ChangeProfileImgDialog.OnPhotoReceivedListener {
private Uri mSelectedImageUri;
private Bitmap mSelectedImageBitmap;
private ImageView cvUserProfileImage;
#Override
public void getImagePath(Uri imagePath) {
if (!imagePath.toString().equals("")) {
mSelectedImageUri = imagePath;
mSelectedImageBitmap = null;
Log.d(TAG, "getImagePath: got the image uri: " + mSelectedImageUri);
}
}
#Override
public void getImageBitmap(Bitmap bitmap, Context context) {
if (bitmap != null) {
mSelectedImageUri = null;
mSelectedImageBitmap = bitmap;
Log.d(TAG, "getImageBitmap: got the image bitmap: " + mSelectedImageBitmap);
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_my_account, container, false);
cvUserProfileImage = v.findViewById(R.Id.cvUserProfileImage);
if (mSelectedImageUri != null) {
Glide.with(getContext()).load(mSelectedImageUri).into(cvUserProfileImage);
} else if (mSelectedImageBitmap != null){
cvUserProfileImage.setImageBitmap(mSelectedImageBitmap);
}
return v;
}
}

Related

Fragment - wait for onCreateView() to complete before running methods

I'm struggling with a puzzling sequence of events relating to a Fragment. I'm trying to add a fragment to an Activity, and then call a method inside the fragment to update some text. However, what I am finding is that the method is being processed in the fragment before onCreateView() finishes, which leaves me with a null View object, and my method fails. Here is the Activity code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_entry_details);
fragmentManager = getSupportFragmentManager();
titleBarFragment = new TitleBarVerticalFragment();
fragmentTransaction = fragmentManager.beginTransaction ();
fragmentTransaction.add(R.id.log_entry_title_frame, titleBarFragment);
fragmentTransaction.commit();
titleBarFragment.updateTitleBar("Edit Log Entry", 20, false);
}
Seems simple enough. Here is the TitleBarVerticalFragment class:
public class TitleBarVerticalFragment extends TitleBarFragment {
#Inject SharedVisualElements sharedVisualElements;
View view;
TextView titleLabel;
public TitleBarVerticalFragment() {
// add this line for any class that want to use any of the singleton objects
Injector.INSTANCE.getAppComponent().inject(this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
Log.d(Constants.TAG, "title fragment onCreateView()");
view = inflater.inflate(R.layout.fragment_title_bar_vertical, container, false);
ImageView logoImage = (ImageView) view.findViewById(R.id.logo_vertical);
titleLabel = (TextView) view.findViewById(R.id.verticalTitleLabel);
titleLabel.setTextColor(sharedVisualElements.secondaryFontColor());
titleLabel.setTypeface(sharedVisualElements.font());
titleLabel.setTextSize(20);
logoImage.setImageDrawable(sharedVisualElements.logoImage());
logoImage.setBackgroundColor(Color.TRANSPARENT);
return view;
}
public void updateTitleBar(String text, int textSize, boolean titleLabelIsHidden) {
Log.d(Constants.TAG, "about to update title bar text");
if (view == null) {
Log.d(Constants.TAG, "vertical title fragment is null");
return;
}
if (titleLabel == null)
titleLabel = (TextView) view.findViewById(R.id.verticalTitleLabel);
if (titleLabel == null) {
Log.d(Constants.TAG, "vertical title label is null");
return;
}
Log.d(Constants.TAG, "updating title text: " + text);
titleLabel.setText(text);
titleLabel.setTextSize(textSize);
}
Note the order of this logcat output. Notice how onCreateView() seems to run after the updateTitleBar() method? How can that be?
about to update title bar text vertical title fragment is null
title fragment onCreateView()
How can I ensure that onCreateView() runs before I call any of the fragment's other methods? Thank you.
Try running fragmentManager.executePendingTransactions() after fragmentTransaction.commit(); and before titleBarFragment.updateTitleBar("Edit Log Entry", 20, false);
Just use onStart() on your activity
Define a listener interface and implement it in your Activity.
interface LyfecycleListener {
void onCreatedView();
}
in your Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
...
this.titleBarFragment = new TitleBarVerticalFragment();
this.titleBarFragment.setListener(this)
...
}
#Override
public void onCreatedView() {
titleBarFragment.updateTitleBar("Edit Log Entry", 20, false);
}
in your Fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
this.listener.onCreatedView();
}

Android - setting data in views of a fragment based on an async server response

I have the following fragment as below, wherein the onPostNetworkRequestWithCode() method is called back by another part of the code (the App extends Application class which does network requests), to paint the views
Since the fragment creation chain (onCreate(), onCreateView() etc) are called in a different thread than the onPostNetworkRequestWithCode() which repaints the views, I am having a race condition sometimes when the onPostNetworkRequestWithCode() method does not find a view to paint. How can I ask it to wait till the view creation is done and then resume post that?
public class MeStatsTableFragment extends Fragment implements HttpResponseHandlerWithResponseCode {
private static final String LINKED_USER_ID = "linkedUserId";
private Context mContext;
public MeStatsTableFragment() {
// Required empty public constructor
}
public static MeStatsTableFragment newInstance(long linkedUserId, Context context) {
MeStatsTableFragment fragment = new MeStatsTableFragment();
Bundle args = new Bundle();
args.putLong(LINKED_USER_ID, linkedUserId);
fragment.setArguments(args);
fragment.mContext = context;
return fragment;
}
/**
* This is responsible for painting the chart after data is obtained by parent Me Fragment
*/
#Override
public void onPostNetworkRequestWithCode(HttpResponseCode responseCode) {
long linkedUserId = getArguments().getLong(LINKED_USER_ID);
MePageInfo m = App.getAppData().getMePageInfoById(linkedUserId);
View v = getView();
if (v == null) {
Log.d("XXX", "Stats fragment Got stuck at view == null in Stats Fragment");
// do nothing else, just return
} else{
v.findViewById(R.id.text_name).setText(m.name);
// do other painting similarly with the view and the variable m
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_me_stats_table, container, false);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
You could use greenrobot EventBus (https://github.com/greenrobot/EventBus) - and make a sticky post, in a case when there is no fragment yet.
Here is more info about sticky post and register - https://github.com/greenrobot/EventBus/blob/master/HOWTO.md#sticky-events

Accessing Fragment's views after inflating

What I need to achieve
A screen displaying a ListView, which can be replaced by an error screen in case of problems (missing connection, server unavailable and the like).
I need to be able to switch (programmatically) back and forth between these two screens.
Requirements
The main screen must be a Fragment.
This is because my application is composed of several sections, each one accessible from the navigation drawer.
What I have done so far
The main fragment class is named AllQueuesFragment: its XML layout consists of a FrameLayout, which I use in combination with the FragmentManager to switch between ErrorFragment (containing the error message) and QueuesViewFragment (containing the ListView).
public class AllQueuesFragment extends Fragment
{
public AllQueuesFragment()
{
super();
}
#Override
public void onStart()
{
super.onStart();
// Show the right fragment based on connectivity status
checkConnection();
}
public void checkConnection()
{
final NetworkManager netManager = NetworkManager.getInstance(this.getActivity());
if (netManager.isConnected())
showQueues();
else
showNoConnection();
}
public void showNoConnection()
{
ErrorFragment fragNoConnection = new ErrorFragment();
displayFragment(fragNoConnection);
fragNoConnection.setTitle(R.string.text_no_connection);
fragNoConnection.setIcon(R.drawable.thatfeel);
fragNoConnection.setLoaderVisibility(false);
}
public void showQueues()
{
QueuesViewFragment fragQueuesView = new QueuesViewFragment();
displayFragment(fragQueuesView);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Inflate the view
View rootView = inflater.inflate(R.layout.fragment_allqueues, container, false);
return rootView;
}
// Displays a new fragment
public void displayFragment(Fragment fragment)
{
if (fragment != null)
{
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
}
}
}
The error screen is the following:
public class ErrorFragment extends Fragment
{
private TextView textTitle;
public ErrorFragment()
{
super();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Inflate the view
View rootView = inflater.inflate(R.layout.fragment_error, container, false);
// Get the widgets
textTitle = (TextView)rootView.findViewById( R.id.fragment_error_text );
return rootView;
}
// Set methods
public void setTitle(int id) { textTitle.setText(id); }
}
The problem
The setTitle() method gets called before the layout is ready, and as a result, a NullPointerException is thrown.
class AllQueuesFragment
{
....
public void displayFragment(Fragment fragment)
{
if (fragment != null)
{
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
}
}
public void showNoConnection()
{
ErrorFragment fragNoConnection = new ErrorFragment();
displayFragment(fragNoConnection);
// PROBLEM HERE: Before calling setTitle(), I must be sure that ErrorFragment's
// layout is inflated!
fragNoConnection.setTitle(R.string.text_no_connection);
}
....
}
class ErrorFragment
{
....
public void setTitle(String value) { textTitle.setText(value); }
....
}
I can't call setTitle() directly from ErrorFragment::onCreateView(), because I don't know beforehand which message I need to show.
How can I ensure that fragNoConnection has completed its layouting?
Is there a better way to achieve my goal?
Unsatisfying workaround
The only workaround I can think of is to use a buffer to defer the actual call:
class ErrorFragment
{
// This string will hold the title until the layout is inflated
private String titleBuffer;
private TextView textTitle = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Inflate the view
View rootView = inflater.inflate(R.layout.fragment_error, container, false);
// Get the widgets
textTitle = (TextView)rootView.findViewById( R.id.fragment_error_text );
// Do the actual set
setTitle(titleBuffer);
return rootView;
}
....
public void setTitle(String value)
{
titleBuffer = value;
// If the layout is not inflated, defer the actual set
if (textTitle != null)
textTitle.setText(titleBuffer);
}
....
}
but I don't like this solution very much (the code above is simplified; ErrorFragment has more properties).
Advices?
Thanks in advance
This is exactly the type of thing arguments are supposed to be used for:
public void showNoConnection() {
ErrorFragment fragNoConnection = new ErrorFragment();
Bundle args = new Bundle();
//you can also use putInt here if you'd rather pass a string resource id, along with anything else you can stick into a Bundle
args.putString("title", "some title");
fragNoConnection.setArguments(args);
displayFragment(fragNoConnection);
}
Then in ErrorFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_error, container, false);
TextView textTitle = (TextView)rootView.findViewById( R.id.fragment_error_text );
//now retrieve the argument...
textTitle.setText(getArguments().getString("title"));
return rootView;
}
The Fragment will even remember it's arguments after an orientation change.
If you feel like being pedantic, you can create a static factory method within ErrorFragment that takes the title as an argument and then creates the Fragment and adds the argument, that way you can achieve proper encapsulation :)
You need to have a callback method in your ErrorFragment and when the view is inflated you then call the method in your callback interface in the onViewCreated and set the title.
sample:
in ErroFragment
public class ErroFragment extends Fragment
{
static interface ErrorDone{
public void doneInflating();
}
private TextView textTitle;
private ErrorDone ed;
public ErroFragment()
{
super();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Inflate the view
View rootView = inflater.inflate(R.layout.fragment_error, container, false);
// Get the widgets
textTitle = (TextView)rootView.findViewById( R.id.fragment_error_text );
return rootView;
}
// Set methods
public void setTitle(int id) { textTitle.setText(id); }
public void setInterFace(ErrorDone er){ this.ed = er; }
}
Then you implement the interface in your AllQueuesFragment
public class AllQueuesFragment extends Fragment implements ErroFragment.ErrorDone
It will generate method doneInflating
and you need to set the interface:
public void showNoConnection()
{
ErrorFragment fragNoConnection = new ErrorFragment();
displayFragment(fragNoConnection);
fragNoConnection.setInterFace(this);
}
And in the generated method(doneInflating) of the AllQueuesFragment you then set the title in there:
public void doneInflating(){
fragNoConnection.setTitle(R.string.text_no_connection);
fragNoConnection.setIcon(R.drawable.thatfeel);
fragNoConnection.setLoaderVisibility(false);
}
If you want to be sure that the FragmentTransaction is commited and effective, you can use the executePendingTransactions method:
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
fragmentManager.executePendingTransactions();
But, the right way to do it is to send the title value to the Fragment when instantiating it. This is the default pattern when you create a Fragment from your IDE (eclipse or Android Studio)

How come position information isn't being passed to my fragments?

I have an Activity that is largely unmodified form the default Android Studio example for a tabbed activity. Its FragmentPagerAdapter is modified to display all 50 United States, with 50 corresponding tabs displaying their names. This works until a fragment is destroyed, but when it's re-created, it's not told which tab it's on. Why does this happen?
The following are all the methods that I think could be part of the problem:
public class MainQuizActivity extends Activity implements ActionBar.TabListener {
...
public class SectionsPagerAdapter extends FragmentPagerAdapter {
...
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return
questionFragments[position] == null
? questionFragments[position] = QuestionFragment.newInstance(position)
: questionFragments[position];
}
...
}
...
}
...
public class QuestionFragment extends Fragment {
...
public static QuestionFragment newInstance(int stateIndex) {
System.out.println("Creating new instance for state #" + stateIndex);
QuestionFragment fragment = new QuestionFragment();
Bundle args = new Bundle();
args.putInt(States.BUNDLE_KEY, stateIndex);
fragment.setArguments(args);
return fragment;
}
...
#Override
public View onCreateView(
LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
System.out.println("~onCreateView");
View rootView = inflater.inflate(
R.layout.fragment_main_quiz, container, false);
webView = (WebView)rootView.findViewById(R.id.webView);
initState(savedInstanceState);
return rootView;
}
private void initState(Bundle args) {
if (state == null) {
System.out.println("Bundle: " + args);
if (args == null)
args = getArguments();
System.out.println("Bundle is now: " + args);
int stateIndex = args.getInt(States.BUNDLE_KEY);
System.out.println("Gonna be state #" + stateIndex);
state = States.values()[stateIndex];
System.out.println("Gonna be " + state);
}
else
System.out.println("State already exists! (yay!)");
String path = state.getImageURL();
System.out.println("Opening image at " + path);
webView.loadUrl(path);
webView.setBackgroundColor(0x00000000);
}
#Override
public void onCreate(Bundle savedInstanceState) {
System.out.println("~onCreate");
super.onCreate(savedInstanceState);
if (webView == null)
webView = (WebView)(getActivity().findViewById(R.id.webView));
System.out.println("onCreate: webView == " + webView);
System.out.println("onCreate: bundle == " + savedInstanceState);
if (webView != null
&& savedInstanceState != null)
initState(savedInstanceState);
}
...
}
I saved this in the bundle with the key States.BUNDLE_KEY (which is "STATE"), but the bundle it's given does not have that key in it the second time. For debugging purposes, I overrode all on* methods that deal with loading and unloading with empty ones like:
#Override public void onResume(){
System.out.println("~onResume");
super.onResume();}
Of course, there are also more debugging outputs that I threw in.
I hope this video I recorded helps illustrate the issue: http://youtu.be/cmbR_2rvpX4
The console dump for the video is in this pastebin: http://pastebin.com/rxAP7qda
And, if all this still doesn't help, here's its git: https://github.com/Supuhstar/US-State-Quiz-App
Even after all this, I feel I'm not giving the right information. Please ask for less or more if you think this can be put better.
You're not initializing things properly in your QuestionFragment. First of all there's no need to call the initState(savedInstanceState); method in both the onCreate() and onCreateView() callbacks. Call it in onCreateView() and remove entirely the onCreate() method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
System.out.println("~onCreateView");
View rootView = inflater.inflate(R.layout.fragment_main_quiz, container, false);
webView = (WebView)rootView.findViewById(R.id.webView);
guessSpinner = (Spinner)getActivity().findViewById(R.id.guess_spinner);
initState();
initGuesser();
return rootView;
}
Your initState(savedInstanceState) method is also a bit too complicated for what it should do:
private void initState() {
Bundle args = getArguments();
if (args == null) {
throw new IllegalArgumentException("The arguments should be valid!");
}
System.out.println("Bundle is now: " + args);
int stateIndex = args.getInt(States.BUNDLE_KEY);
System.out.println("Gonna be state #" + stateIndex);
state = States.values()[stateIndex];
System.out.println("Gonna be " + state);
String path = state.getImageURL();
System.out.println("Opening image at " + path);
webView.loadUrl(path);
webView.setBackgroundColor(getResources().getColor(R.color.transparent));
}

Listview fragment is getting recreated on pressing backbutton

I'm using loader in my ListView fragment, and it's getting recreated on pressing "back" button. Can you tell me how to handle this senario?
Here is my ListView fragment code. Here I have a boolean variable that I'm setting as true on clicking on list item. but once the back button is pressed onCreateView will get called so the backbutton will be false.
public class GTFragment extends SherlockFragment implements LoaderCallbacks<Cursor>{
ListView mTListview = null;
GoogleTasksAdapter mGTasksAdapter = null;
private SQLiteCursorLoader mTLoader=null;
private LoaderManager mTLoaderManager;
private String mSelectedListID = null;
private boolean mIsBackbuttonisPressed = false;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.task_home_activity, container, false);
if(!mIsBackbuttonisPressed)
getLoaderManager().initLoader(0, null, this);
mTListview = (ListView) view.findViewById(R.id.id_task_list_home_activity);
mGTasksAdapter = new GoogleTasksAdapter(getActivity());
mTListview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listview,
View clickedview, int position, long arg3) {
// TODO Auto-generated method stub
GoogleTaskItem item = new GoogleTaskItem();
Cursor coursor = ((GoogleTasksAdapter)listview.getAdapter()).getCursor();
if(coursor.moveToPosition(position))
{
mIsBackbuttonisPressed = true;
GoogleTaskController.get_googletask_controllerObj()
.LaunchTaskPreviewActivity();
}
}
});
mTListview.setAdapter(mGTasksAdapter);
mIsBackbuttonisPressed = false;
return view;
}
My fragment activity class code
public class TLActivity extends SherlockFragmentActivity {
LeftSliderTaskListOptions mTaskOptionsFragment = null;
GoogleTasksFragment mTFragment = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
setContentView(R.layout.layout_gt_list);
// FragmentTransaction tfragment = this.getSupportFragmentManager().beginTransaction();
mTFragment = new GTasksFragment();
t.replace(R.id.id_tfragment, mTFragment);
t.commit();
}
instead of
t.replace(R.id.id_tfragment, mTFragment);
use
t.add(R.id.id_tfragment, mTFragment);
It worked for me
I don't think that the accepted answer is right because Fragment.onSaveInstanceState will not be called until the activity hosting it needs to save its state: The docs states:
There are many situations where a fragment may be mostly torn down
(such as when placed on the back stack with no UI showing), but its
state will not be saved until its owning activity actually needs to
save its state.
In other words: if you're using a Activity with multiple fragments for each screen (which is very common), the fragment state will not be saved when you move the next screen.
You also can't use Fragment.setRetainInstance because he's meant only to fragments that aren't on the back stack.
Most of the time, you don't have to think about this but sometimes it's important. Like when you have scrolled a list and want to "remember" the scroll location.
I took a long time to realize that the fragments put on the back stack are kind of saved and you can reuse the view that you already created instead of creating one every time the fragment calls onCreateView. My setup is something like this:
public abstract class BaseFragment extends Fragment {
private boolean mSaveView = false;
private SoftReference<View> mViewReference;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (mSaveView) {
if (mViewReference != null) {
final View savedView = mViewReference.get();
if (savedView != null) {
if (savedView.getParent() != null) {
((ViewGroup) savedView.getParent()).removeView(savedView);
return savedView;
}
}
}
}
final View view = inflater.inflate(getFragmentResource(), container, false);
mViewReference = new SoftReference<View>(view);
return view;
}
protected void setSaveView(boolean value) {
mSaveView = value;
}
}
public class MyFragment extends BaseFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setSaveView(true);
final View view = super.onCreateView(inflater, container, savedInstanceState);
ListView placesList = (ListView) view.findViewById(R.id.places_list);
if (placesList.getAdapter() == null) { // this check is important so you don't restart your adapter
placesList.setAdapter(createAdapter());
}
}
}
You have multiple options to rectify this issue.
Override onSaveInstanceState like this:
#Override
public void onSaveInstanceState (Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("mIsBackbuttonisPressed", mIsBackbuttonisPressed);
}
and then in your onCreateView you can get your variable back by:
if (savedInstanceState != null)
mIsBackbuttonisPressed = savedInstanceState.getBoolean("mIsBackbuttonisPressed", false);
You can set this.setRetainInstance(true); in your onCreate method of your fragment.
If you could post your Activity code with creates your fragment I can also tell you other options. (P.S I cannot write it as a comment so posting it in the answer.)

Categories

Resources