-1

I'm currently writing an App, it gets JSON from a website, and then lists the contents in a listview. Now since the API itself only returns names like this: "twisted_castle" instead of "Twisted Castle", I created a new class to substitute the generic names to the right names, which I previously added to the strings.xml.

Now I can get Strings via String test = getString(R.string.key) in the MainActivity, but since I created a new class for the Substitute to happen, I somehow can't use getString somehow.

I already discovered that I'll need to get/use the context of MainActivity somehow, but really any solution I found didn't work, and also I'm a bit irritated on how the whole context thing works.

Anyone can help me with this and maybe has a good explanation on how contexts work?

derRAV3N
  • 25
  • 3
  • 1
    Possible duplicate of [What is 'Context' on Android?](https://stackoverflow.com/questions/3572463/what-is-context-on-android) – zsmb13 May 28 '17 at 13:19
  • Why do you create a new class for this? You could achieve this by just creating a method and pass the context as argument. – Denny May 28 '17 at 13:19
  • @Denny Because I want to split my code, so that I don't end up with one huge pile of code later.. – derRAV3N May 28 '17 at 14:13
  • @Denny So should I keep the method in the MainActivity? How do I decide then which things I should create an extra class for? – derRAV3N May 28 '17 at 14:28
  • If it only requires an context, you could make a static method (in a different class) and pass the context from the mainactivity to the method – Denny May 28 '17 at 18:24

1 Answers1

1

You can use Context as:

mcontext.getString(R.string.something);

all you have to do is init context in the class some where like:

static Context mcontext;
public void setmContext(Context context){
  this.mcontext=context;
}

and call setmContext(this) from your activity or where ever you have context attribute

dali
  • 46
  • 1
  • 7
  • Thanks, this worked out, so I have to create a Context object in the class which needs it and then set it with the method which is also in that class, but I need to call it from the class which "has" the context? I'm trying to understand this, but I'm not that far with java yet. – derRAV3N May 28 '17 at 14:24
  • Maybe this [post](https://stackoverflow.com/questions/3572463/what-is-context-on-android) will give you better understand about Context – dali May 29 '17 at 08:14