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 get the share link you need a Context object:



// add to WeatherWidget:
@Override
public void onEnabled(Context ctx)
{
    settings = ctx.getSharedPreferences("weather_prefs", 0);
}

      

+4


source


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


I used this code to get the general preference object in the AppWidgetProvider:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        if (prefs == null)
            throw new NullPointerException("prefs");
prefs.getInt(....);

      

0


source







All Articles