why does android create the R.java file - android

why not just leave the data( strings.xml, main.xml ) in the .xml files? why convert it into the R.java?
it seems that android can read xml ( eg. androidmanifest.xml ). so why not just leave the strins.xml data and main.xml data in .xml form and send those xml's to the android device?
I am new ... maybe I will eventually see that there is a lot more in the R.java other than mere static variables that derived directly from those .xml's.
thanks,
Shannon

so that you can easily reference you object that you have created in you layout, drawable and string files. this class represents all the resources that can be instantiated inside a code or can be used inside your coding

So that you can easily reference your resources ids from your code with the R class object avoiding compile errors, I think

If you have a bug in your program, you want it detected as early as possible.
If resources are retained as XML any bug will be found at runtime (either test-driven or user-driven). Testing can never prove the absence of all defects, so some bugs may be found by the users of your software!
However, if resources are converted to source in R then all references to them will be checked by the compiler. Any bugs (relating to resource references) are detected at this much earlier stage, long before your customers get to seem them.

Transferring the id references of the XML content into code makes it easy to use these references while coding and the correct usage is visible during compile time. So runtime exceptions are avoided.
I do not know if this is the core reason but that's what counts for me :-).

R.java is a handler to all the resources.
You create your resources, and the R.java automatically build a connection between your code and your res. You can easily fetch your various kind of resources from R, and android provide lots of API supporting R.java and its handlers(those ints). You dont need to manually open a stream to res files, do file reading, images decoding and etc. Its great convience.

R.java doesn't contain any data. It's generated by aapt during the build process when it prepares resources to pack them into the APK, including compiling XML files in a format that's easier to read and parse. R.java contains static int members that are only indexes to the packed resources.
See A Detailed Look at the Build Process, and also take a look into a project's bin/ folder.

Related

Android Studio - What is the Java Resources Folder?

I know there are two well-known folders where one can put resources.
The first is the /assets folder, the documentation says:
Contains file that should be compiled into an .apk file as-is. You can navigate this directory in the same way as a typical file system using URIs and read files as a stream of bytes using the AssetManager. For example, this is a good location for textures and game data.
The second is the /res folder, the documentation says:
Contains application resources, such as drawable files, layout files, and UI string. See Application Resources for more information.
Now i was wondering, there is a third option to create a resource folder "New > Folder > Java Resources Folder"
To me i looks like some part of the Android Plugin in IntelliJ because it has a little Android symbol in front of it .
Any ideas what the use of it could be? I couldn't find any documentation about it.
My first guess would be to use it in situations where you want to supply resources to a JVM Test.
In standard java world
Resources can be embedded directly in "your source tree" and used with Class's method getResource (see java documentation for a more precise description).
In android world
This practice is not recommanded (do not work at all, because such resources are removed from generated APK). You can still declare Java resources folders (see build.gradle :
sourceSets {
main {
resources.srcDirs = ['src/main/java/yourresourcesfolder']
}
}
And the result in the apk :
Conclusion
As resources's folder tree is removed,using java's resource folder become from my point of view, useless (in an android projet). Using android's asset folder is a better choice (also avoid resource's name conflict, but it's an another story :D )
This post is a bit old, but I want to bring an answer that explain one use case for the java resources directory on Android. If this folder exists in the options of a project it's because something can be done with it...
Enters the Service Loader, that helps to connect other services (aka libraries) into your main app, it can be used as a Gateway for your Android library to extend the functionality of a feature, exposing only the interfaces or abstract classes, with the Service Loader providing the implementation instead of your project having direct access to them.
Here is an example of how it's implemented. So, in summary the folder (META-INF/services) and files you have to create in order to use the Service Loader on an Android App, NEED to be inside this Java Resources Folder, otherwise your provider won't be able to see any implementation.
You can see it working in my sample here if you want to check it out: https://github.com/difereto-globant/test-library-feature/tree/1.0.9.

Can someone actually explain the workings of Resource.Designer.cs?

I routinely have problems during project builds where Resource.Designer gets generated but will no longer compile. My search engine shows that I'm not the only one that has this problem, but I've also not found any reliable "fix" for when it happens.
For example, right now I have a project that works just fine, but if I add a reference to a NuGet library (that I created) then the app will no longer compile because of loads of errors in Resource.Designer.cs.
On another project, I simply upgraded Xamarin Forms and now I can no longer compile, again due to a load of errors in Resource.Designer.cs.
Of course the immediate issue is "how do I fix the errors in these projects" but really I want to understand what is fundamentally going on here. What causes Resource.Designer to get generated and regenerated? What algorithm is used to decide what items get put into that file? Why do we so often end up with a file getting generated that then cannot actually compile? Why is it not getting the references it needs for those items?
I'd really like to understand this at a fundamental level so that once I get past the current thing causing me headaches, I can avoid it in the future when it comes up again (and I most certainly will come up again).
Resource.Designer.cs is synonymous with R.java in Android. Which of course is an application's resources that are referred to by a generated constant Resource ID.
These items are usually defined in your Xamarin.Android's .csproj via:
<AndroidResgenClass>Resource</AndroidResgenClass> (This might be outdated)
or
<AndroidResgenFile>Resources\Resource.Designer.cs</AndroidResgenFile> (Current)
This is part of the Android Build process in which the aapt tooling will generate respective constant resource IDs per each resource defined in your project(res/ - Android, Resources/ - Xamarin.Android). These are then processed into binary form and embedded into the .apk. Thus the Resource.designer.cs is generated after a successful aapt.
It then goes a bit further to define a Resource in a specific Resource Type:
http://code.google.com/android/reference/android/R.html
anim
animator
array
attr
bool
color
dimen
drawable
fraction
id
integer
interpolator
layout
menu
mipmap
plurals
raw
string
style
styleable
transition
xml
Since aapt is called in the Android Build tooling, it is highly recommended to not manually invoke it unless you understand the complete Android build process.
https://developer.android.com/studio/command-line/index.html
As far as an "Algorithm", I don't think it's really that complex other than simply mapping a Resource ID to a resource as defined above. There are some complexities in the sense of Merging Resources in a project. For example a library project -> your application project:
The build tools merge resources from a library module with those of a dependent app module. If a given resource ID is defined in both modules, the resource from the app is used.|
If conflicts occur between multiple AAR libraries, then the resource from the library listed first in the dependencies list (toward the top of the dependencies block) is used.
To avoid resource conflicts for common resource IDs, consider using a prefix or other consistent naming scheme that is unique to the module (or is unique across all project modules).
https://developer.android.com/studio/projects/android-library.html#Considerations
Given the majority of people's issues with Resource.designer.cs, they typically come from a point of view of understanding where actual third-party Resources come from and how they are supported. Here are some tips that I personally use:
Ensure your Application project is compiled against the latest API version. Typically this will be the <TargetFrameworkVersion> MSBuild property. One of my colleagues has an amazing blog post that stands the test of time about this factor:
http://redth.codes/such-android-api-levels-much-confuse-wow/
Find where the Resource is coming from. Does it come from an official NuGet package? When was the Resource introduced into the Android framework? (Useful for mostly Material Design items).
For example, if I had an error message regarding colorPrimary, I might check what API it was introduced in:
Added in API level 21
https://developer.android.com/reference/android/R.attr.html#colorPrimary
Thus we now know we require API 21+ at minimum to use this item.
Take a deep dive into the dependencies you are loading into your project. You can use a decompiler like dotPeek to look through an assembly and see what Resources it's trying to give your project. Additionally you can look at the cache of respective .aar and view it's res/ folder. This is mostly useful for larger bindings like the Android Support / Google Play Services ones. For smaller projects, look for the /res string inside the decompiled .dll
For example let's take a look at com.android.support:appcompat-v7:24.2.1:
First we need to find the cache on our machine:
AppData\Local\Xamarin\Xamarin.Android.Support.v7.AppCompat\24.2.1\embedded\res (If you get stuck here on OSX, I wrote a guide awhile back about finding these paths here - https://developer.xamarin.com/guides/android/troubleshooting/resolving-library-installation-errors/)
So we can now look through all of the respective Resources this library is trying to give to us.
Finally the last item is that people tend to delete the Resource.designer.cs file from their project. After the aapt process is complete, it will generate a new one or it will fail on aapt. It is up to you to figure out whether that step passed or not (i.e. Check the main project Resources folder for the newly generated Resource.designer.cs file so you can re-include it into your project).

Dynamically Determine Android Resources

I have a number of different string resource files that are built with my Android application using our build system. These string files can be added incrementally at any time and our build system will pick them up from their separate directory. I want to enumerate all of the string files or be able to obtain a single string in them without having to know the name or id of the string resource in them. I also don't want the person adding these to have to edit a main string file in my package that includes an array listing the different files. Is there any way to accomplish this?
Example:
SoccerStrings.xml
id="SoccerDetails" value="soccer"
CricketStrings.xml
id="CricketDetails" value="cricket"
Without knowing these files exist how can I provide a list view with two items: Cricket and Soccer in addition to automatically supporting any additional files that might appear.
I was thinking the best possible approach would be to have the build system pull the individual files under assets folder and then use the getAssets().list("") functionality along with the XMLResourceParser class to access the string values. Would this work and allow me to have id conflicts (ex: id="name")? Is there an easier way?
I would look at aapt. I know you can get the resources out of the .apk with the following command --
aapt d --values resources app.apk
It might be possible to use aapt to get the resources earlier in the build process. It has the following option which looks prosmising, but aapt documentation is a bit thin.
--output-text-symbols
Generates a text file containing the resource symbols of the R class in the
specified folder.
As another alternative, you could modify your build process and parse the string class directly out of the gen/<package>/R.java file after it has been generated. You could store that in a loadable file, or generate your own source file to add to the build.
I am not going to tell you how to do it. I am answering the question to advise against it.
What you are planning to do does not go well with the resource files. These files are basically code. What you want to do is about data. You should have your data in assets directory. Then these files won't be precompiled in your build like the resource file. You can process these files any way you want. There will be then quite a bit coding involved to convert all that into business logic, but that would be price to pay to write good, maintainable code.
Playing with resource files the way you are suggesting is akin to Java reflection. You want to use it only because you have functionality that is about such feature, not because it's the easiest way out.
Having said that, you might be exactly in a situation where you have to handle the resource files the way you stated. In that case, please accept my apologies.

NetBeans and Android image

New to Android development and have decided to use NetBeans 6.9.1 as my IDE. So far the process has been somewhat painful, but I'm getting things rolling. However, I am creating an ImageView subclass for my first custom View and I can't figure out how to add my Box.png file to the project. Drag and Drop doesn't work, there are no right-click options to add a file to the Resources folder, no dropdown menus to add images, no way to add the image to a package. Could use some insight, thanks!
Just go to the project folder and copy the images you want into the res/drawable folder. The IDE helps you a lot with code completion, error checking, etc... but that simple task can be done by hand.
Then, you can reference your resources by using something like: R.drawable.image Notice that I'm not using the image extension. If you wonder what R is, let me give you a brief explanation:
Each resource that is saved in the resources directory is referenced in the R class. That's a file that is autogenerated by Android and it's used to reference those resources from your code. In this case, it will be in R.drawable.* since it's a drawable resource. There are other kind of resources, like layouts: R.layout.something or strings R.string.whatever. That's essential for the android development, so you better read some tutorials (or buy books) in order for you to get started.
So, in your case will be something like setImageDrawable(R.layout.wood); However, I highly recommend to read first a couple of tutorials. Google about it, you will find tons of them.

Building an android library and passing the client's R.java when making the library call, how?

I would like to build a library and be able to distribute it as a jar without having to give the source. In the library, layouts are used for specifying the UI, however android doesn't seem to facilitate easily bundling a jar and distributing it, as it doesn't properly scope the resources (anything in '/res/*') in this jar file, the references made with R.xxxx within the jar don't work.
I can give the xml layouts and other resources to the client and ask them to put them into their resources directory, thus their R.java would have these references, now, how can the client pass this R.java to the library when invoking a method in the library?
Guess, answer to part of the question would be through answer to 'How to pass class in java?"
Yes, I am new to android and java too.
Thanks,
Krishna
If you have just simple layouts you could also create them in Java and not define them in XML.
It's not so nice but you don't have to distribute some other files.

Categories

Resources