【问题标题】:Android getPrefernces(int) is undefinedAndroid getPrefernces(int) 未定义
【发布时间】:2015-04-23 21:25:12
【问题描述】:

**在进行研究并尝试查看 stackoverflow 解决方案并尝试应用它们并完全失败后,此错误仍然存​​在。 我正在尝试使用 SharedPreferences 和 getPreferences 来保存数据。

**如何将其用作仅包含 10 个单元格的数组?(因此它将保存我输入的最后十个值,并且我可以按最大值排序)

代码:

public void onClick(View v) {
        // TODO Auto-generated method stub
        SharedPreferences sharedPref = this.getPrefernces(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        EditText name = (EditText)findViewById(R.id.namep);
        editor.putString(name.getText().toString(), score);
        editor.commit();

    }

在第一行(sharedPref 的定义)我得到了这个错误: 未为类型 new View.OnClickListener(){}

定义方法 getPrefernces(int)

我试过用几种方法来切换它,但没有人能用,在此之后我什至不能调用 getActivity() 函数。我不知道为什么我的代码会扩展 Activity。 我试过这个灵魂: How to resolve an error: getSharedPreferences(String, int) is undefined for the type new View.OnClickListener(){}

The method setOnClickListener(new View.OnClickListener(){}) is undefined for the type imageButton1

【问题讨论】:

  • 首选项拼写错误..
  • getPreferences 仍在工作

标签: java android sharedpreferences


【解决方案1】:

试试这个:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);

SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);

【讨论】:

    【解决方案2】:

    OnClickListner 中的this 将指向该匿名类,而不是Activity。所以你必须改用你的Activity 参考。

    改变

    SharedPreferences sharedPref = this.getPrefernces(Context.MODE_PRIVATE); 
    

    SharedPreferences sharedPref = Your_Activity_Name.this.getPrefernces(Context.MODE_PRIVATE);
    

    【讨论】:

      【解决方案3】:

      您在匿名类 OnClickListener 中执行此操作,并且您的“this”指向它。你需要像这样调用方法

      OuterActivity.this.getPreferences(Context.MODE_PRIVATE);
      

      OuterFragment.this.getActivity().getPreferences(Context.MODE_PRIVATE);
      

      【讨论】:

      • 如果我只是这样做会有不同 = getPreferences(Context.MODE_PRIVATE);到 OuterFragment.this.getActivity().getPreferences(Context.MODE_PRIVATE);
      • “OuterFragment.this./OuterActivity.this”是可选的
      【解决方案4】:

      您必须使用 Context 对象调用该方法。上面代码中的“this”是什么?然后试试@Piotr 代码。

      【讨论】:

        【解决方案5】:

        你不能用

        this.getPrefernces(Context.MODE_PRIVATE); 
        

        在 View.onClickListener 中,因为那不是同一个实例。 而不是这个,你必须使用类似的东西:

        public void click(View v) {
            SharedPreferences pref = PreferenceManager
                    .getDefaultSharedPreferences(MainActivity.this);
        //Your other code
        }
        

        重点是您必须从活动中获取 sharedPreferences,而不是从 onClickListener 中获取。

        【讨论】:

          猜你喜欢
          • 2013-02-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-01-25
          • 2019-06-21
          • 2016-06-28
          • 2015-10-22
          相关资源
          最近更新 更多