0

I want to create an application which can fetch the string name from the resource file in android when we search using string.Is there any way? Suppose my strings.xml file has following

Hello world!

Now what i want to do is when i type Hello world in the search menu of my application it should return abc as the string name.

  • 1
    Did you mean [`Context.getString(int resId)`](http://developer.android.com/guide/topics/resources/string-resource.html)? What do you mean by *search using String*? Example? – Andrew T. Mar 13 '14 at 04:15
  • If my xml resource file has following entry hello world.Is it possible to get res id name i.e. "abc" using hello world – user3413619 Mar 13 '14 at 04:34

3 Answers3

1

1. When you say, "Suppose my strings.xml file has following", and there's a "Hello world!", it would mean your strings.xml would look like:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="hello_world">Hello world!</string>

</resources>  

This means there are strings defined under Resources of your app which can be used by importing yourpackage.R - that is how the compiler will identify values from R.

So what is the name of the string which has value "Hello world!" in your xml?

2. To get that value, you would use:

getResources.getString(R.string.stringNameHere);  

3. And as per your requirement, i suggest you get all strings from your strings.xml in an array and run your search through that.

To know more about all that, please go through:

-> http://developer.android.com/guide/topics/resources/string-resource.html

-> https://developer.android.com/samples/BasicNetworking/res/values/strings.html

-> Organizing Strings.xml

Community
  • 1
  • 1
Pararth
  • 8,114
  • 4
  • 34
  • 51
0

Use getResources().getString(R.string.yourstring) in your Activity. The string yourstring is defined in Strings.xml.

rgamber
  • 5,749
  • 10
  • 55
  • 99
0

You can loop through the defined strings by using reflection on R.string like this:

for (Field field : R.string.class.getDeclaredFields())
{
    try {
        Log.i("Strings", String.format("String %s = %s", field.getName(),
                                       getResources().getString(field.getInt(field))));
    } catch (NotFoundException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }           
}
scottt
  • 8,301
  • 1
  • 31
  • 41