首页 > 解决方案 > 从另一个类访问共享内存

问题描述

我正在向 Firebase 侦听器类中的共享内存写入一些数据。我可以看到数据已写入,并且我能够在同一类中读取相同的数据。但是我想从我的 Firebasemessaging 服务类中读取写入共享内存的数据。

当我尝试从消息服务类中读取共享内存数据时,它没有任何以 OnChildAdded 方法写入的数据。任何帮助表示赞赏。

public class MyFirebaseMessagingService extends FirebaseMessagingService {
public void onMessageReceived(RemoteMessage remoteMessage) {

SharedPreferences settings1 = this.getSharedPreferences("UserInfo",Context.MODE_PRIVATE);
    List<String> sampleReturnList = SharePrefUtil.pullStringList(settings1, sampleName);

    for(String listItem : sampleReturnList){
        Log.d("Item Messaging", listItem);
    }
}
}
public class FirebaseEventListener implements ChildEventListener {

private DataListAdapter userList;
private Context mContext;
public static SharedPreferences settings ;
public static String sampleName = "sample";
private String NotificationMessage;

public FirebaseEventListener(DataListAdapter userList, Context context) {
    mContext = context;
    this.userList = userList;
}

public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) 
{
SharedPreferences settings = 
mContext.getSharedPreferences("UserInfo",Context.MODE_PRIVATE);

        List<String> sampleList = new ArrayList();
     Log.d("Item Status", (String) dataSnapshot.child("7").getValue());
        if (( dataSnapshot.child("7").getValue()).equals("In Progress") )
     {

         String NotificationMessage= (String) dataSnapshot.child("0").getValue()+"-->"+(String) dataSnapshot.child("1").getValue();
            sampleList.add(NotificationMessage);

        }
SharePrefUtil.pushStringList(settings, sampleList, sampleName);

}
}

public class SharePrefUtil {


    public static void pushStringList(SharedPreferences sharedPref, List<String> list, String uniqueListName) {

        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt(uniqueListName + "_size", list.size());

        for (int i = 0; i < list.size(); i++) {
            editor.remove(uniqueListName + i);
            editor.putString(uniqueListName + i, list.get(i));
        }
        editor.apply();
    }

    public static List<String> pullStringList(SharedPreferences sharedPref,
                                              String uniqueListName) {

        List<String> result = new ArrayList<>();
        int size = sharedPref.getInt(uniqueListName + "_size", 0);

        for (int i = 0; i < size; i++) {
            result.add(sharedPref.getString(uniqueListName + i, null));
        }
        return result;
    }

}

标签: androidsharedpreferences

解决方案


推荐阅读