android how and when to use getSupportFragmentManager (newbie is confused) - java

I'm just getting started with Android development and am trying to follow an example in a book and it's not compiling.
The book has me creating a Fragment in my application and then interacting with that fragment in my MainActivity; specifically the book says to call getFragmentManager().findFragmentByID(..) in the main activity, in order to access this fragment, but this is returning an error that the results of getFragmentManager can't be converted to the right type.
So I started poking around and noticed that by default, my installation of Android Studio is apparently using the v4 support library and so my Fragments are v4 Fragments and not the standard sdk Fragments (please correct me if I'm misinterpreting the situation).. and because of this, the call to getFragmentManager is apparently not the right way to get at a v4 Fragment.
Apparently I'm supposed to be calling getSupportFragmentManger instead, but Android Studio says that's not defined. I tried guessing what kind of import I might need in my main activity for it to be able to see getSupportFragmentManager, but I can't seem to figure that out either.
Any help at straightening this out would be very much appreciated.
I have looked at the v4 docs on google's site but honestly to a newbie it's not clear what calls go with what.
Michael

If you want to use support classes in your Activity, then it should also be an Activity from support library.
To accomplish that your Activity must extend AppCompatActivity.
public class MainActivity extends AppCompatActivity {
//Your code that calls getSupportFragmentManager()
}

You should choose some options here:
use android.support.v7.app.AppCompatActivity or android.support.v4.app.FragmentActivity as a parent of your activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager supportFragmentManager = getSupportFragmentManager();
}
}
Instead of android.support.v4.Fragment, use android.app.Fragment and simply use android.app.FragmentManger
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android.app.FragmentManager fragmentManager = getFragmentManager();
}
}

Related

How to use instance of API from Main Activity in Fragments?

If i create an instance of an API in Main Activity, can i use it in fragments so i don't need to create that instance again? Example:
public class MainActivity extends AppCombatActivity {
CustomApi customApi;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customApi = new CustomApi(this, key);
}
}
How can i access this customApi instance in fragments created by the MainActivity without creating an instance of this CustomApi again?
Fragment has access to its Activity, so you can do something like this in your Fragement:
CustomApi customApi = ((MainActivity) getActivity()).customApi;
customApi.method1(...);
This is a bit brute force, but is a simple and easy way to do the job. This assumes that your Fragment is only used by a single Activity. If your Fragment is used by multiple activities, you could define an Interface and have all parent activities implement that interface and access the customApi that way.
A cleaner, more Android-approved, more professional approach would be to use a ViewModel. The ViewModel is shared by the Activity and all of its Fragments and you could manage the custom API reference in the ViewModel. For some examples of how to use ViewModel to communicate between Activity and Fragment, you can look here:
https://developer.android.com/guide/fragments/communicate

Android create a PreferenceFragment without a PreferenceActivity

I added a side menu to my Application and I managed to change the content with fragments. Now I am trying to do the Preferences, but I don't want to use a PreferenceActivity because I want to do my application with fragments because I don't want to do the NavigationDrawer twice (For my main activity displaying the fragments and for the PreferenceActivity).
I found the class PreferenceFragment but after alot of research I found out that appearantly it just is a part of the SettingsActivity and when I try to addPreferenceFromResouce in the PreferenceFragment and then launch the fragment, it crashes.
So basically I am trying to find a way to display a SettingsFragment without any extra activity just by calling fragmentManager.beginTransaction().replace(R.id.contentFrame, settingsFragment).commit() just as I do with my different fragments.
I hope I asked my question understandable (I am sorry if I didn't). Thanks for your time and your help.
I found the solution myself now. It wasn't very hard.
I simply created a normal PreferenceFragment and you can use it like any other fragment without a PreferenceActivity.
public class PreferenceFragment extends android.preference.PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}}
I then replaced it using
getFragmentManager().beginTransaction().replace(R.id.contentFrame, preferenceFragment).commit();
as you normally would.
This worked great for me. I hope it also does for you.

Roboguice causing strange exceptions

In addition to my former question, which hasn't been answered yet, I'm still having lot of problems getting Roboguice up and running. My primary goal is to create a simple activity as well as a navigation drawer using a separate fragment with Roboguice, however nothing works at all.
What I tried:
Roboguice version 2.0
Roboguice version 3.0b-experimental
Android w/ and without support libraries
Example code:
public class MainActivity extends RoboActivity {
#InjectFragment
private NavigationDrawerFragment _navigationDrawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_navigationDrawerFragment.init();
}
}
public class NavigationDrawerFragment extends RoboFragment {}
I tried several things, including using a standard Fragment both from the support library and default Android SDK and implementing the injection methods myself as well as deriving from RoboFragment and what not.
Errors include:
NullPointerException -> Sometimes RoboGuice doesn't inject anything. The _navigationDrawerFragment is null
Type exceptions -> Sometimes RoboGuice tells me that my class doesn't derive from fragment
etc.
Are there any examples where someone has succesfully used RoboGuice together with a navigation drawer (Android SDK, not Sherlock)?

android phonegap cordova webview events

In my code, I am properly using webview and handling onPageFinished and shouldOverrideUrlLoading events. Now I redefined it as DroidGap in order to handle its functions. I should then continue intercepting these events because if I override it, phonegap functions are not executed anymore (as I do on iOS)! how to embed it and handle described events? thank you
public class webPush extends Activity implements CordovaInterface{
You don't need to redefine it to DroidGap. You can use your own implementation using CordovaInterface and just copy the functions you need from DroidGap java class. That way you can edit existing code or add your own.
This is what the official PhoneGap documentation says:
Modify your activity so that it implements the CordovaInterface. It is recommended that you implement the methods that are included. You may wish to copy the methods from /framework/src/org/apache/cordova/DroidGap.java, or you may wish to implement your own methods
Embedding Cordova WebView on Android
Embedding Webview we can do like this way basically
public class CordovaViewTestActivity extends Activity implements CordovaInterface {
CordovaWebView cwv;
/* Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cwv = (CordovaWebView) findViewById(R.id.tutorialView);
cwv.loadUrl("file:///android_asset/www/index.html");
}
If still you are getting the error ,kindly post your code along with logcat output,It will be easy to resolve the issue..

ActionBar in PreferenceActivity

In my application I am using the new Action Bar Compatibility sample from Google (located at <sdk>/samples/android-<version>/ActionBarCompat) which works great. The only problem I have is applying this to my PreferenceActivity in order to get a screen like the settings in the Android Market (see picture).
To fill the ActionBar with icons, each Activity must extend the ActionBarActivity class. The problem is that my Activity already extends PreferenceActivity and in Java classes can not extend more than one class.
There must be a way to get the ActionBar together with a PreferenceScreen. I would be glad if anybody could provide a solution for this common issue.
P.S.: A solution like in How to add a button to PreferenceScreen does not fit because the ActionBar is actually the title bar and so this is more a Java than a layout thing.
Edit: My answer below is rather hacky and it seems like it is now outdated (for pre Android 3.0) Have a look at the other answers for less hacky and more current solutions ~pyko 2014-09-01
I managed to get it working - not sure if this is the nicest/cleanest solution, but it works.
Had to make the following changes:
Make a copy of ActionBarActivity and have the new class extend PreferenceActivity
public abstract class ActionBarPreferenceActivity extends PreferenceActivity {
// contents exactly the same as 'ActionBarActivity'
}
Modify onCreate() in ActionBarHelperBase.java slightly - make a special case for PreferenceActivity classes
#Override
public void onCreate(Bundle savedInstanceState) {
// If the activity is a PreferenceActivity, don't make the request
if (!(mActivity instanceof PreferenceActivity)) {
mActivity.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
}
Have your PreferenceActivity extend this class and add request for FEATURE_CUSTOM_TITLE before you call super.onCreate()
public class MyPreferenceActivity extends ActionBarPreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); // add this line
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
// etc etc
}
// etc etc
}
As far as I can tell, changes 2 and 3 are needed because for PreferenceActivity:
"As soon as you call super.onCreate(), the ViewGroup will be set up and so, you are not allowed to change the Window's parameters." (see Oliver's comment to the answer)
I guess the order of how components in PreferenceActivity activities are created is different to plain Activity activities .
If you want to try a PreferenceFragment implementation based on support-v4 Fragment:
https://github.com/kolavar/android-support-v4-preferencefragment
I´m using it by myself and it isnt much work turning PreferenceActivity into PreferenceFragment.
Can you just clone the code for ActionBarActivity, and change "extends Activity" to "extends PreferenceActivity"? Then extend your new class instead of ActionBarActivity.
From all the Google apps I've seen, though, it seems unusual to put buttons in the action bar of a PreferenceActivity. If you're not putting buttons on it, you could just use a values-v11 alternate style resource to show the holo theme, and set that style in the manifest for your PreferenceActivity.
I used in my application this actionbar
https://github.com/johannilsson/android-actionbar and it's work great with this thread How to add a button to PreferenceScreen
I'd like to thank to #pyko providing a great answer, but it has problem that it won't work well on HoneyComb and above. well you can have a hack way to get it around like #AndroidDev said;
But #pyko is gonna pollute the ActionBarHelperBase class, and #AndroidDev isn't very transparent.The best way is to create ActionBarActivityPreferences who extends from PreferenceActivity; and in onCreate method, change the order of calling parent method:
#Override
protected void onCreate(Bundle savedInstanceState) {
//IMPORTATNT: MAKE SURE actionBarHelper called before super;
//as super oncreate of prefenceactivity is actuallying setting the content view
mActionBarHelper.onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
}
why calls 'mActionBarHelper.onCreate(savedInstanceState);' before 'super.onCreate(savedInstanceState);' , that is because super (i.e. PreferenceActivity) is actually setting the content view in its onCreate method, which would cause crash ("requestFeature() must be called before adding content'). SO what you need do is to swap the order, make sure ' mActionBarHelper.onCreate(savedInstanceState);' is called before super.
In this way, we don't need to pollute the 'ActionBarHelperBase' yet we keep SettingActivity very clean because we encapsulate the tricky detail to 'ActionBarActivityPreferences' and bang!
You can easily add action bar in preference activity by the following changes:
In AndroidManifest.xml :
<activity
android:name=".activity.SettingsActivity"
android:theme="#style/SettingsTheme"
android:label="Settings"/>
In v21/styles.xml
<style name="SettingsTheme" parent="#android:style/Theme.Material.Light.DarkActionBar">
<item name="android:colorPrimary">#color/colorPrimary</item>
<item name="android:colorPrimaryDark">#color/colorPrimaryDark</item>
</style>
In v14/styles.xml for Back API support:
<style name="SettingsTheme" parent="#android:style/Theme.Holo.Light.DarkActionBar">
<item name="android:actionBarStyle">#style/ActionBar.V14.Movie.NoTitle</item>
</style>
Thanks, just an update, you need to add an if statement before the Custom Title line to support HoneyComb and above.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
You can get a ActionBarSherlock lib and let you code extends SherlockPreference;

Categories

Resources