2015-04-23 26 views
0

**經過研究和嘗試後,看太多的stackoverflow解決方案,並試圖applay他們和失敗的所有,這個錯誤仍然appers。Iam嘗試使用SharedPreferences和getPrefernces保存數據。 ?Android getPrefernces(int)未定義

**我該如何使用它作爲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(); 

    } 

在第一行IVE(sharedPref的defind)得到這個錯誤: 方法getPrefernces(INT)是未定義的類型新View.OnClickListener(){}

伊夫試圖切換它在幾種方式沒有那些工程,我甚至不能在此之後調用getActivity()函數。我不知道爲什麼我的代碼擴展活動。 伊夫嘗試這種soultions: 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

+0

首選項拼寫錯誤 – amdixon

+0

getPreferences現在仍在工作 – Adi

回答

1

試試這個:

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

SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE); 
+0

一次工作謝謝 – Adi

1

thisOnClickListner內將指向該匿名類,而不是Activity 。所以你必須在那裏使用你的Activity參考。

變化

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

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

您在匿名類OnClickListener和你的 「本」 指向它做到這一點。您需要調用的方法是這樣

OuterActivity.this.getPreferences(Context.MODE_PRIVATE); 

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

有沒有不同,如果我只是做= getPreferences(Context.MODE_PRIVATE);到OuterFragment.this.getActivity()。getPreferences(Context.MODE_PRIVATE); – Adi

+0

「OuterFragment.this./OuterActivity.this」是可選的 – Yaroslav

0

你必須調用與上下文對象的方法。上述代碼中的「this」是什麼?然後嘗試@Piotr代碼。

0

在View.onClickListener不能使用

this.getPrefernces(Context.MODE_PRIVATE); 

,因爲這是不一樣的實例。 取而代之的是,你必須使用類似的東西:

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

的一點是,你必須從一個活動,而不是從onClickListener得到sharedPreferrences。

相關問題