HoLoGram
HoLoGram

Reputation: 169

How to call non static function from another activity?

I have a function in my code that I want to use in the other activity but I can't make the function static because every time I add static it gives me an error(the error refer to "this") :

'com.example.memorableplacecs.MainActivity.this' cannot be referenced from a static context

this is my code I want to use:

protected boolean saveArray() {
    SharedPreferences sp = this.getSharedPreferences(SHARED_PREFS_NAME, Activity.MODE_PRIVATE);
    SharedPreferences.Editor mEdit1 = sp.edit();
    Set<String> set = new HashSet<String>();
    set.addAll(mArrayList);
    mEdit1.putStringSet("list", set);
    return mEdit1.commit();
}

Thank you for your help

Upvotes: 0

Views: 137

Answers (3)

Perraco
Perraco

Reputation: 17360

A static method exists outside the life of a class instance, is part of the class definition itself, and not the instance. This means that when a method is declared as static, its execution is not related to an Activity or a class instance, therefore it can't access any local variables, neither instance references using the "this" keyword.

The solution is to pass a context into the method along with any required data:

public static boolean saveArray(final Context context, final List<Needed_Class> data) {
    final SharedPreferences sp = context.getSharedPreferences(SHARED_PREFS_NAME, Activity.MODE_PRIVATE);
    final SharedPreferences.Editor editor = sp.edit();
    final Set<String> set = new HashSet<String>();
    set.addAll(data);
    editor.putStringSet("list", set);
    return editor.commit();
}

Notice that as it is declared as static, you no longer need to have this method in your Activity class. It would be better to move it into a dedicated helper class.

Upvotes: 0

Twelve
Twelve

Reputation: 51

There is no point to call a method from another activity, because you're on one activity at a time.

You can create an Application, register it in the Manifest.

And add your static method in it.

Then in an activity, you can call it like this:

    MyApplication application = ((MyApplication)getApplicationContext());
    application.saveArray(params..)

Upvotes: 1

Crazy
Crazy

Reputation: 111

You can make it static like this:

private final static String SHARED_PREFS_NAME = "your_name";

public static boolean saveArray(Context context, List<Needed_Class> list) {
    SharedPreferences sp = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor mEdit1 = sp.edit();
    Set<String> set = new HashSet<String>();
    set.addAll(list);
    mEdit1.putStringSet("list", set);
    return mEdit1.commit();
}

and call from activity:

PrefsHelper.saveArray(this, list)

Upvotes: 1

Related Questions