2011年6月24日星期五

  存储和检索数据

使用首选项

在Android中的Activity之间切换时,将一些全局应用程序状态存储在SharedPreferences对象中是非常方便的。可以通过当前所用的Context来访问SharedPreferences对象。Context包括一个getSharedPreferences(String name,int accessMode)方法。

XML

public void onCreate(final Bundle icicle) {
        super.onCreate(icicle);
        this.setContentView(R.layout.read_xmlresource_file);

        this.readOutput = (TextView) findViewById(R.id.readxmlres_output);

        XmlPullParser parser = getResources().getXml(R.xml.people);
        StringBuffer sb = new StringBuffer();

        try {
            while (parser.next() != XmlPullParser.END_DOCUMENT) {
                String name = parser.getName();
                Log.v(ReadXMLResourceFile.LOGTAG, "    parser NAME - " + name);
                String first = null;
                String last = null;
                if ((name != null) && name.equals("person")) {
                    int size = parser.getAttributeCount();
                    for (int i = 0; i < size; i++) {
                        String attrName = parser.getAttributeName(i);
                        String attrValue = parser.getAttributeValue(i);
                        if ((attrName != null) && attrName.equals("firstname")) {
                            first = attrValue;
                        } else if ((attrName != null) && attrName.equals("lastname")) {
                            last = attrValue;
                        }
                    }
                    if ((first != null) && (last != null)) {
                        sb.append(last + ", " + first + "\n");
                    }
                }
            }
            this.readOutput.setText(sb.toString());
        } catch (Exception e) {
            Log.e(ReadXMLResourceFile.LOGTAG, e.getMessage(), e);
        }       

在Android中,ContentProvider用于在不同应用程序之间共享数据。

没有评论:

发表评论