无法从sharedPreference获取以前保存的数据

时间:2011-03-21 11:41:29

标签: android sharedpreferences

public class RegularExpensesActivity extends ListActivity implements OnClickListener{

    private static final String TAG = "RegularExpensesActivity";


    private static final int state_edit = 0;
    private static final int state_insert = 1;
    private static final String array_key = "array";
    private static final String pref_name = "Setting";
    private static final String des_key = "DES";
    private static final String amt_key = "AMT";

    private String des;
    private String amt;
    private ArrayList<HashMap<String, String>> list;
    ArrayList<String> array;
    HashMap<String, String> map;

    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;

    private Button add_btn;
    private EditText description;
    private EditText amount;

    private SimpleAdapter adapter;


    private int clickedPosition;

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

        preferences = getSharedPreferences (pref_name, MODE_PRIVATE);

        list = new ArrayList<HashMap<String, String>>();
        map = new HashMap<String, String>();
        retrieveAndLoadData();
        displayList();


        add_btn = (Button) findViewById(R.id.button_add_reg);
        add_btn.setOnClickListener(this);
        add_btn.setText(R.string.btn_add);

    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {

        clickedPosition = position;

        openDialog(state_edit);
    }

    @Override
    public void onClick(View view) {
            if(view==add_btn){
                openDialog(state_insert);
            }
    }

    private void openDialog(int state) {
        LayoutInflater inflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.reg_add_edit, null);

        description = (EditText) view.findViewById(R.id.edit_reg_description);
        amount = (EditText) view.findViewById(R.id.edit_reg_amount);

        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setView(view)
             .setIcon(android.R.drawable.ic_menu_more);

         switch(state){
         case state_insert:
            alert.setTitle("Add Record")
                 .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int id) {

                    if(!description.getText().toString().equals(null)&& !amount.getText().toString().equals(null)){
                        array.add(description.getText().toString());
                        map = new HashMap<String, String>();
                        map.put(des_key, description.getText().toString());
                        map.put(amt_key, amount.getText().toString());
                        list.add(map);
                        editor = preferences.edit();
                        editor.putString(array_key, fromArrayListToString(array));
                        editor.putString(""+array.indexOf(description.getText().toString()), amount.getText().toString());
                        editor.commit();
                        adapter.notifyDataSetChanged();
                        dialog.dismiss();
                    }

                }
                })
                 .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            dialog.cancel();
                        }
                    });
            break;
         case state_edit:
            String selectedDes;
            String selectedAmt;

            selectedDes = array.get(clickedPosition);
            selectedAmt = preferences.getString(""+clickedPosition, "0");

            description.setText(selectedDes);
            amount.setText(selectedAmt);

            alert.setTitle("Edit Record")
                 .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {

                        if(!description.getText().toString().equals(null)&& !amount.getText().toString().equals(null)){
                            array.set(clickedPosition, description.getText().toString());
                            map = new HashMap<String, String>();
                            map.put(des_key, description.getText().toString());
                            map.put(amt_key, amount.getText().toString());
                            list.set(clickedPosition, map);
                            editor = preferences.edit();
                            editor.putString(array_key, fromArrayListToString(array));
                            editor.putString(""+clickedPosition, amount.getText().toString());
                            editor.commit();

                            dialog.dismiss();
                            adapter.notifyDataSetChanged();

                            Toast.makeText(getBaseContext(),"Record added.",Toast.LENGTH_LONG).show();
                        }

                    }
                    })
                    .setNegativeButton("Delete", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,int id) {

                                array.remove(clickedPosition);
                                list.remove(clickedPosition);

                                for(int i = clickedPosition;i<array.size();i++){
                                    int oldPosition = i+1;
                                    String old = preferences.getString(""+oldPosition,"0");
                                    editor = preferences.edit();
                                    editor.putString(""+i, old);
                                }
                                editor.putString(array_key, fromArrayListToString(array));
                                editor.commit();

                                dialog.cancel();
                                adapter.notifyDataSetChanged();
                                Toast.makeText(getBaseContext(),"Deleted.",Toast.LENGTH_LONG).show();
                            }
                        });
             break;
         }

         alert.create();
         alert.show();
    }

    public String fromArrayListToString(ArrayList<String> arrayList) {
        StringBuffer packedString = new StringBuffer();
        for (int i = 0; i < arrayList.size(); i++) {
            if (i > 0) {
                packedString.append("\u001f");
            }
            packedString.append(arrayList.get(i));
        }
        return packedString.toString();
    }

    public ArrayList<String> getArrayList(String packedString) {
        String[] array = packedString.split("\u001f");
        ArrayList<String> returnArrayList = new ArrayList<String>();

        Log.d(TAG, "split array length: "+array.length);
        if(!array[0].equals("")){
        for (int i = 0; i < array.length; i++) {
            returnArrayList.add(array[i]);
        }
        }
        return returnArrayList;
    }
    private String convText(TextView v,String text) {
        switch (v.getId()) {
        case R.id.reg_amount:
            double dblAmt;
            if(!text.equals("0")){
            DecimalFormat twoDigit = new DecimalFormat("#,##0.00");

            dblAmt = Double.parseDouble(text);

            return "RM "+twoDigit.format(dblAmt);
            }
        }
        return text;
    }   

    private void displayList() {
        adapter = new SimpleAdapter(this, list, R.layout.reg_row, new String[] { des_key, amt_key }, 
                new int[] { R.id.reg_description,R.id.reg_amount}){
                @Override
                public void setViewText(TextView v, String text) {
                    super.setViewText(v, convText(v, text));
                }
            };
            setListAdapter(adapter);
    }

    private void retrieveAndLoadData() {
        des=preferences.getString(array_key,""); 
        Log.d(TAG, des);
        array = getArrayList(des);

        for(int i=0;i<array.size();i++){
            map = new HashMap<String, String>();
            map.put(des_key, array.get(i));
            map.put(amt_key, preferences.getString(""+i, "0"));
            list.add(map);
        }
    }
}

我是Android应用程序开发的初学者,我真的需要一些帮助。当我添加第一条记录时,我的代码运行良好,我可以在重新启动应用程序后恢复记录。但是当我试图添加第二条记录时,我会收到此警告,并且在重新启动后我无法获得以前保存的记录。

WARN/ApplicationContext(17598): getSharedPreferences
WARN/ApplicationContext(17598): org.xmlpull.v1.XmlPullParserException: Error parsing document. (position:line -1, column -1) caused by: org.apache.harmony.xml.ExpatParser$ParseException: At line 4, column 27: not well-formed (invalid token)
WARN/ApplicationContext(17598):     at org.apache.harmony.xml.ExpatPullParser$ByteDocument.flush(ExpatPullParser.java:958)
WARN/ApplicationContext(17598):     at org.apache.harmony.xml.ExpatPullParser$Document.pump(ExpatPullParser.java:769)
WARN/ApplicationContext(17598):     at org.apache.harmony.xml.ExpatPullParser$Document.dequeue(ExpatPullParser.java:813)
WARN/ApplicationContext(17598):     at org.apache.harmony.xml.ExpatPullParser.next(ExpatPullParser.java:302)
WARN/ApplicationContext(17598):     at com.android.internal.util.XmlUtils.readValueXml(XmlUtils.java:675)
WARN/ApplicationContext(17598):     at com.android.internal.util.XmlUtils.readMapXml(XmlUtils.java:470)
WARN/ApplicationContext(17598):     at android.app.ContextImpl.getSharedPreferences(ContextImpl.java:373)
WARN/ApplicationContext(17598):     at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:146)
WARN/ApplicationContext(17598):     at com.yan.app.RegularExpensesActivity.onCreate(RegularExpensesActivity.java:78)
WARN/ApplicationContext(17598):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
WARN/ApplicationContext(17598):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1586)
WARN/ApplicationContext(17598):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1638)
WARN/ApplicationContext(17598):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
WARN/ApplicationContext(17598):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:928)
WARN/ApplicationContext(17598):     at android.os.Handler.dispatchMessage(Handler.java:99)
WARN/ApplicationContext(17598):     at android.os.Looper.loop(Looper.java:123)
WARN/ApplicationContext(17598):     at android.app.ActivityThread.main(ActivityThread.java:3647)
WARN/ApplicationContext(17598):     at java.lang.reflect.Method.invokeNative(Native Method)
WARN/ApplicationContext(17598):     at java.lang.reflect.Method.invoke(Method.java:507)
WARN/ApplicationContext(17598):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
WARN/ApplicationContext(17598):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
WARN/ApplicationContext(17598):     at dalvik.system.NativeStart.main(Native Method)

为什么会这样?谁能给我一些建议?我的代码有什么问题?感谢。

编辑:

editor = preferences.edit();
for(int i = clickedPosition;i<array.size();i++){
    int oldPosition = i+1;
    String old = preferences.getString(""+oldPosition,"0");

    editor.putString(""+i, old);
}
editor.putString(array_key, fromArrayListToString(array));
editor.commit();

使用我的代码更新。

2 个答案:

答案 0 :(得分:1)

public void onClick(DialogInterface dialog,int id) {

                            array.remove(clickedPosition);
                            list.remove(clickedPosition);

                            for(int i = clickedPosition;i<array.size();i++){
                                int oldPosition = i+1;
                                String old = preferences.getString(""+oldPosition,"0");
                                editor = preferences.edit();
                                editor.putString(""+i, old);
                            }
                            editor.putString(array_key, fromArrayListToString(array));
                            editor.commit();

                            dialog.cancel();
                            adapter.notifyDataSetChanged();
                            Toast.makeText(getBaseContext(),"Deleted.",Toast.LENGTH_LONG).show();
                        }
                    });

这看起来很奇怪。在for循环中,你打开多个编辑器而不提交它们,最后你只提交最后一个。我不知道这是否是您问题的根源,但这是一个问题:)

答案 1 :(得分:0)

你需要这个:

preferences = getAplicationContext().getSharedPreferences (pref_name, MODE_PRIVATE);

如果我没弄错,sharedPreferences需要aplication的上下文。