代码之家  ›  专栏  ›  技术社区  ›  beginner

尝试在共享首选项之间加载数据时应用程序崩溃

  •  1
  • beginner  · 技术社区  · 5 年前

    在我的应用程序中,我将获取Notification Posted事件并过滤该通知,然后将其保存在对象模型的共享首选项中,并对其使用哈希映射:

      Map<String,  List<Model>> 
    

    我正在使用asynctask从共享首选项中获取应用程序中的列表:

        private class FetchData extends AsyncTask<Void,Void,Map<String,List<Model>>> {
    
        @Override
        protected Map<String, List<Model>> doInBackground(Void... voids) {
            SharedPreferences shared;
            Gson gson = new Gson();
            shared = getSharedPreferences("MyVariables", Context.MODE_PRIVATE);
            modelList = gson.fromJson(
                    shared.getString("My_map", null),
                    new TypeToken<HashMap<String, List<Model>>>() {
                    }.getType());
            return modelList;
        }
    
        @Override
        protected void onPostExecute(Map<String, List<Model>> stringListMap) {
            super.onPostExecute(stringListMap);
            if(modelList!=null) {
                keys = getKeys(modelList);
                adapter = new CustomListAdapter(getApplicationContext(), keys);
                list.setAdapter(adapter);
            }
        }
    }
    

    数据的保存在此函数中:

         private void saveMap(Map<String,List<Model>> inputMap){
        SharedPreferences shared;
        SharedPreferences.Editor editor;
    
        shared = getSharedPreferences("MyVariables", Context.MODE_PRIVATE);
        editor = shared.edit();
    
        Gson gson = new Gson();
        String json = gson.toJson(inputMap);
        editor.putString("My_map", json);
        editor.commit();
    }
    

    每当发布新的通知时,我都会从中提取数据,并将其保存在本地hashmap和共享首选项中。在应用程序打开时,我将数据从共享首选项加载到本地列表。

    我无法理解的是每当发布新通知时,应用程序中出现anr的原因。

    It has been 8006.8ms since event, 8006.4ms since wait started.  Reason: Waiting to send non-key event because the touched window has not finished processing certain input events that were delivered to it over 500.0ms ago.  Wait queue length: 2.  Wait queue head age: 9112.1ms.
    
     Reason: Waiting to send non-key event because the touched window has not finished processing certain input events that were delivered to it over 500.0ms ago.  Wait queue length: 2.  Wait queue head age: 9112.1ms.
    
    1 回复  |  直到 5 年前
        1
  •  2
  •   Alex Shevelev    5 年前

    很好的一天! 首先,应该将saveMap()函数的调用移到后台线程。例如在doinBackground()中。

    另外,我建议您考虑使用数据库来存储通知-太复杂,无法存储在共享首选项中。