列表的共享首选项

时间:2012-12-29 18:53:13

标签: android sharedpreferences

作为一名经验不足的Android程序员,我需要一些帮助。我正在为一个需要一个可记录祷告请求的活动的教会设计这个应用程序(类似于制作待办事项列表)。此时我可以将项目输入到列表中,但它们似乎没有保存并在使用下面的共享首选项摘录关闭后返回,同时查看此站点看起来我可以在没有按下物理按钮的情况下执行此操作保存。

SharedPreferences prayRequests = getPreferences(Activity.MODE_PRIVATE);

ListView myListViewa = (ListView)findViewById(R.id.myListView);

SharedPreferences.Editor editor = prayerRequests.edit();

editor.putString("prayers", myListViewa.toString());

editor.apply();

全班都在这里:

   package com.direction.investor.prayerjournal;

   import java.util.ArrayList;



   import android.annotation.TargetApi;
   import android.app.Activity;
   import android.os.Build;
   import android.os.Bundle;
   import android.view.KeyEvent;
   import android.view.View;
   import android.widget.ArrayAdapter;
   import android.widget.EditText;
   import android.widget.ListView;
   import android.widget.TextView;
   import android.content.SharedPreferences;
   import android.content.SharedPreferences.Editor;



 public class prayerRequests extends Activity {

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void onCreate(Bundle savedInstanceState) 
{ super.onCreate(savedInstanceState);
setContentView(R.layout.prayerrequest);

ListView myListView = (ListView)findViewById(R.id.myListView);
final EditText myEditText = (EditText)findViewById(R.id.myEditText);

final ArrayList<String> prayers = new ArrayList<String> ();

final ArrayAdapter<String> aa;

aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, prayers);

myListView.setAdapter(aa);



SharedPreferences prayerRequests = getPreferences(Activity.MODE_PRIVATE);

ListView myListViewa = (ListView)findViewById(R.id.myListView);

SharedPreferences.Editor editor = prayerRequests.edit();

editor.putString("prayers", myListViewa.toString());

editor.apply();






myEditText.setOnKeyListener(new View.OnKeyListener() {
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN)
            if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER) ||
                    (keyCode == KeyEvent.KEYCODE_ENTER)) {

                prayers.add(0, myEditText.getText().toString());
                aa.notifyDataSetChanged();
                myEditText.setText("");
                return true;

            }
        return false;
    }
});


}


}

1 个答案:

答案 0 :(得分:0)

我建议使用数据库而不是共享偏好

seee http://developer.android.com/guide/topics/data/data-storage.html#db