我正在尝试使用SharedPrefrences保存数据,但我收到此错误:
错误:(26,36)错误:找不到符号方法getActivity()
我需要导入一些东西吗?
这是我的java文件:
package test.test;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
/**@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}**/
}
答案 0 :(得分:2)
您不需要在活动中致电getActivity()
,只需使用this
或完全跳过它并致电getSharedPreferences
答案 1 :(得分:2)
您甚至不需要这样做:
Context context = getActivity();
Activity
是一个上下文。
只是做:
Context context = this;
或者只是:
SharedPreferences sharedPref = this.getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
甚至只是:
SharedPreferences sharedPref = getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);