I initialize one variable in an onUpdate() method and after that I call onReceive() function which runs fine but cannot access varible set in onUpdate() method. Why is that? Those varible is string variableand are declared public. Am I missing something?

public class WidgetTest extends AppWidgetProvider {
public static String ACTION_WIDGET_RECEIVER = "ActionReceiverWidget";
public String state;
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) 
{
    Log.e("UPDATE", "Start");   
    RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
     state="State_update"

 System.out.println(state);// My variable is initilised
    Intent active = new Intent(context, WidgetTest.class);
    active.setAction(ACTION_WIDGET_RECEIVER);       
    PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0);
    remoteViews.setOnClickPendingIntent(R.id.buttonclick, actionPendingIntent);

    super.onUpdate(context, appWidgetManager, appWidgetIds);
    appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
    Log.e("UPDATE", "End");
}

@Override
public void onReceive(Context context, Intent intent) 
{
   super.onReceive(context, intent);
    Log.e("RECEIVE", "Start 2");
    if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) 
    {

            Log.e("Test", "My State is  "state);//it gives me null point exception;

    }
   Log.e("RECEIVE", "End");


}

state varible in onReceive gives null point exception

有帮助吗?

解决方案

for a AppWidgetReceiver , first onReceive() will be called and then based on the Action received, it will call onUpdate(...) method. so here you are initializing state in onUpdate() which will be called after onReceive(), thus state is null in onReceive().

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top