2010-12-13 4 views
0

가 나는 appwidget를 가지고 있고, 나는이 메서드를 호출의 OnUpdate :안드로이드 appwidget/된 SharedPreferences 충돌

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 "";  } 
     } 

probleme입니다 : 내가 때때로 nullexception을 얻고, 충돌. 여기 문제가 뭐니?

답변

0

myContextContext으로 설정 했습니까?

다음은 테스트되지 않았습니다 :

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

하는 그래, 내가 너무 mycontext 있습니다. 이상한 일은 때로는 나타나지 않는 것입니다. – lacas

+0

그리고'saved_pref_file'이 설정되고 존재합니까? 어쩌면'mycontext.getSharedPreferences'는 null을 반환하고 NPE는'.getString'에서 발생합니다. – ccheneson

0

probleme 여기에 무엇입니까?

문제는 당신이 '원인'이 아니라 '결과'에 집중하고 있다는 것입니다.

작은 코드 샘플 만 제공하고 try/catch 블록을 주석 처리했기 때문에 '크래시'가 표시되는 이유와 마찬가지로 중요한 문제를 진단하기가 어렵습니다.

작은 코드 예제에서 가끔씩 NullPointerException이 표시되는 경우 mycontext.getSharedPreferences()가 'null'을 반환하기 때문에 이것이 가능할 수 있습니다. 이 경우 환경 설정을 저장해야하는 것은 작동하지 않습니다.

환경 설정을 저장하는 코드를 살펴보십시오. 그 대답이 어디에 있는지 의심 스럽습니다.

편집 : OK, 답안에서 제공 한 코드를 확인하십시오 (질문에 편집되어 있어야합니다).

saveStringValue 단 하나의 호출이있다() 여기 ...

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); 
     } 

     ... 

    } 
} 

... 단 하나의 loadStringValue()의 호출에 여기가있다 ...

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); 
    ... 
} 

첫 번째는 저장 "frissitve"이고 두 번째로드는 "listazas"이므로 문제가 무엇인지 아직 명확하지 않습니다. 내가하려고하는 점은 loadStringValue()에서 settings.getString()을 사용할 때 '때때로'NullPointerException이 발생하면 saveStringValue()가 이전에 해당 문자열을 저장하기 위해 호출되지 않았다는 유일한 이유가 될 수 있다는 것입니다. 그 일이 때때로 일어날 수있는 이유를 알아야합니다.

0

내 코드는 다음과 같습니다

... 

    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

내 대답을 끝까지 편집하십시오. – Squonk