SharedPreferences suffers. getSharedPreferences doesn't work
Please help me. I don't know what is wrong with this code:
import android.appwidget.AppWidgetProvider;
import android.content.SharedPreferences;
public class WeatherWidget extends AppWidgetProvider {
static SharedPreferences settings = getSharedPreferences("weather_prefs", 0);
public void onUpdate()
{
settings.getString("location", "N/A");
}
}
On the line "static SharedPreferences ..." I get an error:
GetSharedPreferences (String, int) method is undefined for type WeatherWidget
Why is his method undefined if his is a class method?
+3
source to share
4 answers
The method is getSharedPreferences
not available for AppWidgetProvider
because it is not a Context. This link explains a little more: Get Settings in AppWidget Provider
+4
source to share
Send context as parameter from activity class to inactive class
In Activity class:
function_name( getApplicationContext() ); // calling
(or simply)
function_name( this ); // calling
In class Non Activity: (where context doesn't exist)
public void fun_name(Context ctx)
{
settings = ctx.getSharedPreferences("pref", 0);
}
+2
source to share