Save widget state

document http://developer.android.com/guide/topics/data/data-storage.html

shows that there are several ways to save data, I need to do this in widgets, and every time I try to save, I get errors ...

eg

      SharedPreferences settings = getSharedPreferences("NAME", 0);
      SharedPreferences.Editor editor = settings.edit();
      editor.putBoolean("silentMode", false);

      // Commit the edits!
      editor.commit();

Error

Description Resource    Path    Location    Type
The method getSharedPreferences(String, int) is undefined for the type AWidget

another attempt:

     String FILENAME = "hello_file";
     String string = "hello world!";

     FileOutputStream fos = openFileOutput("Test.txt", Context.MODE_PRIVATE);
     fos.write(string.getBytes());
     fos.close();

with an error

Description Resource    Path    Location    Type
The method openFileOutput(String, int) is undefined for the type AWidget

What a deal? I do not see a mention that this does not work in widgets, so why these examples do not work for me?

What is the preferred way to save this data?

+3
source share
2 answers

, , , , . ...

 SharedPreferences settings = context.getSharedPreferences("NAME", 0);
      SharedPreferences.Editor editor = settings.edit();
      editor.putBoolean("silentMode", false);

      // Commit the edits!
      editor.commit();

, , , ... ...

int [] allids = AppWidgetManager       .getInstance()       .getAppWidgetIds( ComponentName (, AwarenessWidget.class));

onupdate

, - ...

, ! !

+2

, , , . SharedPreferences . , AWidget, .

:

onRestoreInstanceState (Parcelable state)

onSaveInstanceState()

, Android onSaveInstanceState(), Parcelable, onRestoreInstanceState(), .

+1

Source: https://habr.com/ru/post/1771235/


All Articles