I have a question about inheriting resources from android libraries.
Assume you have an android library project and in that library you put some resources (let's say strings for the moment) under the package name com.libexample
Now in an android project under the package name com.example, I reference the library I created earlier.
If I want to use one of the strings of the library I can get it by using
getString(com.libexample.R.string.test_string);
My question is, is it possible for a string resource in my main project to get assigned the same integer ID as a string in my library? Cause if it is, then the above code statement would in fact be equal to :
getString(R.string.new_string);
assuming that the new_string recourse was assigned the same ID as the test_string resource.
Apparently the compiler adds the resources under the same generated R.java file automatically which prevents any conflicts.
Related
I created a simple Android project out of my curiosity. It contains two modules: app and lib. Each module has its own package name. I created one string resource in the lib module and one string resource in the app module. Like this:
<string name="my_str">my_str_from_lib</string>
<string name="my_str">my_str_from_app</string>
Then I set the texts to two TextViews in the app module:
fromLib.text = resources.getString(ru.maksim.sample.lib1.R.string.my_str) // here I expected to see the string from the lib.
fromApp.text = resources.getString(R.string.my_str)
In both cases it was my_str_from_app
I ran Lint and thought it would detect the fact of resource overriding. But it didn't.
Is there a chance to detect this situation? Not necessarily with Lint. Other tools suit me too.
Well you can do a global search in your root folder. Find all instances of my_str and make sure its only the string.xml in your app that uses it as name.
The answer here is a script that parses a resulting XML to which all the string from the main app module and all its libraries are merged and finds all the duplicates.
I have two Android projects, a main one (package name com.adip.sampler) and a library that is added to main (package name com.samples.projb). In both of them in resources I have an integer-array with same key: my_int_values:
In main project:
<integer-array name="my_int_values">
<item>10</item>
<item>20</item>
<item>30</item>
<item>40</item>
<item>50</item>
<item>60</item>
<item>70</item>
<item>80</item>
</integer-array>
while in library:
<integer-array name="my_int_values">
<item>34</item>
<item>35</item>
<item>36</item>
<item>37</item>
</integer-array>
In main project from an activity if I am investigating what are the values from these arrays (both main project and library):
protected void showLocalStrings() {
Log.d("RESSampler", "In Main: " + Arrays.toString(getResources().getIntArray(com.adip.sampler.R.array.my_int_values)));
Log.d("RESSampler", "In Libr: " + Arrays.toString(getResources().getIntArray(com.samples.projb.R.array.my_int_values)));
}
then I'm seeing this in Logcat:
In Main: [10, 20, 30, 40, 50, 60, 70, 80]
In Libr: [10, 20, 30, 40, 50, 60, 70, 80]
It seems that main project is overriding the values defined in library array ... I doubled checked if I am reading from resources with correct key and that is ok. Until I took a look in each generated R class. In the main project this is what I have for com.adip.sampler.R.array.my_int_values:
public static final class array {
public static final int my_int_values=0x7f060000;
}
while in library project com.samples.projb.R.array.my_int_values:
public static final class array {
public static final int my_int_values = 0x7f060000;
}
Android tool has generated the same value, so no wonder I am getting this behavior. I can get rid of this behavior if I change the key from one of the integer arrays, but imagine that you have some big projects with a lot of resources, dependency libraries and sooner or later you may bump into this kind of issue: having the same type of resources with the same key value (I've checked with string and with string-array and above behavior appears there as well). So the questions would be:
Why this issue appears? Or if it's not an issue what explains this behavior?
How to avoid it best? I am guessing that trying to have some kind of uniqueness in defining the keys will do the trick, but developers tend to be lazy ...
This appears using multiple variants of latest ADTs and Eclipse versions (Juno and Indigo). Checked on Windows only.
Reading from Library Projects at Android Developers, there are many references where they clearly say merging happens at build time and resources with same IDs overwrite each other.
For resources with same ID from a library and application
In cases where a resource ID is defined in both the application and
the library, the tools ensure that the resource declared in the
application gets priority and that the resource in the library project
is not compiled into the application .apk. This gives your application
the flexibility to either use or redefine any resource behaviors or
values that are defined in any library.
For resources with same ID from two libraries
... your application can add references to multiple library projects, then
specify the relative priority of the resources in each library. This
lets you build up the resources actually used in your application in a
cumulative manner. When two libraries referenced from an application
define the same resource ID, the tools select the resource from the
library with higher priority and discard the other.
Solution suggested in documentation
Use prefixes to avoid resource conflicts
To avoid resource conflicts for common resource IDs, consider using a
prefix or other consistent naming scheme that is unique to the project
(or is unique across all projects).
How to set priority in libraries from command line
If you are adding references to multiple libraries, note that you can
set their relative priority (and merge order) by manually editing the
project.properties file and adjusting the each reference's .n index as
appropriate.
Personally, I would change the names of the resources. If you read anything about naming conventions, it should be something meaningful and "my_int_array" isn't really too helpful, especially in a library that other people or project could potentially use.
Ideally, you want to be able to forget about this for 6 months, come back and look at it and know what that array is for/contains, without having to delve through code to deduce what the array is for by what's done with it.
This post; https://stackoverflow.com/a/7249410/1222199 contains a few different answers on naming conventions.
Finally, not sure about the conflict, couldn't dig anything up. I'm guessing it's to do with the way it's automatically generated, might be worth logging it as a bug and see if you get any response from the development team.
I have been working on a simple android tutorial and while browsing through the project folders I found this R.java file in gen folder...
When I opened it seemed to me as a mess...
first R itself is a class.
it had multiple Inner classes defined within eg drawable,id,layout,etc.
and that inner classes had lots of variables declared as below which were assigned with hex values
public static final int addr=0x7f080003;
...
...
and much more
R is auto generated and acts as some pointer for other files
Questions for R.java
what it is basically for
how it works
why
values are in hex
what role did it performs while the actual application is running
"Acts as some pointer to other files" is actually absolutely correct, now the question is which files it points to how it is done.
What does it contain?
R file contains IDs for all the resources in the res folder of your project and also some additional IDs that you define on your own (in the layouts, for example). The IDs are needed for the Android resource management system to retrieve the files from the APK. Each ID is basically a number which corresponds to some resource in the resource management system.
The file itself is needed so you can access or reference the resource from code by giving the ID of the resource to the resource manager. Say, if you want to set the view in the activity, you call
setContentView(R.layout.main);
main in the R file contains the number which is understood by the Android resource management system as the layout file which is called main.
Why is it better than just plain file names?
It's harder to make a mistake with the generated fields. If you write the field name incorrectly, your program won't compile and you will know that there's an error immediately. If you write an incorrect string, however, the application won't fail until it is launched.
If you want to read more on this topic, you should check the Android documentation, especially the Accessing Resources part.
This holds your resource ids. So when you do something like
TextView tv = (TextView) findViewById(R.id.mytextview);
it looks up your id here for that View, layout, etc... This way the app has an easy way to look up your ids while you can use easy to remember names. Anytime you create a resource it automatically creates an id for it and stores it here. That's why you never want to try and edit this file yourself.
One way to think about how valuable R.java is, imagine a world without it. Its amazing how android brings the xml and java world together to help avoid coding the UI manually completely. With legacy java building UI using the java language was a pain. Invaluable.
With Android you can not only build your UI using only xml, but also see it while you build it. Invaluable.
Every element in the xml can be referenced in the java code WITHOUT writing a single line of code to parse the xml :). Just R.id.nameOfElement. Invaluable.
Rapid development is beautifully done in android. Imagine if iPhone would have 5000 screens to fit that one piece of code, they would crumble on their XCode. Google has done a wonderful job with just R.java. Invaluable.
I have an Android library MyLib containing everything I need for my app (targeting Android 2.2). This library has an XML resource:
drawable/main_background.xml
In my Application MyApp project I reference MyLib. Here I want to override specific resources (i.e. branding). So I added a background image in MyApp:
drawable/main_background.png
Eclipse keeps giving me this error:
[com.mycom.mylib.myapp] res\drawable\main_background.xml:0: error: Resource entry main_background is already defined.
[com.mycom.mylib.myapp] res\drawable\main_background.png:0: Originally defined here.
How can I override the resource in the library project?
You cannot simply override resource ID (it's the resource ID you are overriding, not the actual file) with a file with different extension in Android SDK. However, you can do the trick by putting in your project xml file with the same name (main_background.xml) and fill it in a proper way to display your new file (main_background.png), which you need to rename earlier. All syntax you need is descibed here:
http://developer.android.com/guide/topics/resources/drawable-resource.html
, in your case it could be simply (assuming you put this in your non-library project as main_background.xml, and you have your new png as main_background_new.png):
<?xml version="1.0" encoding="utf-8"?>
<bitmap
xmlns:android="http://schemas.android.com/apk/res/android"
android:src="#drawable/main_background_new" />
With above solution, you could refer to #drawable/main_background from your project and it should use your file included with that project, instead of a library one.
[com.mycom.mylib.myapp] res\drawable\main_background.xml:0: error: Resource entry main_background is already defined.
[com.mycom.mylib.myapp] res\drawable\main_background.png:0: Originally defined here.
I don't believe you can have the same file name even with different extensions. Try naming the png something else.
Now, i've not used overriding, So this seems odd as you'd expect this to be how you override the asset. However i think you've either got the two assets in your lib named the same. And that in your project it might be ok to have an asset with the same name. I would however check that its ok to have different types. XML is different than png, and if you access the asset from code you could get type errors.
Let me clarify the above point. I understand that a library project can have an item with the same Resource ID as an item in your application.
However the error above suggests that both main_background.png and main_background.xml are in the same project ([com.mycom.mylib.myapp]) which i don't believe is correct.
Further reading
This page describes the various types of project including the library project http://developer.android.com/tools/projects/index.html
Now i don't know where i got the impression from but having looked again it simply doesn't state anywhere that you can override a resource by using the same resource name. God knows why i thought that was a feature.
So no, the same rule applies as far as i can tell, that resources have to be named uniquely even across library projects, otherwise the generated resource ids will conflict. (The error your getting)
What is explained is how resource conflicts are managed.
Resource conflicts Since the tools merge the resources of a library
project with those of a dependent application project, a given
resource ID might be defined in both projects. In this case, the tools
select the resource from the application, or the library with highest
priority, and discard the other resource. As you develop your
applications, be aware that common resource IDs are likely to be
defined in more than one project and will be merged, with the resource
from the application or highest-priority library taking precedence.
The system will use the resource with the highest priority, discarding everything else. Whats odd, is that you would think that a compile error wouldn't occur as the compiler should be discarding the resource. This makes me believe that the original poster had the similarly named assets in the same project, and not across the lib and project.
I haven't read anywhere that this is actually an intended feature. Got any links to say otherwise? (comment them)
So one 'solution' to this problem, which I do not consider to be an answer is the following:
Define an XML document in the library in question (we'll call it bunny.xml), and have it refer to another xml of a similar name (bunny_drawn.xml) with the actual content to be displayed.
Then, in the target project, override bunny.xml with another and use it to refer to an image with a different name instead - bunny_image.png
This does not however solve the problem, firstly because we aren't technically overriding a png with an xml (although the effect is somewhat close to that). Secondly because one of the key features of overriding resources is they are overridden, i.e. they are NOT compiled into the APK:
the tools ensure that the resource declared in the application gets
priority and that the resource in the library project is not compiled
into the application .apk
But the bunny_drawn.xml will still be compiled in! We can sort-of overcome the second point, by not only defining the image to be replaced in the target APP, but also replacing the old target bunny_drawn.xml with a blank xml. (or, as Fenix pointed out, you can have the contents of bunny_drawn.xml inside bunny.xml in the first case - the fact still remains that the resource ID can't be replaced...)
So my final conclusion is that this need to be submitted as a bug in the Developer Tools.
My application depends on a library project.
The menu.xml file is within the application project.
All the java code is within the library project, including the menu handler code onOptionsItemSelected().
Is there a way to access the application resources from library project ? I'd like to write something like this, which is currently impossible, since menu items are not visible from the library:
if ( item.getItemId()==R.id.settings ) {
...
}
Yes you can if you know the package name of your library. See: Resources#getIdentifier
You can do:
getResources().getIdentifier("res_name", "res_type", "com.library.package");
ex:
R.id.settings would be:
getResources().getIdentifier("settings", "id", "com.library.package");
You should really just include a version of the menu.xml resource in your library project. If you want to have a different menu.xml in your application, you can do that and it will override the copy from the library project.
From the Library Projects docs:
In cases where a resource ID is defined in both the application and the library, the tools ensure that the resource declared in the application gets priority and that the resource in the library project is not compiled into the application .apk. This gives your application the flexibility to either use or redefine any resource behaviors or values that are defined in any library.
I found #triad's solution with Resources.getIdentifier(String, String, String) to be somewhat error-prone:
the String-literal resource identifiers aren't checked by the IDE
multiple sequential String arguments to a single method are easy to use incorrectly.
I found this approach to work better for me:
String libString = context.getString(example.library.pkg.R.string.library_string)
Where the library's package is example.library.pkg.
The library's R class is resolved at compile-time, so your IDE will tell you if you referenced it correctly
Not importing the library's R class allows you to still use your own local R later,
and explicitly marking the external resource usages makes them easier to spot.