android數據庫存儲方法(一)---------------SharedPreferences(實例)記錄應用程序使用次數(二)讀寫寫他應用程序

【】講之前我這說幾個本節要用到的方法

   createPackageContext(String packageName, int flags)

 註釋:Return a new Context object for the given application name.

我們要想獲得其它程序的SharedPreferences,就要先獲得該程序的context

當獲得該程序的context後,通過調用getSharedPreferences()方法來取得SharedPreferences。

【代碼】

package lc.sqlitedata.save.orio;

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.Toast;

public class ReadOtherPreferences extends Activity {
SharedPreferences pre;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Context useCount = null;
try {
useCount = createPackageContext("org.crazyit.io",
Context.CONTEXT_IGNORE_SECURITY);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pre=useCount.getSharedPreferences("count", MODE_WORLD_READABLE);
int count=pre.getInt("count", 0);
Toast.makeText(this, count+"次", 5000).show() ;


}
}

【特別講解】

我們知道,SharedPreferences保存的數據類型是key-value,所以原諒中的count實際上就是表中的key,我們取的是它的值。所以如果你取得的應用程序中,用來存儲點擊次數的key不是count的話,則在這裏會永遠是0

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章