We've been using the Navigation component in our project but have stumbled across an issue which seems unique to our project and the JetBrains Android plugin. I can't pinpoint the exact point it started happening but I noticed it after the release of AS 3.2.
The project builds fine however when editing a navigation XML things such as auto-complete and highlighting are broken and the Android Support Plugin throws this error:
java.lang.IllegalArgumentException: Multiple entries with same key: org.jetbrains.android.dom.navigation.NavigationSchema$TypeRef#0=org.jetbrains.android.dom.navigation.NavigationSchema$NavigatorKeyInfo#17d69e53 and org.jetbrains.android.dom.navigation.NavigationSchema$TypeRef#0=org.jetbrains.android.dom.navigation.NavigationSchema$NavigatorKeyInfo#442c4fde
at com.google.common.collect.ImmutableMap.conflictException(ImmutableMap.java:215)
at com.google.common.collect.ImmutableMap.checkNoConflict(ImmutableMap.java:209)
at com.google.common.collect.RegularImmutableMap.checkNoConflictInKeyBucket(RegularImmutableMap.java:147)
at com.google.common.collect.RegularImmutableMap.fromEntryArray(RegularImmutableMap.java:110)
at com.google.common.collect.ImmutableMap$Builder.build(ImmutableMap.java:393)
at org.jetbrains.android.dom.navigation.NavigationSchema.buildCacheKeys(NavigationSchema.java:488)
at org.jetbrains.android.dom.navigation.NavigationSchema.init(NavigationSchema.java:479)
at org.jetbrains.android.dom.navigation.NavigationSchema.createIfNecessary(NavigationSchema.java:389)
at org.jetbrains.android.dom.AttributeProcessingUtil.processNavAttributes(AttributeProcessingUtil.java:408)
at org.jetbrains.android.dom.AttributeProcessingUtil.processAttributes(AttributeProcessingUtil.java:596)
at org.jetbrains.android.dom.AndroidDomExtender.registerExtensions(AndroidDomExtender.java:57)
at org.jetbrains.android.dom.AndroidDomExtender.registerExtensions(AndroidDomExtender.java:29)
at com.intellij.util.xml.reflect.DomExtenderEP.extend(DomExtenderEP.java:83)
at com.intellij.util.xml.impl.DynamicGenericInfo.runDomExtenders(DynamicGenericInfo.java:134)
at com.intellij.util.xml.impl.DynamicGenericInfo.lambda$checkInitialized$0(DynamicGenericInfo.java:64)
at com.intellij.openapi.util.RecursionManager$2.doPreventingRecursion(RecursionManager.java:98)
at com.intellij.util.xml.impl.DynamicGenericInfo.checkInitialized(DynamicGenericInfo.java:63)
at com.intellij.util.xml.impl.DynamicGenericInfo.getAttributeChildrenDescriptions(DynamicGenericInfo.java:241)
at com.intellij.util.xml.impl.DynamicGenericInfo.processAttributeChildrenDescriptions(DynamicGenericInfo.java:254)
at com.intellij.util.xml.impl.DomSemContributor.lambda$registerSemProviders$5(DomSemContributor.java:199)
at com.intellij.semantic.SemServiceImpl$2.lambda$registerSemElementProvider$0(SemServiceImpl.java:93)
at com.intellij.semantic.SemServiceImpl.createSemElements(SemServiceImpl.java:190)
at com.intellij.semantic.SemServiceImpl.getSemElements(SemServiceImpl.java:161)
at com.intellij.semantic.SemService.getSemElement(SemService.java:37)
at com.intellij.util.xml.impl.DomManagerImpl.getDomHandler(DomManagerImpl.java:390)
at com.intellij.util.xml.impl.GenericValueReferenceProvider.getReferencesByElement(GenericValueReferenceProvider.java:47)
at com.intellij.psi.impl.source.resolve.reference.ReferenceProvidersRegistryImpl.getReferences(ReferenceProvidersRegistryImpl.java:135)
at com.intellij.psi.impl.source.resolve.reference.ReferenceProvidersRegistryImpl.mapNotEmptyReferencesFromProviders(ReferenceProvidersRegistryImpl.java:123)
at com.intellij.psi.impl.source.resolve.reference.ReferenceProvidersRegistryImpl.doGetReferencesFromProviders(ReferenceProvidersRegistryImpl.java:102)
at com.intellij.psi.impl.source.resolve.reference.ReferenceProvidersRegistry.getReferencesFromProviders(ReferenceProvidersRegistry.java:50)
at com.intellij.psi.impl.source.resolve.reference.ReferenceProvidersRegistry.getReferencesFromProviders(ReferenceProvidersRegistry.java:44)
at com.intellij.psi.impl.source.xml.XmlAttributeValueImpl.getReferences(XmlAttributeValueImpl.java:110)
at com.intellij.codeInsight.daemon.impl.analysis.XmlHighlightVisitor.checkReferences(XmlHighlightVisitor.java:439)
at com.intellij.codeInsight.daemon.impl.analysis.XmlHighlightVisitor.visitXmlAttributeValue(XmlHighlightVisitor.java:406)
at com.intellij.psi.impl.source.xml.XmlAttributeValueImpl.accept(XmlAttributeValueImpl.java:61)
at com.intellij.codeInsight.daemon.impl.analysis.XmlHighlightVisitor.visit(XmlHighlightVisitor.java:587)
at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass.runVisitors(GeneralHighlightingPass.java:353)
at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass.lambda$collectHighlights$5(GeneralHighlightingPass.java:286)
at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass.analyzeByVisitors(GeneralHighlightingPass.java:313)
at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass.lambda$analyzeByVisitors$6(GeneralHighlightingPass.java:316)
at com.intellij.codeInsight.daemon.impl.analysis.XmlHighlightVisitor.analyze(XmlHighlightVisitor.java:597)
at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass.analyzeByVisitors(GeneralHighlightingPass.java:316)
at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass.lambda$analyzeByVisitors$6(GeneralHighlightingPass.java:316)
at com.intellij.codeInsight.daemon.impl.DefaultHighlightVisitor.analyze(DefaultHighlightVisitor.java:71)
at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass.analyzeByVisitors(GeneralHighlightingPass.java:316)
at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass.collectHighlights(GeneralHighlightingPass.java:283)
at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass.collectInformationWithProgress(GeneralHighlightingPass.java:227)
at com.intellij.codeInsight.daemon.impl.ProgressableTextEditorHighlightingPass.doCollectInformation(ProgressableTextEditorHighlightingPass.java:84)
at com.intellij.codeHighlighting.TextEditorHighlightingPass.collectInformation(TextEditorHighlightingPass.java:69)
at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.lambda$null$1(PassExecutorService.java:423)
at com.intellij.openapi.application.impl.ApplicationImpl.tryRunReadAction(ApplicationImpl.java:1171)
at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.lambda$doRun$2(PassExecutorService.java:416)
at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:582)
at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:532)
at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:87)
at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.doRun(PassExecutorService.java:415)
at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.lambda$run$0(PassExecutorService.java:391)
at com.intellij.openapi.application.impl.ReadMostlyRWLock.executeByImpatientReader(ReadMostlyRWLock.java:147)
at com.intellij.openapi.application.impl.ApplicationImpl.executeByImpatientReader(ApplicationImpl.java:222)
at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.run(PassExecutorService.java:389)
at com.intellij.concurrency.JobLauncherImpl$VoidForkJoinTask$1.exec(JobLauncherImpl.java:161)
at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
We're running the latest version of the navigation component (2.0.0-rc2) and and I've tried all the usual fixes (Invalidate Caches & Restart etc). I've tried using navigation in fresh projects and it seems to work without this error being thrown.
I have tried removing all nav XMLs from our project and then adding in a completely blank XML but it still throws the error. I delved into the source of the plugin and it seems this occurs when the plugin is initially processing the nav file for the design view which doesn't make sense if it's throwing it for a fresh nav file.
I'm currently at a loss as to why this may be happening and any ideas would be greatly appreciated!
The short answer:
I fixed it by moving an anonymous class which extended androidx.navigation.Navigator to a separate class and adding the annotation #Navigator.Name(String name) with a unique name.
If you are also experiencing this issue check that in your project or its dependencies if there are any classes inheriting the Navigator class which are either missing the #Navigator.Name(String name) annotation or using non-unique strings as the name parameter. fragment and activity cannot be used as they are used already within the API.
Further info:
After further delving into the Android Support plugin source code to understand what's going on I've managed to solve the issue on our project.
When initiating the IDE functionality in the Android Support Plugin it goes through your project and any dependencies looking for any class which inherits the Navigator class and gives it a tag for the purpose of managing it in the XML files and design view. This tag is based on an annotation #Navigator.Name(String name). If no annotation is present a default value is used.
These tags have to be unique as they are used as the keys for building an immutable map of tags to navigator types. In our project we had an anonymous class which was extending Navigator class and had no annotation.
There is also an anonymous class extending Navigator within the navigation component source, specifically within the NavDeepLinkBuilder class. As there is only a single default value for the tags any other class inheriting Navigator with no annotation being present in your project or its dependencies will cause this issue.
I am a newbie at robolectric unit testing, i have a fragment which i want to test, ex, ScreenAFragment. This has a hierarchy as below,
ScreenAFragment -> MyAppFragment -> MyLibFragment -> SherlockFragment.
There are 2 problems,
The MyLibFragment has some code which links to a database and does other stuff which don't need to be tested as a 'unit test case'.
This MyLibFragment reference is also causing a "PackageManager#NameNotFoundException"
How do I go about testing this? My initial thought was create a ShadowMyLibFragment and config my test case #config(shadow={ShadowMyLibFragment.class}) to use this instead of the original class. Doesn't seem to be working at the moment, as it still seems to refer to the original library and throws the old error.
Any Solutions? I am using Robolectric 2.4 version.
I am porting an Xamarin-based Android app to be PCL'ified and MvvmCross'ified so we can target multiple mobile device platforms.
Since this is a line-of-business app where we can dictate the minimum Android OS version, we wish to avoid using the various v4 / v7 etc "Support libraries". We prefer to use all native components that are already part of the OS. So this basically means we only wish to target Jellybean and probably Android v4.2 upwards.
Unfortunately whilst there are lots of examples out there of using MvvmCross with ActionBarSherlock and the SupportActionBar (in a support library), there appears to be no examples of how to wire up MvvmCross with the native ActionBar using native Fragments as tabs.
I'm not expecting someone to post up swathes of code but would really appreciate if someone could give me a few pointers on the best approach to take to achieve this.
I will certainly blog about it once I have a working solution to benefit the whole MvvmCross/Xamarin community.
Thanks.
Probably the most important thing is to use MvvmCross - Hot Tuna Droid Full Fragment Support NUGet library. Then create activity that inherits from MvxActivity and fragment from MvxFragment.
ViewModel for tab fragment set in activity when create this class for TabEventArgs.FragmentTransaction.Add method used in ActionBar.Tab.TabSelected event handler like this:
var tab1 = new TabFragment1 {DataContext = ViewModel};
In TabFragment1 class you can use standard fluent binding method on bindingSet creted by
var bindingSet = this.CreateBindingSet<TabFragment1, MyViewModel>();
I don't know if it is a right way, but work.
I was trying the sample roboguice project in ActionBarSherlock library. It uses roboguice2.0b4.jar (a beta release) but when i replace it with the stable release roboguice2.0.jar I am getting
java.lang.IllegalArgumentException: com.actionbarsherlock.sample.roboguice.activity.AstroboyMasterConsole#40533b68 does not appear to be a RoboGuice context (instanceof RoboContext)
what can be done to resolve this issue.
Your activity (AstroboyMasterConsole) must implement the RoboContext interface, means you have to extend it from one of the classes below:
I'm looking to write preferences that can be applied to both 3.0 and pre-3.0 devices. Discovering that PreferenceActivity contains deprecated methods (although these are used in the accompanying sample code), I looked at PreferenceFragement and the compatibility package to solve my woes.
It appears, though, that PreferenceFragment isn't in the compatibility package. Can anyone tell me whether this was intentional? If so, can I easily target a range of devices (i.e. < 3.0 and >=3.0) or will I have to jump through hoops? If it wasn't intentionally excluded, can we expect a new release of the compatibility package? Or is there another workaround that is safe to use?
Discovering that PreferenceActivity contains deprecated methods (although these are used in the accompanying sample code)
The deprecated methods are deprecated as of Android 3.0. They are perfectly fine on all versions of Android, but the direction is to use PreferenceFragment on Android 3.0 and higher.
Can anyone tell me whether this was intentional?
My guess is it's a question of engineering time, but that's just a guess.
If so, can I easily target a range of devices (i.e. < 3.0 and >=3.0) or will I have to jump through hoops?
I consider it to be done "easily". Have two separate PreferenceActivity implementations, one using preference headers and PreferenceFragments, the other using the original approach. Choose the right one at the point you need to (e.g., when the user clicks on the options menu item). Here is a sample project demonstrating this. Or, have a single PreferenceActivity that handles both cases, as in this sample project.
If it wasn't intentionally excluded, can we expect a new release of the compatibility package?
You will find out when the rest of us find out, which is to say, if and when it ships.
Or is there another workaround that is safe to use?
See above.
The subtle implication of the answer from #CommonsWare is that - your app must choose between the compatibility API or the built-in fragment API (since SDK 11 or so). In fact that's what the "easily" recommendation has done. In other words, if you want to use PreferenceFragment your app needs to use the built-in fragment API and deal with the deprecated methods on PreferenceActivity. Conversely, if it's important that your app use the compat. API you will be faced with not having a PreferenceFragment class at all. Thus, targeting devices is not a problem, but the hoop-jumping happens when you have to choose one or the other API and thus submit your design to unforeseen workarounds. I need the compat. API so I'm going to create my own PreferenceFragment class and see how that works. In the worst case scenario I'll just create a normal (fragment) layout and bind the view components to the sharedprefs manually...ugh.
EDIT:
After trying and looking at the code at http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.0.1_r1/android/preference/PreferenceFragment.java?av=h -- creating my own PreferenceFragment isn't going to happen. It appears the liberal use of package-private in PreferenceManager instead of 'protected' is the main blocker. It really doesn't look like there's any security or really good motivation to have done that and it isn't great for unit-testing but oh well...less typing I guess...
EDIT v2:
Actually it did happen and it worked. It was definitely a headache to make the code work with the Compatibility API JAR. I had to copy about 70% the com.android.preference package from the SDK to my app and then wrestle with typically mediocre-quality Java code in Android. I used v14 of the SDK. It would have been much easier for a Goog engineer to do what I did, contrary to what I've heard some lead Android engineers say about this topic.
BTW - did I say "targeting devices is not a problem"? It totally is...if you use com.android.preference you are not going to be able to swap out with the Compatibility API without major refactoring. Fun log!
Building upon CommonsWare's answer as well as Tenacious' observations, I have come up with a single descendant class solution capable of targeting all current Android API versions with minimal fuss and no code or resource duplication. Please see my answer to the related question over here:
PreferenceActivity Android 4.0 and earlier
or on my blog:
http://www.blackmoonit.com/2012/07/all_api_prefsactivity/
Tested on two tablets running 4.0.3 and 4.0.4 as well as a phone running 4.0.4 and 2.3.3 and also an emulator running 1.6.
See PreferenceFragment-Compat from Machinarius. It was easy to drop in with gradle and I forget that it's even there.
compile 'com.github.machinarius:preferencefragment:0.1.1'
Important Update: The latest revision of the v7 support library now has a native PreferenceFragmentCompat.
On August 2015 Google released the new Preference Support Library v7.
Now you can use the PreferenceFragmentCompat with any Activity or AppCompatActivity
public static class PrefsFragment extends PreferenceFragmentCompat {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
}
You have to set preferenceTheme in your theme:
<style name="AppTheme" parent="#style/Theme.AppCompat.Light">
...
<item name="preferenceTheme">#style/PreferenceThemeOverlay</item>
</style>
In this way you can customize the preferenceTheme to style the layouts used for each preference type without affecting other parts of your Activity.
Tenacious's answer is correct, but here are some more details.
The reason you can't "create a normal layout and bind the view components to the sharedprefs manually" is that there are some surprising omissions in the android.preferences API. PreferenceActivity and PreferenceFragment both have access to critical non-public PreferenceManager methods, without which you can't implement a preference UI of your own.
In particular, to construct a Preference hierarchy from an XML file you need to use a PreferenceManager, but all of PreferenceManager's constructors are either package-private or hidden. The method of attaching the Preference onClick listeners to your activity is also package-private.
And you can't work around this by sneakily putting your implementation in the android.preferences package, because non-public methods in Android APIs are actually omitted from the SDK. With a bit of creativity involving reflection and dynamic proxies, you can still get at them. The only alternative, as Tenacious says, is to fork the entire android.preference package, including at least 15 classes, 5 layouts, and a similar number of style.xml and attrs.xml elements.
So to answer the original question, the reason Google didn't include PreferenceFragment in the compatibility package is that they would have had exactly the same difficulty as Tenacious and myself. Even Google can't go back in time and make those methods public in the old platforms (though I hope they do that in future releases).
My app target is API +14 but due to using support library for some fancy navigation, I couldn't use the android.app.Fragment and had to use android.support.v4.app.Fragment, but I also needed to have PreferenceFragment in place without large changes to code behind.
So my easy fix for having both worlds of support library and PreferenceFragment:
private android.support.v4.app.Fragment fragment;
private android.app.Fragment nativeFragment = null;
private void selectItem(int position) {
fragment = null;
boolean useNativeFragment = false;
switch (position) {
case 0:
fragment = new SampleSupprtFragment1();
break;
case 1:
fragment = new SampleSupprtFragment2();
break;
case 2:
nativeFragment = new SettingsFragment();
useNativeFragment = true;
break;
}
if (useNativeFragment) {
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, nativeFragment).commit();
} else {
if (nativeFragment != null) {
getFragmentManager().beginTransaction().remove(nativeFragment)
.commit();
nativeFragment = null;
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
}
}
I needed integrate Preferences into application's design and keep support for 2.3 android. So I still needed PreferencesFragment.
After some search I found android-support-v4-preferencefragment lib. This lib save a lot of time for copying and refactoring original PreferencesFragment as Tenacious said. Works fine and users enjoy preferences.