建立savepreferences

package com.android.demo.savepreference;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;

public class DemoSavePreference extends Activity {
    
    private static final String PREF = "DemoSavePreference";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        SharedPreferences settings = this.getSharedPreferences(PREF, MODE_WORLD_READABLE);
        settings.edit().putString("info", "test").commit();
    }
}

 

讀取savepreferences

package com.android.demo.getsavepreference;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.widget.TextView;

public class DemoGetSavePreference extends Activity {
    private static final String PREF = "DemoSavePreference";
    TextView info;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        info = (TextView)    findViewById(R.id.info);
        Context myContext = null;
        try {
            myContext = createPackageContext("com.android.demo.savepreference",    MODE_WORLD_WRITEABLE);
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        SharedPreferences testPrefs = myContext.getSharedPreferences(PREF, 0);       
        String result = testPrefs.getString("info", "null");
        info.setText(result);
    }
}

狼翔月影 發表在 痞客邦 PIXNET 留言(0) 人氣()