Search code examples
androidclassandroid-activitygetstring

getstring() from a call without extend activity


I have a problem with a simple class that contains information that I will like to call from another class. For example here is the class Util which contains the info:

public class Util{

public ArrayList<RecetaBean> getRellenas() {
    ArrayList<RecetaBean> MiLista = new ArrayList<RecetaBean>();

    RecetaBean receta1 = new RecetaBean();
    String ingrediente1[] = {         getString(R.string.app_name),getString(R.string.app_name),
    };
    receta1.setIngredientesLista(ingrediente1);

    MiLista.add(receta1);
    MiLista.add(receta1);
    MiLista.add(receta1);


    return MiLista;
}   
  }

Then in another class I get the Items calling like this:

    Util u = new Util();
    ArrayList<RecetaBean> Recetas = u.getRellenas();

So, I have a execution problem in the class Util with the GETSTRING, because I would like to get a different string (because of different languages). The way to quit the error is to extend the class Util from Activity, but Util is not an Activity! And if I extend from Activity, the app crash.


Solution

  • all you need to do is Define a Context in the Method .

    and call it like this;

    Util u = new Util();
    ArrayList<RecetaBean> Recetas = u.getRellenas(this);
    

    and you the context in you Methods like this:

    public ArrayList<RecetaBean> getRellenas(Context con) {
        ArrayList<RecetaBean> MiLista = new ArrayList<RecetaBean>();
    
        RecetaBean receta1 = new RecetaBean();
        String ingrediente1[] = {         con.getString(R.string.app_name), con.getString(R.string.app_name),
        };
        receta1.setIngredientesLista(ingrediente1);
    
        MiLista.add(receta1);
        MiLista.add(receta1);
        MiLista.add(receta1);
    
    
        return MiLista;
    }