android - 尝试将数据加载到共享首选项或从共享首选项加载数据时,应用程序崩溃

标签 android notifications crash

在我的应用程序中,我正在获取通知发布事件并过滤通知,然后将其保存在对象模型的共享首选项中并为其使用 HashMap :

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

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

我无法理解的是每当发布新通知时我的应用程序中出现 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.

最佳答案

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

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

关于android - 尝试将数据加载到共享首选项或从共享首选项加载数据时,应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53368482/

相关文章:

android - Realm 在移动设备中存储数据在哪里?

java - 文件实用程序 : readLines and writeLines methods not found

android - Android Studio 2.3不显示布局设计

android - 在 Activity 可见时隐藏前台服务的通知

android - AlarmManager 每 24 小时发出一次通知

swift - 从 CloudKit 下载的 URL 在按钮按下期间使应用程序崩溃

Android如何将listview放入view pager fragments

android - 通知 Android 3.0

android - 如果没有互联网,android应用程序将崩溃

java - 点击主页按钮然后单击应用程序图标返回到同一 Activity 后应用程序崩溃