what R.java file actually does and how - android

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.

Related

Kotlin classes with underscores

Please explain me what is the purpose and meaning of classes like StringsKt__StringsKt (i.e. doubled class name with one or more underscores in between) and, similarly, StringsKt__StringsJVMKt?
Strings are not the only example, there are many others too. I see them when looking into the structure of the classes.dex file in my .apk.
screenshot here
I'm asking because I faced a situation where I had to explicitly state some of them in my proguard-rules. The app crashed without it.
It is a generated file. A file like that will be generated if there are several Kotlin files named with same JvmName.
Let's take Strings.kt and StringNumberConversions.kt as an example:
// StringNumberConversions.kt
#file:kotlin.jvm.JvmMultifileClass
#file:kotlin.jvm.JvmName("StringsKt")
...
// Strings.kt
#file:kotlin.jvm.JvmMultifileClass
#file:kotlin.jvm.JvmName("StringsKt")
...
Both of them have #file:kotlin.jvm.JvmName("StringsKt"), so StringsKt and StringsKt__StringNumberConversionsKt are generated to distinguish them.

Obfuscate R.id class with or without proguard

I know in Proguard you are recommended to keep the fields names of the R inner classes like ID. Because ProGuard doesn't handle the layout xml files. You will end up with broken links
But is there away to obfuscate classes like R$id by some other means, even if it involves doing it before passing it to ProGuard, via Ant.
I am asking this because if you have a button with an id btnSaveArticle, for a hacker it becomes too easy to grasp what the code around is doing by looking at the name.
Could it be possible to copy all the source code, including the resource files to another folder and use ant to run regex to change the names of the R.ids as well as changing where they appear in the layout xml files, and then somehow running generate to re-create the R classes?
Or you could create translation class eg TR then map it to the fields in the R.class
eg.
TR.btnSaveArticle = R.id.DHTXM;
Where DHTXM is some meaning less word that can be used in the layout XML. But in the code you always refer to TR.btnSaveArticle, which will be obfuscated by proguard.
Are there ways to achieve this or am I wasting my time?
Just use below ,add it to you Proguard config file
-keepclassmembers class **.R$* {
public static <fields>;}
I am asking this because if you have a button with an id btnSaveArticle, for a hacker it becomes too easy to grasp what the code around is doing by looking at the name.
Using Hierarchy View, it would take them less than 30 seconds to determine the actual ID of the "Save Article" button, no matter what you name it. And I can envision even faster solutions with a bit of custom tooling.
am I wasting my time?
IMHO, yes.
With the default configuration for Android, ProGuard removes R classes entirely, unless your code performs introspection on them. In the latter case, ProGuard also preserves the fields with their original names, in order not to break the introspection.
That being said, the resource names can also be retrieved from the resource XML files, which ProGuard leaves untouched.
It is possible through Ant, as it allows you to set a different gen and res folder.
So what you do is copy from the originals to those folders and then you edit the files using regex to update to the new names.
You will need a translation class (eg D) like this to map it to the fields in the R.class, so in your code you can work with non obfuscated names.
public final class D{
public static final class id{
D.btnSaveArticle = R.id.btnSaveArticle //DHTXM;
Then you also need to create a different src folder and copy from the original folder. There you run a task to edit the D class so it becomes
D.btnSaveArticle = R.id.DHTXM;
I had to create a java program which is run through ant to swap the names to obfuscated names.
If you do something similar for strings, and styles your XML in the apk would end up looking like this:
<TextView
android:id="#+id/GnvCMa"
android:text="#string/OVuCbd"
style="#style/ZOVkuu.MGTRgZ" />
It is a little time consuming to setup, but once implemented it can be used for other projects.

Benefit of Declaring String as Resource in strings.xml file

I have read in many places that you should declare your String objects in your resource file but I haven't read about any benefits anywhere.
I have already declared all my Strings that I have in my layouts as resources but I haven't done so in my classes.
My question is:
What are the benefits of declaring Strings as a resource? Are there any memory benefits?
Internationalisation,
Keeping all of your strings in a single place (where they can be editted globally),
Changing strings based on device (mdpi/large/portrait)... I mean, it'd be really rare for this
last one, but it's possible.
Sharing the same string among many layouts (this will happen in any app which isn't tiny)
The top one I reckon is: Translations! Put a new strings.xml in the right folder and the app translates itself for each device.
But there's a matter of organisation too. Just like the layout, you normally don't build in the code, because that's not the place for it.
The code is to process stuff. The string is just one more of the resources that your code will use to show stuff on the screen.
One of the main benefits is for localization: you keep your code language-independent and just need to provide a different XML file for each language you want to support.

Cannot override library's xml resource with png resource in application?

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.

How can one bend Android's layout XML l10n-wise?

As you probably know, Mozilla aims to do the mobile UI on fennec as native Java/Android UI.
That includes using the layout XML files, which by default use stuff like
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="#string/text_a"
/>
with #string/text_a being resolved to text_a in a strings.xml file, doing l10n.
We'd like to use something else, and I wonder if/how we can hook that up in the XML files.
So, I'd love to get pointers to android source code that actually does the string lookup, for one.
And I have three ideas on how to hook up something custom, which are not fact-checked, basically because I haven't managed to find the code that does stuff yet:
#moz-l10n/text_a, with a java-implemented service giving back values for that resource type
moz:l10n="text_a" custom attribute that would get hooked up to post process the generated widgets
subclass the widgets we want to localize with our scheme, adding (2)
I hope that there are folks out here that have a good idea to point me to good paths or shoot some down.
PS: I'd appreciate a lack of bike-shed about whether android l10n scheme is good or not.
So, I'd love to get pointers to android source code that actually does the string lookup, for one.
android.content.res.Resources delegates to android.content.res.AssetManager and the getResourceText() method. That in turn dives into a native loadResourceValue() method. And you're on your own from there... :-)
1) #moz-l10n/text_a, with a java-implemented service giving back values for that resource type
Unless you are going to pre-process your faux resource files with your own build tools, generating valid Android resource files into the res/ directory, you cannot invent new resource types (e.g., #moz-10n). That would require modifications to the build tools and the firmware.
2) moz:l10n="text_a" custom attribute that would get hooked up to post process the generated widgets
3) subclass the widgets we want to localize with our scheme, adding 2)
Your option #3 is definitely possible and is fairly typical when creating custom widgets. It's conceivable that the techniques for it (usually involving a res/values/attrs.xml file with a declare-styleable resource) could somehow be applied to a standard widget class, but I've never seen that done. Of course, you could always do the pre-processing as in how you'd accomplish option #1.

Categories

Resources