简体   繁体   English

从带有微调器的单独类中调用SharedPreferences?

[英]Calling SharedPreferences from a separate class with a spinner?

I'm not sure how to word this but I'm having issues accessing Shared Preferences under MODE_PRIVATE. 我不确定该如何措辞,但在访问MODE_PRIVATE下的“共享首选项”时遇到问题。

I'm implementing a Spinner like so: 我正在像这样实现Spinner:

setSessions = (Spinner)findViewById(R.id.numSessions);
setSessions.setOnItemSelectedListener(new CustomOnItemSelectedListener());

The Custom listener is like so: 自定义侦听器如下所示:

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class CustomOnItemSelectedListener implements OnItemSelectedListener {

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {

        SharedPreferences defaultPrefs;
        defaultPrefs = getSharedPreferences("Defaults", MODE_PRIVATE);
        String savedSessions = defaultPrefs.getString("tcpCapSessions", "None Set");

        if (savedSessions != parent.getItemAtPosition(pos).toString()) {
        final Editor defaultEdit = defaultPrefs.edit();  
        defaultEdit.putString("tcpCapSessions", parent.getItemAtPosition(pos).toString());              // Writes the key "Default Server" along with Server Name chosen (as the value).
        defaultEdit.commit();
        }

        Toast.makeText(parent.getContext(), 
                "Sessions set to: " + parent.getItemAtPosition(pos).toString(),
                Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }

}

I'm getting an error on the " MODE_PRIVATE " when getting SharedPreferences.... 获取SharedPreferences时出现“ MODE_PRIVATE ”错误。...

在此处输入图片说明

I simply want to update a preference depending on the users selection. 我只是想根据用户选择来更新首选项。 I've tried extending the Activity which gets rid of the error but the app will still crash on first launch. 我尝试扩展Activity以消除错误,但该应用在首次启动时仍会崩溃。

I've checked out Use sharedpreferences inside class but it hasn't helped me resolve the issue, may be it's missing something as it appears like the same issue as myself. 我已经检查了在类内部使用sharedpreferences的方法,但是它并没有帮助我解决问题,可能是因为缺少了某些东西,因为它看起来和我本人一样。

MODE_PRIVATE is a static member of Context . MODE_PRIVATEContext的静态成员。 It's actually described pretty good here . 实际上, 这里描述的很好。

change it to Context.MODE_PRIVATE 将其更改为Context.MODE_PRIVATE

Hi Genius try this.. 嗨,天才试试这个。

  1. Shared Preferences allow you to save and retrieve data in the form of key,value pair. 共享首选项允许您以键,值对的形式保存和检索数据。
  2. You have to call a method getSharedPreferences() that returns a SharedPreferences instance pointing to the file that contains the values of preferences. 您必须调用方法getSharedPreferences(),该方法返回一个SharedPreferences实例,该实例指向包含首选项值的文件。

      SharedPreferences sharedpreferences = getSharedPreferences(YOUR_PREFERENCE_NAME, Context.MODE_PRIVATE); 

The first parameter is the Name and the second parameter is the MODE . 第一个参数是Name ,第二个参数是MODE

Name: 名称:

Desired preferences file. 所需的首选项文件。 If a preferences file by this name does not exist, it will be created when you retrieve an editor (SharedPreferences.edit()) and then commit changes (Editor.commit()). 如果不存在使用此名称的首选项文件,则将在您检索编辑器(SharedPreferences.edit())然后提交更改(Editor.commit())时创建该文件。

Mode: 模式:

(Operating Mode) (操作模式)

  • 0 or MODE_PRIVATE for the default operation. 0MODE_PRIVATE为默认操作。
  • MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions. MODE_WORLD_READABLEMODE_WORLD_WRITEABLE来控制权限。
  • MODE_MULTI_PROCESS can also be used if multiple processes are mutating the same SharedPreferences file. 如果多个进程正在变异同一个SharedPreferences文件,则也可以使用MODE_MULTI_PROCESS

Example: 例:

public class CustomOnItemSelectedListener implements OnItemSelectedListener {

  //Initialize SharedPreferences.

    public static SharedPreferences.Editor editUserSelection;
public static SharedPreferences prefUserSelection;
public static final String GET_USER_PREF = "get_my_user";

@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {

     //save user selected position.
    prefUserSelection = getApplicationContext().getSharedPreferences(GET_USER_PREF, 0);
    editUserSelection= prefUserSelection.edit();
     editUserSelection.putInt("user", pos);
     editUserSelection.commit();
     }

For retrieve the user position, 为了检索用户位置,

prefUserSelection = getApplicationContext().getSharedPreferences(GET_USER_PREF, 0);
int userSelected = prefUserSelection .getInt("user", 0); //0 is the default value
Toast.makeText(getActivity(), "User Selected Position: "+userSelected ,Toast.LENGTH_SHORT).show();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM