AppWidgetProvider: problem with variables

I created a widget for the main screen and declared some variables in the AppWidgetProvider class. These variables are integer and boolean.

The problem I am encountering (mostly a Java programming problem) is that any value that I assign to my variables; when I remove the widget from the main screen, and then later, when I add the widget back to the main screen, the variables still retain the values ​​since the last widget on the main screen. I declare the variables as follows:

public class MyWidget extends AppWidgetProvider {
    static int iPicNum = 0;
    static Boolean bClosed = false;
    ...

How do I reset the values ​​of my variables every time the widget is removed from the screen and put back on the screen again. Or, if the user wants to have more than one instance of the widget on the screen, the variables should not share values ​​with each other. They must be independent of each other.

Thank. Faraz Azhar

+3
source share
3 answers

Why not override onDeleted()in MyWidgetand reset your value whenever it is called (do not forget to call super.onDeleted()though).

0
source

, , , . Java, static, , . , , PolarBear. , "". , , PolarBear.bearColor, . , . , .

0

, .

, appWidgetId. , - HashMap , :

private static class MyValues{
    private final int iPicNum = 0;
    private final boolean bClosed = false;

    public MyValues(int iPicNum, boolean bClosed) {
        this.iPicNum = iPicNum;
        this.bClosed = bClosed;
    }
    public int getiPicNum() {
        return iPicNum;
    }
    public boolean isbClosed() {
        return bClosed;
    }        
}

AppWidgetProvider:

private static HashMap<int,MyValues> mValues = new HashMap<int,MyValues>;

:

mValues.put(appWidetId, new MyValues(iPicNum,bClosed);

:

MyValues values = mValues.get(appWidgetId);
if (values != null){
   int iPicNum = values.getiPicNum();
   boolean bClosed = values.isbClosed();
}

And don't forget to clear the unused data in the onDeleted () method (it is called when a single action of the widget is removed from the screen):

public void onDeleted(Context context, int[] appWidgetIds) {
    for (int appWidgetId : appWidgetIds) {
        if (appWidgetId != -1) {
            mValues.remove(appWidgetId);
        }
    }
}

Hope this helps.

0
source

All Articles