2010-12-13 6 views
0

J'ai un appwidget et onUpdate j'appelle cette méthode:android appwidget/sharedpreferences accident

String asd=loadStringValue("asd"); 

public static String loadStringValue(String sName) { 
      //try { 
       SharedPreferences settings = mycontext.getSharedPreferences(saved_pref_file, 0); 
       return settings.getString(sName,""); 
      //} catch (Exception ex) { return "";  } 
     } 

le Probleme est: je reçois un nullexception parfois, et un accident. Quel est le problème ici?

Répondre

0

Avez-vous réglé myContext sur Context?

Ce qui suit n'a pas été testé:

Context mycontext; 

public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { 
     mycontext = context; 
     String asd=loadStringValue("asd"); 

} 

public static String loadStringValue(String sName) { 
    //try { 
      SharedPreferences settings = mycontext.getSharedPreferences(saved_pref_file, 0); 
      return settings.getString(sName,""); 
    //} catch (Exception ex) { return "";  } 
} 
+0

ouais, j'ai un mycontext aussi. la chose étrange est que nullexception apparaissant parfois. – lacas

+0

Et le fichier 'saved_pref_file' est-il défini et existe-t-il? Peut-être 'mycontext.getSharedPreferences' renvoie null et que le NPE se produit sur' .getString' – ccheneson

0

Quel est le Probleme ici?

Le problème est que vous vous concentrez sur le 'résultat' et non sur la 'cause'.

Il est difficile de diagnostiquer un problème lorsque vous avez seulement donné un petit échantillon de code et, tout aussi important, la raison pour laquelle vous voyez un 'crash' est parce que vous avez commenté le bloc try/catch. Dans la mesure où je peux interpréter à partir de ce petit exemple de code, si vous voyez parfois une exception NullPointerException, cela ne peut être que parce que mycontext.getSharedPreferences() retourne un 'null'. Dans ce cas, tout ce qui est supposé sauvegarder les préférences ne fonctionne pas. Jetez un oeil à votre code qui enregistre les préférences - Je pense que c'est là que réside la réponse.

EDIT: OK, en regardant le code que vous avez fourni dans une réponse (il aurait vraiment dû être édité dans votre question).

Il n'y a qu'un seul appel à saveStringValue() ici ...

private static void loadmm(RemoteViews updateViews, Context context, int appWidgetId) { 
    String now_date=getFullHungaryDate(); 
    String mm=""; 
    boolean error=false; 

    if (isInternetOn()) {    
    // try { 
     mm=getALL(); 

     if (!mm.equals("")) { 
      String frissitve=now_date+" "+getTime(); 

      updateViews.setTextViewText(R.id.mm, Html.fromHtml(mm)); 
      updateViews.setTextViewText(R.id.ma, "Fr. "+frissitve); 

      saveStringValue("frissitve", frissitve, context); 
     } 

     ... 

    } 
} 

... et il n'y a qu'un seul appel à loadStringValue() ici ...

private static String getALL() { 

    String sOut   = ""; 
    String sOutAll  = "<br>"; 
    Boolean err   = false; 

    HttpStringCutter Cutter = new HttpStringCutter(); 

    Calendar calendar = Calendar.getInstance(); 

    int hnow=calendar.get(Calendar.HOUR_OF_DAY); 
    if (hnow>1) hnow--; 

    String hour=Integer.toString(hnow); 
    String min=Integer.toString(calendar.get(Calendar.MINUTE)); 

    String LISTAZAS  =loadStringValue("listazas", mycontext); 
    ... 
} 

Le premier sauve "frissitve" et le second charge "listazas" donc on ne sait toujours pas quel est le problème. Le point que j'essaie de faire est que si 'parfois' vous obtenez une exception NullPointerException lors de l'utilisation de settings.getString() dans loadStringValue() alors la seule raison peut être que saveStringValue() n'a pas été appelé précédemment pour sauvegarder cette chaîne. Vous devez regarder pourquoi cela peut arriver parfois.

0

mon code est:

... 

    public static Context mycontext; 



    @Override 
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { 
     mycontext=context; 

     for (int appWidgetId : appWidgetIds) { 
      PendingIntent newPending = makeControlPendingIntent(context, "update", appWidgetId); 
      AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
      alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()+UPDATE_INTERVAL, UPDATE_INTERVAL, newPending); 

      try { 
       newPending.send(); 
      } catch (CanceledException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 



    @Override 
    public void onDisabled(Context context) { 
     context.stopService(new Intent(context, UpdateService.class)); 
    } 

    @Override 
    public void onDeleted(Context context, int[] appWidgetIds) { 
     context.stopService(new Intent(context, UpdateService.class)); 
    } 


    public static PendingIntent makeControlPendingIntent(Context context, String command, int appWidgetId) { 
     Intent active = new Intent(context, UpdateService.class); 
     active.setAction(command); 
     active.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); 

     Uri data = Uri.withAppendedPath(Uri.parse("mm://widget/id/#"+command+appWidgetId), String.valueOf(appWidgetId)); 
     active.setData(data); 
     return(PendingIntent.getService(context, 0, active, PendingIntent.FLAG_UPDATE_CURRENT)); 
    } 


    public static class UpdateService extends Service { 

      private String command; 
      public static Intent intentx; 


      @Override 
      public void onStart(Intent intent, int startId) { 

      UpdateService.intentx=intent; 

       command = intent.getAction(); 
       int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID); 

       try { 
        if (command!=null) { 
         if (command.equals("refresh") || command.equals("update")){ 
          buildUpdate(this, appWidgetId); 
         } else if (command.equals("showall")) { 
          Intent i =new Intent(mm.mycontext, mmMain.class); 
          i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); 

          startActivity(i); 
         } 
        } 
       } catch (Exception ex){ 
        buildUpdate(this, appWidgetId); 
       } 

      } 

      public static void buildUpdate(Context context, int appWidgetId) { 

       RemoteViews updateViews = null; 
       updateViews = new RemoteViews(context.getPackageName(), R.layout.main); 

       updateViews.setTextViewText(R.id.loader, "Frissít ("+getTime()+")"); 
       updatewidget(updateViews, context, appWidgetId); 

       loadmm(updateViews, context, appWidgetId); 
      } 

      private static void updatewidget(RemoteViews updateViews, Context context, int appWidgetId) { 
       AppWidgetManager manager = AppWidgetManager.getInstance(context); 
       manager.updateAppWidget(appWidgetId, updateViews); 
      } 


      public final static boolean isInternetOn() { 

       try { 
        ConnectivityManager connec = (ConnectivityManager) mycontext.getSystemService(Context.CONNECTIVITY_SERVICE); 

        if ( connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED || 
          connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING || 
          connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING || 
          connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED) { 

         return true; 
        } else if (connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED || connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED ) { 
         return false; 
        } 
        return false; 
       } catch (Exception ex) { 
        return true; 
       } 
      } 


      ... 


      private static String getALL() { 

       String sOut   = ""; 
       String sOutAll  = "<br>"; 
       Boolean err   = false; 

       HttpStringCutter Cutter = new HttpStringCutter(); 

       Calendar calendar = Calendar.getInstance(); 

       int hnow=calendar.get(Calendar.HOUR_OF_DAY); 
       if (hnow>1) hnow--; 

       String hour=Integer.toString(hnow); 
       String min=Integer.toString(calendar.get(Calendar.MINUTE)); 


       String LISTAZAS  =loadStringValue("listazas", mycontext); 
       int peroldal  =0; 
       if (LISTAZAS.equals("")) { 
        peroldal=50; 
       } else { 
        peroldal=Integer.parseInt(Beallitasok.listazasok[Integer.parseInt(LISTAZAS)]); 
       } 

... 


       return sOut; 

      } 


      private static void loadmm(RemoteViews updateViews, Context context, int appWidgetId) { 

      String now_date   =getFullHungaryDate(); 
      String mm   =""; 
      boolean error    =false; 

       if (isInternetOn()) {    
        // try { 
         mm=getALL(); 

         if (!mm.equals("")) { 
          String frissitve=now_date+" "+getTime(); 

          updateViews.setTextViewText(R.id.mm, Html.fromHtml(mm)); 
          updateViews.setTextViewText(R.id.ma, "Fr. "+frissitve); 

          saveStringValue("frissitve", frissitve, context); 

         } 

        /*} catch (Exception ex) { 
         Log.e(TAG+"_ERR","No Internet or Other Error occured."); 

         error=true; 
         //mm="Letöltés hiba!"; 
        }*/ 
       } else { 
        //nincs net 
        Log.e(TAG+"_ERR","No Internet found."); 

        mm="NET elérés hiba!"; 

        error=true; 

       } 

      if (error) { 
       //hint(TAG+" Hiba!"); 
      } 


      updateViews.setTextViewText(R.id.loader, ""); 

       updateViews.setOnClickPendingIntent(R.id.mm, makeControlPendingIntent(context, "showall", appWidgetId)); 
       updateViews.setOnClickPendingIntent(R.id.refresh, makeControlPendingIntent(context, "refresh", appWidgetId)); 

       updatewidget(updateViews, context, appWidgetId); 
      } 


      @Override 
      public IBinder onBind(Intent intent) { 
       return null; 
      } 
     } 



     //load, save 
     private final static String saved_pref_file="mmm_saved_prefs"; 

     public static String loadStringValue(String sName, Context ctx) { 
      try { 
       SharedPreferences settings = ctx.getSharedPreferences(saved_pref_file, 0); 
       return settings.getString(sName,""); 
      } catch (Exception ex) { return "";  } 
     } 
     public static void saveStringValue(String sName, String sValue, Context ctx) { 
      SharedPreferences settings = ctx.getSharedPreferences(saved_pref_file, 0); 
      SharedPreferences.Editor editor = settings.edit(); 
      editor.putString(sName, sValue); 

      editor.commit(); 
     } 

    ... 
+0

voir ma modification à la fin de ma réponse – Squonk