0

How do I Load Your String Resources Programmatically from a Class file and not an Activity:

this is in my Strings.xml

    <!-- FactBook Resource -->
    <string-array name="facts">
        <item>facts 1</item>
        <item>facts 2</item>
...
    </string-array>

Here my Class File

public class FactBook {

    public String[] mFacts;

    mFacts = getResources().getStringArray(R.array.facts);

    public String getFact() {

        String fact = "";

        // Randomly select a fact
        Random randomGenerator = new Random();  
        int randomNumber = randomGenerator.nextInt(mFacts.length);

        fact = mFacts[randomNumber];

        return fact;
    }
}

I get a erro. - Invalid Method declaration, return type required.

2
  • 2
    Load Your String Resources Pro-grammatically from a Class file get call getResources() you should need valid current component Context. so use FactBook class constructor for getting context during object creation and then access String array as context.getResources().getStringArray(R.array.facts) Commented Jan 2, 2015 at 9:35
  • 1
    You can't access getResources() from outside. If you want then only using a Context. Commented Jan 2, 2015 at 9:36

1 Answer 1

2

You need to create Constructor and pass Context as first argument.

public class FactBook {

public String[] mFacts;

Context context;

public FactBook(Context con){
context=con;
mFacts =con.getResources().getStringArray(R.array.facts);
}

public String getFact() {

    String fact = "";

    // Randomly select a fact
    Random randomGenerator = new Random();  
    int randomNumber = randomGenerator.nextInt(mFacts.length);

    fact = mFacts[randomNumber];

    return fact;
 }
}

Now, you called this Facebook class like

FactBook fb=new Facebook(your_Activity.this);
String str=fb.getFact();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.