在android中存储和获取sharedpreferences的值

时间:2014-04-21 04:53:43

标签: java android listview

我想在sharedpreferences中存储值,并从sharedpreferences获取值最终显示listview中的值。接下来,我想在单击特定值的longpress时从列表中删除值。删除在sharedpreferences中更新的值状态。我做了这个,但问题是当关闭应用程序并再次打开时,我必须在listview中显示sharedpreferences vales。但它显示NullPointerExeption

实际上我的要求是1)将值存储在sharedpreferences中并在listview中显示每次点击的值。仅允许五个值。并且onresume()方法中也可以使用该列表值。 2)当长按listview的特定值时,它必须删除,并且更新的值也存储在sharedpreferences中。

我的代码

public class ListViewDemo1 extends Activity {
    /**
     * Called when the activity is first created.
     */
    Button btn;
    static int count;
    private ListView list;
    public static ArrayList<String> values = new ArrayList<String>();        
    ArrayList countList = new ArrayList();
    private ArrayAdapter adapter;
    SharedPreferences shared;
    Editor editor;
    private static ArrayList<String> sharedList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        list = (ListView) findViewById(R.id.list);
        btn = (Button) findViewById(R.id.btn);
        shared = this.getSharedPreferences("Myprefernces", Context.MODE_WORLD_WRITEABLE);
        editor = shared.edit();
        btn.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                sharedList = new ArrayList();
                count++;
                if (count == 1) {
                    values.add("one");
                    countList.add(count);
                }
                if (count == 2) {
                    values.add("two");
                    countList.add(count);
                }
                if (count == 3) {
                    values.add("three");
                    countList.add(count);
                }
                if (count == 4) {
                    values.add("four");
                    countList.add(count);

                }
                if (count == 5) {
                    values.add("five");
                    countList.add(count);
                }
                if (count > 5) {
                    --count;
                    Toast.makeText(getApplicationContext(), "" + count, 100).show();
                }
                //put values to sharedpreferences
                editor.putInt("SIZE", values.size());
                for (int i = 0; i < values.size(); i++) {
                    editor.putString("addr" + i, values.get(i));
                }
                editor.commit();
                // getting values from sharedpreference
                int size = shared.getInt("SIZE", 0);
                for (int k = 0; k < size; k++) {
                    sharedList.add(shared.getString("addr" + k, ""));
                }
                adapter = new
                        ArrayAdapter(ListViewDemo1.this, android.R.layout.simple_list_item_1, sharedList);
                list.setAdapter(adapter);
            }
        });
        list.setOnItemLongClickListener(new OnItemLongClickListener() {

            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                           int arg2, long arg3) {
                // TODO Auto-generated method stub
                --count;
                values.remove(arg2);
                sharedList.remove(arg2);
                editor.clear();
                editor.commit();
                editor.putInt("SIZE", sharedList.size());
                for (int i = 0; i < sharedList.size(); i++) {
                    editor.putString("addr" + i, sharedList.get(i));
                }
                editor.commit();
                adapter.notifyDataSetChanged();


                return true;
            }
        });

    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        if (sharedList.size() > 0) {
            adapter = new
                    ArrayAdapter(ListViewDemo1.this, android.R.layout.simple_list_item_1, sharedList);
            list.setAdapter(adapter);
        }
    }
}

logcat的

04-21 09:56:02.142: E/AndroidRuntime(1160): FATAL EXCEPTION: main
04-21 09:56:02.142: E/AndroidRuntime(1160): java.lang.RuntimeException: Unable to resume activity {com.views/com.views.ListViewDemo1}: java.lang.NullPointerException
04-21 09:56:02.142: E/AndroidRuntime(1160):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-21 09:56:02.142: E/AndroidRuntime(1160):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
04-21 09:56:02.142: E/AndroidRuntime(1160):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-21 09:56:02.142: E/AndroidRuntime(1160):     at android.os.Looper.loop(Looper.java:137)
04-21 09:56:02.142: E/AndroidRuntime(1160):     at android.app.ActivityThread.main(ActivityThread.java:5041)
04-21 09:56:02.142: E/AndroidRuntime(1160):     at java.lang.reflect.Method.invokeNative(Native Method)
04-21 09:56:02.142: E/AndroidRuntime(1160):     at java.lang.reflect.Method.invoke(Method.java:511)
04-21 09:56:02.142: E/AndroidRuntime(1160):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-21 09:56:02.142: E/AndroidRuntime(1160):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-21 09:56:02.142: E/AndroidRuntime(1160):     at dalvik.system.NativeStart.main(Native Method)
04-21 09:56:02.142: E/AndroidRuntime(1160): Caused by: java.lang.NullPointerException
04-21 09:56:02.142: E/AndroidRuntime(1160):     at com.views.ListViewDemo1.onResume(ListViewDemo1.java:114)
04-21 09:56:02.142: E/AndroidRuntime(1160):     at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1185)

3 个答案:

答案 0 :(得分:1)

仅在按钮的sharedList方法中实例化onClick()。恢复活动并且sharedList为空时,不会调用此方法。

您需要检查它是否为空:

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    if(sharedList != null && sharedList.size()>0){
        adapter=new ArrayAdapter(ListViewDemo1.this,android.R.layout.simple_list_item_1,sharedList);
        list.setAdapter(adapter);
    }
} 

答案 1 :(得分:0)

我认为问题在于初始化(或者说不是这样做),

static int count;
public static ArrayList<String>  values = new ArrayList<String>();
private static ArrayList<String> sharedList;

现在,例如,未初始化计数到之前的值:

count++;  
if(count==1){  

sharedList需要完成同样的工作,例如new ArrayList ...

是的,每次onCreate()之前都没有调用onResume()的原因,有关推荐Android Activity Life Cycle的更多内容 检查图1.活动生命周期。在那个链接上。

它可以让您更好地了解您的实施/要求,以及如何初始化或使用sharedPref以及您的活动的其他组件。

答案 2 :(得分:0)

请阅读此内容我希望能帮助您http://developer.android.com/guide/topics/data/data-storage.html

您可以使用SharedPreferences:

保存数据:

SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
 editor.putString("text", mSaved.getText().toString());
 editor.putInt("selection-start", mSaved.getSelectionStart());
 editor.putInt("selection-end", mSaved.getSelectionEnd());
 editor.commit();

要检索数据:

SharedPreferences prefs = getPreferences(MODE_PRIVATE); 
String restoredText = prefs.getString("text", null);
int selectionStart = prefs.getInt("selection-start", -1);
int selectionEnd = prefs.getInt("selection-end", -1);