I’m new to creating apps on Android with Eclipse and having a little trouble doing certain things.
I’m currently trying to not have to repeat tasks over and over again, so instead do functions that can be called from any activity.
Making a new java file with a public class appears to work ok, but then certain things don’t work.
package com.android.packagename;
import android.content.SharedPreferences;
public class Functions
{
public static final String PREFS_NAME = "PrefsFile";
SharedPreferences preferences;
public void loadPreferences()
{
SharedPreferences preferences=getSharedPreferences(PREFS_NAME,0);
String username = preferences.getString("username", "");
}
}
where I get the error of "The method getSharedPreferences(String, int) is undefined for the type Functions" and calling it by Functions.loadPreferences();
This code is absolutely fine when in the original Activity. I’ve tried adding this. etc onto the beginning but with no such luck. What am I missing?
Thanks
Instead of
use
If the method you are trying to use is contained in some other class type then pass in the instantiated class object to make it useable from multiple activities etc.
If you call loadPreferences(this) from an activity that would then work, same kind of pattern for other things will work as well.
You are right though, Android takes a bit of thought to make things reusable