Espresso: How to use R.string resources of androidTest folder - android

I want to put data in xml file of androidTest/res/values/string.xml folder. I have created the file say test.xml with below contents.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="test">hello</string>
</resources>
When i am trying to access the field test via R.string.test. It is not accessible and says "cannot resolve symbol test". Can someone please advice me here.

This is how you do it:
import com.my.example.test.R;
Resources resources = InstrumentationRegistry.getContext().getResources();
String terms = resources.getString(R.string.test);

androidx.test.platform.app.InstrumentationRegistry is deprecated use androidx.test.core.app.ApplicationProvider
val targetContext = ApplicationProvider.getApplicationContext<Context>()
val test: String = targetContext.resources.getString(R.string.test)

I have a longstanding Android library project in which I had renamed my sources' package at some point from a.b.c.d to a.b.c but I had forgot to change the package value in my library's AndroidManifest.xml file likewise. This led to some confusion when I added a res/values/strings.xml file to my library's androidTest folder but I was unable to see an a.b.c.test.R object in my test classes.
The solution for me was to rename the package value in my library's AndroidManifest.xml file to match my sources' package (i.e. a.b.c). I am now able to see an a.b.c.test.R object in my test classes and I am able to access the string resources defined in androidTest/res/values/strings.xml via the InstrumentationRegistry.getInstrumentation().context.getString(resId:) method.

Related

Android instrumented test - test resource not resolved

I want to have androidTest resources specific to each app flavor. I found an answer on this site that indicated you can just make a resource directory androidTestFlavorName and it will be managed like all the other resources. So I have a directory app/src/androidTestFlavorName/res/values and a file strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="test_sec_code">aStringValue</string>
</resources>
I have a test class app/src/androidTest/java/com/company/package/StartupTest.kt. In that class:
val code = context.getString(R.string.test_sec_code)
test_sec_code is red, so the IDE doesn't like it, and the compiler reports: Unresolved reference: test_sec_code
My selected build variant is flavorNameDebug. So am I setting up these resources wrong, or is my goal not possible?
Edit:
I tried putting the resource in app/src/androidTest/res/values/strings.xml and it can't be found there either. Surely there must be a way to define test resources right? Hello, is this thing on?

How do I access a text file for JUnit test in Android?

How can I access a text file in my directory 'src/test/resources'
I can't seem to get it to pickup during my JUnit test
mobile/build.gradle:
sourceSets {
test {
java {
srcDirs = [ 'src/test/java' ]
}
resources {
srcDirs = [ 'src/test/resources' ]
}
}
}
Test method:
#Test
public void test_file() {
URL resource = getClass().getResource("file_four_lines.txt");
File file = new File(resource.getFile()); // Get NullPointerException here
...
}
Prefix the file path with /.
Basically, you'd do something like this:
File helloBleprintJson = new File(
getClass().getResource("/helloBlueprint.json").getPath());
Above snippet is taken from here.
I think this link will help. In your case why not hard code strings for testing? Why not use String.xml instead of "file_four_lines.txt". Internationalization requires a directory structure for each resource file having different language, screen size, orientation, flavor, night/day vision version. For this reason resources are compiled and accessed from the R file. You are trying to bypass this convention by using .txt instead of .xml and accessing the resource directly, it just feels wrong. I don't think testing is you problem as much as not following convention.
Forgive me for posting twice, I do have an answer from the official documentation" Arbitrary files to save in their raw form. To open these resources with a raw InputStream, call Resources.openRawResource() with the resource ID, which is R.raw.filename.
However, if you need access to original file names and file hierarchy, you might consider saving some resources in the assets/ directory (instead of res/raw/). Files in assets/ are not given a resource ID, so you can read them only using AssetManager." Json and txt are non-standard(unsupported) so you have to provide your own implementation/parcer to read this type file. Thanks for this post. I knew something about resources but thanks to your prodding now I know even more. To recap The Android resource system keeps track of all non-code assets associated with an application. The Android SDK tools compile your application's resources into the application binary at build time. To use a resource, you must install it correctly in the source tree (inside your project's res/ directory) and build your application. As part of the build process, the SDK tools generate symbols for each resource, which you can use in your application code to access the resources and of course the symbols referred to are in the generated R file

R.java is not being created?

I dowloaded google-play-services from sdk manager and copy pasted all the code from admob samplebut it is not working. Everything seems perfect only errors produced are R can't be resolved to a variable.
Here is a sample error
Error: No resource found that matches the given name (at 'text' with value '#string/load_interstitial').
Here is strings.xml file
<resources>
<string name="app_name">Google Ads SDK Sample</string>
<string name="ad_unit_id">INSERT_YOUR_AD_UNIT_ID_HERE</string>
<string name="load_interstitial">Load Interstitial</string>
<string name="interstitial_not_ready">Interstitial Not Ready</string>
<string name="banner_in_xml">Banner in XML</string>
<string name="banner_in_code">Banner in Code</string>
<string name="interstitial">Interstitial</string>
</resources>
Try to delete the import line import com.your.package.name.app.R, then, any resource calls such as mView= (View) mView.findViewById(R.id.resource_name); will highlight the 'R' with an error, a 'Quick fix' will prompt you to import R, and there will be at least two options:
android.R
your.package.name.R
Select the R corresponding to your package name, and you should be good to go. Hope that helps.
Or.....second region,
Each time I had a problem with R not been generated, or even disappeared, this was due to some problem in the XML layout file that prevented the application from being built.
The error in res folder cause missing of R.java filevso please check your res folder for any error.
The error may be with image too any capital letter or blank space can cause missing of R.java file.
Also check all the XML file ,error with res files only

Android Library Project - Error when calling context.getResources().openRawResource()

I'm developing an android library project that should read from an xml file in its raw resources (let's call it xml_file_name.myextension).
What I do is basically creating a jar file of the library project including these folders:
src
gen
lib
res/raw
and referencing it as a library in a test app. This is the code that I use (inside the library project) in order to get the xml file:
int xml_res_id = -1;
for (Field f : R.raw.class.getFields()) {
System.out.println("Raw resource found: " + f.getName());
if (f.getName().equalsIgnoreCase("xml_file_name"))
xml_res_id = f.getInt(null);
}
if(xml_res_id != -1){
System.out.println("xml_file_id: " + xml_res_id);
InputStream is = context.getResources().openRawResource(xml_res_id);
// Decode xml file with SAXParser..
}
(I have the app context because the app explicitly passes it to the library project.)
What happens is that when I launch the test app (and call the method that reads the xml file) I get this error:
It seems that the xml file is actually in the right folder, because:
1) The for loop actually prints "Raw resource found: xml_file_name.myextension" and "xml_file_id: 2130968576"
2) If I put a file named "xml_file_name.myextension" in the res/raw folder of the app, it does not compile, and the error is: "Error generating final archive: Found duplicate file for APK: res/raw/xml_file_name.myextension". This basically gives me the proof that the
file is correctly "imported" from the library project.
Please Note:
I also tried in this other way
InputStream is = context.getResources().openRawResource(R.raw.xml_file_name);
getting the same error.
I honestly don't understand what could be the problem.. what am I doing wrong?
Edit:
for anyone interested in this issue:
I finally realized that this is not possible, basically because when I try to get a resource through context.anymethod I refer to the R file of the app, so I can't give the resource ID got from the R file of my library project.
It will compile, because the library project jar file contains the resource (R.raw.xml_file), but the call to context.something will always give null as a result because it refers to the app R file, that does not have that particular resource in it.
I finally had to put my xml file in the res/raw folder of the app, and access the xml_file raw resource in this way:
int xml_id = context.getResources().getIdentifier("xml_file_name", "raw", context.getPackageName());
// Getting input stream from xml file
InputStream is = context.getResources().openRawResource(xml_id);
I have actually done this with success - the library object should be within the app context. However, it only works with Activity and no other type that I have found. Using the same library with a FragmentActivity fails with NoClassDefFoundError.
EDIT****
It may work with a FragmentActivity within the same root namespace as the library. I was accessing from a different root namespace.
END EDIT****
I have a library project that references an xml file:
InputStream is = context.getResources().openRawResource(R.raw.application_table_defs);
when I call the library method that executes the previous line I have to pass in a context:
Context context = this.getContext();
The key is fully qualifying the getResource to context.getResources()... that was injected.

Change default package from com.example for Eclipse Android projects

I am using Eclipse 4.2 with Android SDK.
I am wondering if it is possible to change the default package ID com.example that shows in the "New Android Application" wizard as you type the application name?
I would like it to default to my own package ID so that I don't need to correct the Package Name field each time.
Is this possible to do? Please explain how.
No, you cannot change the default; it's hardcoded in the plugin sources.
(For the curious, it's in com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectPage#SAMPLE_PACKAGE_PREFIX in the ADT code base). We should consider persisting the most recently set package prefix and inserting the parent package next time. Feel free to file an issue for that at http://b.android.com category Component-Tools.
-- Tor
With Android Studio not running, edit the file: C:\Users\MyAccount\.AndroidStudio\config\options\options.xml (replace C: with the installation drive and MyAccount with your account name).
Within the xml file look for "property name="SAVED_COMPANY_DOMAIN" value=" and change the value to what you want.
Following user2232952's guidance, for new versions of Android Studio change the value of:
<property name = "SAVED_ANDROID_PACKAGE" value = "com.example" />
I'm not sure why so many people have right answers with wrong file location...
I've installed android studio 2020.3 with all default settings and the file others.xml is in folder
C:\Users\MYUSER\AppData\Roaming\Google\AndroidStudio2020.3\options
For anyone coming here in 2020, the file you are looking for is other.xml
It can be found in your AndroidStudio library under config/options/other.xml
(For mac this is probably ~/Library/Application Support/Google/AndroidStudio4.1/options)
Then you can follow the instructions by #Murillo Comino
<property name = "SAVED_ANDROID_PACKAGE" value = "com.example" />
EDIT:
As per #Douglas Kazumi 's comment, it is important that AS will be closed while editing this.
If you've already created your project, you could go to your AndroidManifest.xml file and update the attribute in the Manifest (root) tag
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="your.package.name"
android:versionCode="1"
android:versionName="1.0" >
Just make sure the rest of your code also reflects this change.
Click the package name and hit Alt+Shift+R and Rename, it will update everything!

Categories

Resources