Android Fragment + Tablet = NullPointerException - android-fragments

My layout is a little bit complex:
I have a vertical viewflipper and on the second page a horizontal viewpager with several fragments.
On the third page I have a listview with a textfild, that can filter the listview depending on the states of togglebuttons in the fragments.
Due to the fact, that the viewflipper has some caching and unload mechanisms for performance reasons, I had to make the references to the togglebuttons in the fragments static:
public class FragmentOne extends Fragment {
public static ToggleButton btn_1;
public static ToggleButton btn_2;
...
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
btn_1 = (ToggleButton)V.findViewById(R.id.btn_1);
btn_2 = (ToggleButton)V.findViewById(R.id.btn_2);
...
}
}
Everything works fine, but for some reasons only on tablets (manly Galxy Tab3) I get a nullpointerexception when I want to check the state of the Togglebuttons:
filterListview(){
if(FragmentOne.btn_1.isChecked()){ //doSomething };
....
}
Any Idea what can cause this problem? (btw I don't have any specific layout for tablets, only one layout for the app, and the app always runs in portrait-mode)

Related

addSnapshotListener, get, update, etc. in onActivityCreated are called several times (when the user rotates the screen for example) [duplicate]

In my Android application, when I rotate the device (slide out the keyboard) then my Activity is restarted (onCreate is called). Now, this is probably how it's supposed to be, but I do a lot of initial setting up in the onCreate method, so I need either:
Put all the initial setting up in another function so it's not all lost on device rotation or
Make it so onCreate is not called again and the layout just adjusts or
Limit the app to just portrait so that onCreate is not called.
Using the Application Class
Depending on what you're doing in your initialization you could consider creating a new class that extends Application and moving your initialization code into an overridden onCreate method within that class.
public class MyApplicationClass extends Application {
#Override
public void onCreate() {
super.onCreate();
// TODO Put your application initialization code here.
}
}
The onCreate in the application class is only called when the entire application is created, so the Activity restarts on orientation or keyboard visibility changes won't trigger it.
It's good practice to expose the instance of this class as a singleton and exposing the application variables you're initializing using getters and setters.
NOTE: You'll need to specify the name of your new Application class in the manifest for it to be registered and used:
<application
android:name="com.you.yourapp.MyApplicationClass"
Reacting to Configuration Changes [UPDATE: this is deprecated since API 13; see the recommended alternative]
As a further alternative, you can have your application listen for events that would cause a restart – like orientation and keyboard visibility changes – and handle them within your Activity.
Start by adding the android:configChanges node to your Activity's manifest node
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name">
or for Android 3.2 (API level 13) and newer:
<activity android:name=".MyActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="#string/app_name">
Then within the Activity override the onConfigurationChanged method and call setContentView to force the GUI layout to be re-done in the new orientation.
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.myLayout);
}
Update for Android 3.2 and higher:
Caution: Beginning with Android 3.2 (API level 13), the "screen size" also changes when the device switches between portrait and landscape orientation. Thus, if you want to prevent runtime restarts due to orientation change when developing for API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), you must include the "screenSize" value in addition to the "orientation" value. That is, you must declare android:configChanges="orientation|screenSize". However, if your application targets API level 12 or lower, then your activity always handles this configuration change itself (this configuration change does not restart your activity, even when running on an Android 3.2 or higher device).
From http://web.archive.org/web/20120805085007/http://developer.android.com/guide/topics/resources/runtime-changes.html
Instead of trying to stop the onCreate() from being fired altogether, maybe try checking the Bundle savedInstanceState being passed into the event to see if it is null or not.
For instance, if I have some logic that should be run when the Activity is truly created, not on every orientation change, I only run that logic in the onCreate() only if the savedInstanceState is null.
Otherwise, I still want the layout to redraw properly for the orientation.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_list);
if(savedInstanceState == null){
setupCloudMessaging();
}
}
not sure if this is the ultimate answer, but it works for me.
what I did...
in the manifest, to the activity section, added:
android:configChanges="keyboardHidden|orientation"
in the code for the activity, implemented:
//used in onCreate() and onConfigurationChanged() to set up the UI elements
public void InitializeUI()
{
//get views from ID's
this.textViewHeaderMainMessage = (TextView) this.findViewById(R.id.TextViewHeaderMainMessage);
//etc... hook up click listeners, whatever you need from the Views
}
//Called when the activity is first created.
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
InitializeUI();
}
//this is called when the screen rotates.
// (onCreate is no longer called when screen rotates due to manifest, see: android:configChanges)
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
setContentView(R.layout.main);
InitializeUI();
}
What you describe is the default behavior. You have to detect and handle these events yourself by adding:
android:configChanges
to your manifest and then the changes that you want to handle. So for orientation, you would use:
android:configChanges="orientation"
and for the keyboard being opened or closed you would use:
android:configChanges="keyboardHidden"
If you want to handle both you can just separate them with the pipe command like:
android:configChanges="keyboardHidden|orientation"
This will trigger the onConfigurationChanged method in whatever Activity you call. If you override the method you can pass in the new values.
Hope this helps.
I just discovered this lore:
For keeping the Activity alive through an orientation change, and handling it through onConfigurationChanged, the documentation and the code sample above suggest this in the Manifest file:
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name">
which has the extra benefit that it always works.
The bonus lore is that omitting the keyboardHidden may seem logical, but it causes failures in the emulator (for Android 2.1 at least): specifying only orientation will make the emulator call both OnCreate and onConfigurationChanged sometimes, and only OnCreate other times.
I haven't seen the failure on a device, but I have heard about the emulator failing for others. So it's worth documenting.
You might also consider using the Android platform's way of persisting data across orientation changes: onRetainNonConfigurationInstance() and getLastNonConfigurationInstance().
This allows you to persist data across configuration changes, such as information you may have gotten from a server fetch or something else that's been computed in onCreate or since, while also allowing Android to re-layout your Activity using the xml file for the orientation now in use.
See here or here.
It should be noted that these methods are now deprecated (although still more flexible than handling orientation change yourself as most of the above solutions suggest) with the recommendation that everyone switch to Fragments and instead use setRetainInstance(true) on each Fragment you want to retain.
The approach is useful but is incomplete when using Fragments.
Fragments usually get recreated on configuration change. If you don't wish this to happen, use
setRetainInstance(true); in the Fragment's constructor(s)
This will cause fragments to be retained during configuration change.
http://developer.android.com/reference/android/app/Fragment.html#setRetainInstance(boolean)
I just simply added:
android:configChanges="keyboard|keyboardHidden|orientation"
in the AndroidManifest.xml file and did not add any onConfigurationChanged method in my activity.
So every time the keyboard slides out or in nothing happens! Also checkout this article about this problem.
The onCreate method is still called even when you change the orientation of android. So moving all the heavy functionality to this method is not going to help you
Put the code below inside your <activity> tag in Manifest.xml:
android:configChanges="screenLayout|screenSize|orientation"
It is very simple just do the following steps:
<activity
android:name=".Test"
android:configChanges="orientation|screenSize"
android:screenOrientation="landscape" >
</activity>
This works for me :
Note: orientation depends on your requitement
onConfigurationChanged is called when the screen rotates.
(onCreate is no longer called when the screen rotates due to manifest, see:
android:configChanges)
What part of the manifest tells it "don't call onCreate()"?
Also,
Google's docs say to avoid using android:configChanges (except as a last resort). But then the alternative methods they suggest all DO use android:configChanges.
It has been my experience that the emulator ALWAYS calls onCreate() upon rotation.
But the 1-2 devices that I run the same code on... do not.
(Not sure why there would be any difference.)
Changes to be made in the Android manifest are:
android:configChanges="keyboardHidden|orientation"
Additions to be made inside activity are:
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
Add this line to your manifest :-
android:configChanges="orientation|keyboard|keyboardHidden|screenSize|screenLayout|uiMode"
and this snippet to the activity :-
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
There are several ways to do this:
Save Activity State
You can save the activity state in onSaveInstanceState.
#Override
public void onSaveInstanceState(Bundle outState) {
/*Save your data to be restored here
Example: outState.putLong("time_state", time); , time is a long variable*/
super.onSaveInstanceState(outState);
}
and then use the bundle to restore the state.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState!= null){
/*When rotation occurs
Example : time = savedInstanceState.getLong("time_state", 0); */
} else {
//When onCreate is called for the first time
}
}
Handle orientation changes by yourself
Another alternative is to handle the orientation changes by yourself. But this is not considered a good practice.
Add this to your manifest file.
android:configChanges="keyboardHidden|orientation"
for Android 3.2 and later:
android:configChanges="keyboardHidden|orientation|screenSize"
#Override
public void onConfigurationChanged(Configuration config) {
super.onConfigurationChanged(config);
if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
//Handle rotation from landscape to portrait mode here
} else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
//Handle rotation from portrait to landscape mode here
}
}
Restrict rotation
You can also confine your activity to portrait or landscape mode to avoid rotation.
Add this to the activity tag in your manifest file:
android:screenOrientation="portrait"
Or implement this programmatically in your activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
The way I have found to do this is use the onRestoreInstanceState and the onSaveInstanceState events to save something in the Bundle (even if you dont need any variables saved, just put something in there so the Bundle isn't empty). Then, on the onCreate method, check to see if the Bundle is empty, and if it is, then do the initialization, if not, then do it.
Even though it is not "the Android way" I have gotten very good results by handling orientation changes myself and simply repositioning the widgets within a view to take the altered orientation into account. This is faster than any other approach, because your views do not have to be saved and restored. It also provides a more seamless experience to the user, because the respositioned widgets are exactly the same widgets, just moved and/or resized. Not only model state, but also view state, can be preserved in this manner.
RelativeLayout can sometimes be a good choice for a view that has to reorient itself from time to time. You just provide a set of portrait layout params and a set of landscaped layout params, with different relative positioning rules on each, for each child widget. Then, in your onConfigurationChanged() method, you pass the appropriate one to a setLayoutParams() call on each child. If any child control itself needs to be internally reoriented, you just call a method on that child to perform the reorientation. That child similarly calls methods on any of its child controls that need internal reorientation, and so on.
Every time when the screen is rotated, opened activity is finished and onCreate() is called again.
1 . You can do one thing save the state of activity when the screen is rotated so that, You can recover all old stuff when the activity's onCreate() is called again.
Refer this link
2 . If you want to prevent restarting of the activity just place the following lines in your manifest.xml file.
<activity android:name=".Youractivity"
android:configChanges="orientation|screenSize"/>
you need to use the onSavedInstanceState method to store all the values to its parameter is has which is a bundle
#Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
outPersistentState.putBoolean("key",value);
}
and use
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
savedInstanceState.getBoolean("key");
}
to retrieve and set the value to view objects
it will handle the screen rotations
Note: I post this answer if someone in the future face the same problem as me. For me the following line wasn't enough:
android:configChanges="orientation"
When I rotated the screen, the method `onConfigurationChanged(Configuration new config) didn't get called.
Solution: I also had to add "screenSize" even if the problem had to do with the orientation. So in the AndroidManifest.xml - file, add this:
android:configChanges="keyboardHidden|orientation|screenSize"
Then implement the method onConfigurationChanged(Configuration newConfig)
In the activity section of the manifest, add:
android:configChanges="keyboardHidden|orientation"
Add this line in manifest : android:configChanges="orientation|screenSize"
People are saying that you should use
android:configChanges="keyboardHidden|orientation"
But the best and most professional way to handle rotation in Android is to use the Loader class. It's not a famous class(I don't know why), but it is way better than the AsyncTask. For more information, you can read the Android tutorials found in Udacity's Android courses.
Of course, as another way, you could store the values or the views with onSaveInstanceState and read them with onRestoreInstanceState. It's up to you really.
One of the best components of android architecture introduced by google will fulfill all the requirements that are ViewModel.
That is designed to store and manage UI-related data in a lifecycle way plus that will allow data to survive as the screen rotates
class MyViewModel : ViewModel() {
Please refer to this: https://developer.android.com/topic/libraries/architecture/viewmodel
After a while of trial and error, I found a solution which fits my needs in the most situations. Here is the Code:
Manifest configuration:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pepperonas.myapplication">
<application
android:name=".App"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboardHidden|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
MainActivity:
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MainActivity";
private Fragment mFragment;
private int mSelected = -1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate " + "");
// null check not realy needed - but just in case...
if (savedInstanceState == null) {
initUi();
// get an instance of FragmentTransaction from your Activity
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
/*IMPORTANT: Do the INITIAL(!) transaction only once!
* If we call this everytime the layout changes orientation,
* we will end with a messy, half-working UI.
* */
mFragment = FragmentOne.newInstance(mSelected = 0);
fragmentTransaction.add(R.id.frame, mFragment);
fragmentTransaction.commit();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.d(TAG, "onConfigurationChanged " +
(newConfig.orientation
== Configuration.ORIENTATION_LANDSCAPE
? "landscape" : "portrait"));
initUi();
Log.i(TAG, "onConfigurationChanged - last selected: " + mSelected);
makeFragmentTransaction(mSelected);
}
/**
* Called from {#link #onCreate} and {#link #onConfigurationChanged}
*/
private void initUi() {
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate instanceState == null / reinitializing..." + "");
Button btnFragmentOne = (Button) findViewById(R.id.btn_fragment_one);
Button btnFragmentTwo = (Button) findViewById(R.id.btn_fragment_two);
btnFragmentOne.setOnClickListener(this);
btnFragmentTwo.setOnClickListener(this);
}
/**
* Not invoked (just for testing)...
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.d(TAG, "onSaveInstanceState " + "YOU WON'T SEE ME!!!");
}
/**
* Not invoked (just for testing)...
*/
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Log.d(TAG, "onSaveInstanceState " + "YOU WON'T SEE ME, AS WELL!!!");
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume " + "");
}
#Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause " + "");
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy " + "");
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_fragment_one:
Log.d(TAG, "onClick btn_fragment_one " + "");
makeFragmentTransaction(0);
break;
case R.id.btn_fragment_two:
Log.d(TAG, "onClick btn_fragment_two " + "");
makeFragmentTransaction(1);
break;
default:
Log.d(TAG, "onClick null - wtf?!" + "");
}
}
/**
* We replace the current Fragment with the selected one.
* Note: It's called from {#link #onConfigurationChanged} as well.
*/
private void makeFragmentTransaction(int selection) {
switch (selection) {
case 0:
mFragment = FragmentOne.newInstance(mSelected = 0);
break;
case 1:
mFragment = FragmentTwo.newInstance(mSelected = 1);
break;
}
// Create new transaction
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.frame, mFragment);
/*This would add the Fragment to the backstack...
* But right now we comment it out.*/
// transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
}
And sample Fragment:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* #author Martin Pfeffer (pepperonas)
*/
public class FragmentOne extends Fragment {
private static final String TAG = "FragmentOne";
public static Fragment newInstance(int i) {
Fragment fragment = new FragmentOne();
Bundle args = new Bundle();
args.putInt("the_id", i);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d(TAG, "onCreateView " + "");
return inflater.inflate(R.layout.fragment_one, container, false);
}
}
Can be found on github.
Use orientation listener to perform different tasks on different orientation.
#Override
public void onConfigurationChanged(Configuration myConfig)
{
super.onConfigurationChanged(myConfig);
int orient = getResources().getConfiguration().orientation;
switch(orient)
{
case Configuration.ORIENTATION_LANDSCAPE:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
case Configuration.ORIENTATION_PORTRAIT:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
default:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
}
Put this below code in your Activity in Android Manifest.
android:configChanges="orientation"
This will not restart your activity when you would change orientation.
Fix the screen orientation (landscape or portrait) in AndroidManifest.xml
android:screenOrientation="portrait" or android:screenOrientation="landscape"
for this your onResume() method is not called.
You may use the ViewModel object in your activity.
ViewModel objects are automatically retained during configuration changes so that the data they hold is immediately available to the next activity or fragment instance.
Read more:
https://developer.android.com/topic/libraries/architecture/viewmodel

JavaFX: Need help understanding setControllerFactory

I set up multiple custom controllers during the creation of an app and would need some help in organizing these controllers with setControllerFactory in JavaFX.
I'm fairly inexperienced with JavaFX but invested quite some time in creating a small app with Scenebuilder and JavaFX.
Background of the app
The app consists of:
- a map (implemented as an imageView)
- a sidebar with buttons and icons for drag and drop events.
- the map also has separate layers as the target for the drag and drop of different icon types.
As a prototype of my drag and drop event I used the instructions of Joel Graff (https://monograff76.wordpress.com/2015/02/17/developing-a-drag-and-drop-ui-in-javafx-part-i-skeleton-application/). He writes "in order for an object to be visible beyond a container’s edges, it must be a child of a parent or other ancestral container – it must belong to a higher level of the hierarchy. In the case of our drag-over icon, this means we had to add it as a child to the RootLayout’s top-level AnchorPane." and he uses dynamic roots for his project.
To teach myself how to use custom control with FXML I used Irina Fedortsova's tutorial https://docs.oracle.com/javafx/2/fxml_get_started/custom_control.htm.
And to learn how to set up multiple screens I used the video https://www.youtube.com/watch?v=5GsdaZWDcdY and associating code from https://github.com/acaicedo/JFX-MultiScreen.
After building my app the logic tier of my app got more and more entangled with the presentation tier, and I feel as if my code would benefit greatly from some refactoring.
My problem seems to be a lack in the understanding of the load and initialize process of controller classes. Since the drag icons and the RootLayout have to be loaded from the beginning, it is a mystery to me how I can load these classes in a way that I can call them again at a later time.
When I was looking for further solutions, I repeatedly came across the method setControllerFactory. Unfortunately I can't find a good explanation for how to use it properly and what it's specific purpose is.
The only tutorial I found was: https://riptutorial.com/javafx/example/8805/passing-parameters-to-fxml---using-a-controllerfactory, unfortunately it seems to be a bit insufficient for my purpose.
I feel as if I would benefit the most from a methode/class with which I could organize all my custom controllers, load and initialize them at the appropriate time and then later access them again (similar to the interface and superclass in the video for JFX-MultiScreen).
I repeatedly came across the method setControllerFactory. Unfortunately I can't find a good explanation for how to use it properly and what it's specific purpose is
By default, the FXMLLoader.load() method instantiates the controller named in the fxml document using the 0-arg constructor. The FXMLLoader.setControllerFactory​ method is used when you want your FXMLLoader object to instantiate controllers in a certain way, e.g. use a different controller constructor on specific arguments, call a method on the controller before it's returned, etc, as in
FXMLLoader loader = new FXMLLoader(...);
loader.setControllerFactory(c -> {
return new MyController("foo", "bar");
});
Now when you call loader.load() the controller will be created as above. However, calling the FXMLLoader.setController​ method on a preexisting controller may be easier.
I feel as if I would benefit the most from a methode/class with which I could organize all my custom controllers, load and initialize them at the appropriate time and then later access them again
When I first came across this problem, as you have, I tried and retried many approaches. What I finally settled on was turning my main application class into a singleton. The singleton pattern is great when you need to create one instance of a class which should be accessible throughout your program. I know there are many people who will take issue with that (in that it's essentially a global variable with added structure), but I've found that it reduced complexity significantly in that I no longer had to manage a somewhat artificial structure of object references going every which way.
The singleton lets controllers communicate with your main application class by calling, for example, MyApp.getSingleton(). Still in the main application class, you can then organize all of your views in a private HashMap and add public add(...), remove(...), and activate(...) methods which can add or remove views from the map or activate a view in the map (i.e. set the scene's root to your new view).
For an application with many views that may be placed in different packages, you can organize their locations with an enum:
public enum View {
LOGIN("login/Login.fxml"),
NEW_USER("register/NewUser.fxml"),
USER_HOME("user/UserHome.fxml"),
ADMIN_HOME("admin/AdminHome.fxml");
public final String location;
View(String location) {
this.location = "/views/" + location;
}
}
Below is an example of the main application class:
public final class MyApp extends Application {
// Singleton
private static MyApp singleton;
public MyApp() { singleton = this; }
public static MyApp getSingleton() { return singleton; }
// Main window
private Stage stage;
private Map<View, Parent> parents = new HashMap<>();
#Override
public void start(Stage primaryStage) {
stage = primaryStage;
stage.setTitle("My App");
add(View.LOGIN);
stage.setScene(new Scene(parents.get(View.LOGIN)));
stage.show();
}
public void add(View view) {
var loader = new FXMLLoader(getClass().getResource(view.location));
try {
Parent root = loader.load();
parents.put(view, root);
} catch (IOException e) { /* Do something */ }
}
public void remove(View view) {
parents.remove(view);
}
public void activate(View view) {
stage.getScene().setRoot(parents.get(view));
}
public void removeAllAndActivate(View view) {
parents.clear();
add(view);
activate(view);
}
}
If you have application-wide resources you can put them in the app class and add getters/setters so your controllers can access them. Here is an example controller class:
public final class Login implements Initializable {
MyApp app = MyApp.getSingleton();
// Some #FXML variables here..
#FXML private void login() {
// Authenticate..
app.removeAllAndActivate(View.USER_HOME);
}
#FXML private void createAccount() {
app.add(View.NEW_USER);
app.activate(View.NEW_USER);
}
#Override
public void initialize(URL url, ResourceBundle rb) {}
}

how to hide USE FALLBACK in Plugin.Fingerprint dialogue

i have implemented finger-touch login using Plugin.Fingerprint Pluginin my xamarin application.
i dont want to show USE FALLBACK option in dialogue.
i have tried this way to hide it
var config = new AuthenticationRequestConfiguration("pput your finger to authenticate!")
{
FallbackTitle = string.Empty
};
var auth = await CrossFingerprint.Current.AuthenticateAsync(config);
but it is still showing.
anyone have idea how can i hide that?
please help .
On android platform, if you want to disable it, you can inherit from FingerprintDialogFragment and override OnCreateView.
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var view = base.OnCreateView(inflater, container, savedInstanceState);
view.FindViewById<Button>(Resource.Id.fingerprint_btnFallback).Visibility = ViewStates.Gone;
return view;
}
In your MainApplication class, override OnCreate
public override void OnCreate()
{
base.OnCreate();
RegisterActivityLifecycleCallbacks(this);
//A great place to initialize Xamarin.Insights and Dependency Services!
CrossFingerprint.SetCurrentActivityResolver(() => CrossCurrentActivity.Current.Activity);
CrossFingerprint.SetDialogFragmentType<MyCustomDialogFragment>();
}

Issue with ViewPager and FragmentStatePagerAdapter when activity is destroyed

I have an activity which creates viewpager adapter (FragmentStatePagerAdapter) and sets the viewpager to this adapter.
This is how viewpager adapter is created and is set to the viewpager widget.
viewPageAdapter = new viewPageAdapter(getSupportFragmentManager(), getApplicationContext());
mCustomSwipeViewPager.setAdapter(viewPageAdapter);
And this is how i am creating viewPageAdapter
public class viewPagerAdapter extends FragmentStatePagerAdapter {
private SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public viewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// returning newly created fragment
}
#Override
public int getCount() {
// returning total count
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
// This is where i am putting created fragment in the sparse array,
// which i will be accessing in the activity based on position
// for updating fragment views.
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// And here i am removing it from the sparse array
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
}
Now, i went to the developers options and checked "Donot keep activities".
This is where the problem starts, after moving forward this activity, this activity will get destroyed, which is fine.
Now if i come back, the a new adapter is created in onCreate() and is set to the viewpager, but it's not calling getItem() again, instead it's calling instantiateItem(), with fragment in memory as null.
I checked the fragmentmanager in debug mode, the fragment manager holds two fragments as activestate, with all fragment fields as null.
Things i have tried...
Tried clearing the fragment manager in onDestroy() of activity using
fragmentManager.getFragments.clear() but no luck.
Made getItemCount() of adapter to 0 and called notifydatasetChanged() on adapter in onDestroy(), still getting the same.
However, if comment out the super.onSavedInstance() of activity, it's working fine, but this is not i want as it's failing for few cases.
Is there any way wherein if i create a new adapter and again set it to the viewpager, it should start afresh, i.e should call getItem() from first position without minimizing the performance of fragmentStateViewPagerAdapter.
Any kind of help or suggestion would be appreciated.
The only solution i figured out is to comment out the default super.onSaveInstanceState(outState) inside onSaveInstanceState(Bundle outState) callback of activity lifecycle.
#Override
protected void onSaveInstanceState(Bundle outState) {
// super.onSaveInstanceState(outState);
}
Doing so will not keep the fragment old instance in the fragmentManager of viewpager and will start afresh.
I couldn't thought of any better solution, as there are many global variables inside fragment and in also in activity and it's presenter, and saving them in the onSaveInstanceState bundle and them restoring them in onCreate or in onRestoreInstanceState() would be very heavy for me.
Any better solution or approach than this is still appreciable.
Had the same issue, was assigning the fragment's view container an id programmatically, we removed this and assigned an id in its layout XML file and the issue went away.

Duplicate context menu icons when launching the app from background

I am testing my app with "Don't Keep Activities" options from developer options. When I try to background the app and launch it , am getting multiple duplicate icons added to the actionbar.
I am adding the context menu icon from the fragment. I have a string passed in a bundle to the fragment. When I background and launch the app, Android tries to recreate the activity and as setHasOptionsMenu(true); is called multiple time during this process and adds duplicate icons to the actionbar.
The following fixes this issue , but would like to know if this is the best approach
if(savedInstanceState == null) {
setHasOptionsMenu(true);
}
Maybe i'm a little late to answer your question, but it can be useful for future users.
The problem origin:
When you background the app and and launch it, the system will save and restore the state of your fragment. Also onCreate() method will be called and a new fragment will be added to your Activity, and you end up with multiple fragments running in your activity, each one added an item to the menu.
The solution:
(+) The correct fix: simply add a null check in your onCreate() method before adding your fragment (to avoid duplication)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
if (savedInstanceState == null) {
Fragment fragment = ...
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, fragment)
.commit();
}
}
(+) Or a workaround1: Clear your menu inside onCreateOptionsMenu() method of your fragment
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.your_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
(+) Or a workaround2: Call setHasOptionsMenu(true) only when savedInstanceState == null like you mentioned in OP.

Resources