【问题标题】:android appwidget/sharedpreferences crashandroid appwidget/sharedpreferences 崩溃
【发布时间】:2010-12-13 08:11:34
【问题描述】:

我有一个 appwidget,我在更新时调用了这个方法:

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

问题是:我有时会遇到空异常,然后崩溃。这里有什么问题?

【问题讨论】:

    标签: android sharedpreferences


    【解决方案1】:

    您是否将myContext 设置为Context

    以下内容未经测试:

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

    【讨论】:

    • 是的,我也有一个 mycontext。奇怪的是有时会出现空异常。
    • saved_pref_file 设置并存在吗?也许 mycontext.getSharedPreferences 返回 null 并且 NPE 发生在 .getString
    【解决方案2】:

    我的代码是:

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

    【讨论】:

      【解决方案3】:

      这里有什么问题?

      问题在于你关注的是“结果”而不是“原因”。

      如果您只给出了一小段代码示例,就很难诊断出问题,同样重要的是,您看到“崩溃”的原因是因为您已经注释掉了 try/catch 块。

      据我可以从那个小代码示例中解释,如果您有时会看到 NullPointerException,那只能是因为 mycontext.getSharedPreferences() 返回了“null”。在这种情况下,任何应该保存首选项的东西都不起作用。

      看看您保存偏好的代码 - 我怀疑这就是答案所在。

      编辑:好的,查看您在答案中提供的代码(它确实应该被编辑到您的问题中)。

      这里只有一次调用 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() 来保存该字符串。你需要看看为什么有时会发生这种情况。

      【讨论】:

        猜你喜欢
        • 2013-05-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-21
        • 1970-01-01
        • 1970-01-01
        • 2018-02-07
        • 2012-07-07
        相关资源
        最近更新 更多