我试图加载 SharedPreferences 但从未找到共享首选项,并且我试图从另一个类更新它,但这也不起作用。我也将 lst 适配器用于列表视图。以下代码有什么想法吗?我正在获取列表视图的备份 hello 字符串。
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class WorldMenu extends ListActivity{
SharedPreferences prefs = null;
String splitter;
String[] worldList;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
context = getBaseContext();
prefs = context.getSharedPreferences("worldString", 1);
splitter = "Create World," + prefs.getString("worldString", "hello");
worldList = splitter.split(",");
setListAdapter(new ArrayAdapter<String>(WorldMenu.this,
android.R.layout.simple_list_item_1, worldList));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
if(position == 0){
Intent openWorldNamer = new Intent("this works no need to check");
startActivity(openWorldNamer);
}
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
编辑更新程序类:
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class WorldCreator extends Activity{
EditText worldNameEditor;
Button saver;
SharedPreferences prefs;
OnSharedPreferenceChangeListener listener;
String updater2;
Editor editor;
String updater;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_worldcreator);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
worldNameEditor = (EditText) findViewById(R.id.hello);
saver = (Button) findViewById(R.id.button1);
updater2 = worldNameEditor.getText().toString() + ",";
saver.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
updater = updater2;
editor = prefs.edit();
editor.putString("worldString", updater);
editor.commit();
Intent openListWorld = new
Intent("the list activity");
startActivity(openListWorld);
}});
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
}