Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/202.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
共享引用Android问题_Android_Sharedpreferences - Fatal编程技术网

共享引用Android问题

共享引用Android问题,android,sharedpreferences,Android,Sharedpreferences,我正在尝试在我的应用程序中使用SharedReference,我需要一点hep,因为我刚刚开始使用它。基本上,我想做的事情是:我在我的主要活动中创建SharedReference对象,然后在第二个活动中,我有一个列表视图,并单击我使用Puint的项目;在新活动中,我有一个按钮,可以在adroid系统中添加SharedReference。最后,根据发送到第二个活动的id,我想在活动3中显示不同的文本 下面是一个小代码: 主要活动: SharedPreferences faves = Prefere

我正在尝试在我的应用程序中使用SharedReference,我需要一点hep,因为我刚刚开始使用它。基本上,我想做的事情是:我在我的主要活动中创建SharedReference对象,然后在第二个活动中,我有一个列表视图,并单击我使用Puint的项目;在新活动中,我有一个按钮,可以在adroid系统中添加SharedReference。最后,根据发送到第二个活动的id,我想在活动3中显示不同的文本

下面是一个小代码:

主要活动:

SharedPreferences faves = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = faves.edit();
        editor.putInt("favorites",0);
        editor.commit();
第二项活动:

SharedPreferences favs= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        final SharedPreferences.Editor editor = favs.edit();
我想显示文本的第三个活动取决于单击的项目:

favs.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                editor.putInt("favorites", getIntent().getIntExtra("id", 0));
            }
        });

有什么建议吗?

您实际上不必创建自己的SharedReference对象api Activity.GetSharedReferenceName,模式将执行此操作

基本上,它所做的是在你的应用程序自己的文件夹下创建一个xml文件,并且每一次放置。。。将在xml中添加一个项目,以便您以后可以更新和阅读,您只需要提供正确的名称


拥有一个全局编辑器不是一个好主意,有时它可能会丢失您的数据,所以每次您想读/写SharedReference时都需要一个编辑器。

好的,首先,很难理解这个问题。在示例代码中,您试图在主活动和第三个活动中存储值,但似乎从未读取值。最后,你会问一些如何解决这个问题的建议吗?这代表什么?您是否得到了一个错误或一个您不期望的结果?下面是我使用的一些示例代码。我有一个静态常量类,其中的一些值我在我的应用程序的其他部分中重用,但你明白了

ApplicationContext context = ApplicationContext.getInstance(); //I use a custom app context but any context will do.
SharedPreferences prefs = context.getSharedPreferences(
Constants.PREFS_FILE_NAME, Activity.MODE_PRIVATE);
prefs.getString("favorites", null);//or any other getter you want to use

你为什么把编辑标记为final?