3

Please, help me. I dont 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");
}
}

In the line "static SharedPreferences..." I get an error:

The method getSharedPreferences(String, int) is undefined for the type WeatherWidget

Why its undefined method if its class method?

Ok-Alex
  • 558
  • 2
  • 13
  • 29

4 Answers4

4

The getSharedPreferences method is not available for an AppWidgetProvider because it's not a Context. This link explains a bit more: Get preferences in AppWidget Provider

Community
  • 1
  • 1
Aldryd
  • 1,456
  • 1
  • 11
  • 7
4

You need a Context object to get shared preference reference:

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

Send the context as a parameter from the activity class to the non-activity class

In your Activity class:

function_name( getApplicationContext() ); // calling
(or simply)
function_name( this ); // calling

In your Non Activity class: (where no context exists)

public void fun_name(Context ctx)
{
    settings = ctx.getSharedPreferences("pref", 0);
}
0

I used this code to get shared preferences object in AppWidgetProvider:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        if (prefs == null)
            throw new NullPointerException("prefs");
prefs.getInt(....);
Tanya
  • 31
  • 1
  • 3