2013-06-26 11 views
1

我在我的應用程序中使用getDefaultSharedPreferences(con)來存儲首選項。現在我想在另一個應用程序中訪問這個共享首選項。 我用下面的方法:跨應用程序訪問sharedpreference

con = this.createPackageContext("com.example.preferences", Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY); 
SharedPreferences filePref = PreferenceManager.getDefaultSharedPreferences(con); 
      if(filePref != null){ 
       Toast.makeText(getApplicationContext(), "file pref not null --- ", Toast.LENGTH_LONG).show(); 
      }else{ 
       Toast.makeText(getApplicationContext(), "file pref is null **** ", Toast.LENGTH_LONG).show(); 
      } 
      Map<String,?> allkeys = filePref.getAll(); 
      Toast.makeText(getApplicationContext(), "file pref size **** "+allkeys.size(), Toast.LENGTH_LONG).show(); 
      for(Map.Entry<String,?> entry : allkeys.entrySet()){ 
       Toast.makeText(getApplicationContext(), "~~~ file pref --- map values --- "+entry.getKey() + ": "+entry.getValue().toString(), Toast.LENGTH_LONG).show(); 
      } 

的另一種方法,其試圖被指定的文件名&訪問它,如下;

SharedPreferences filePref = gvcon.getSharedPreferences("com.example.preferences_preferences", Context.MODE_PRIVATE); 

用這種方法我能夠訪問SharedPrefernce文件,返回文件不爲空,但是當我檢查文件大小就顯示爲0。我無法從文件中讀取優先值。 我使用了另一個應用程序的shareduserid,以便我可以完全訪問該應用程序。 這是什麼正確的方法?

+0

看看從另一個包訪問共享數據在此回覆 http://stackoverflow.com/a/13236870/1936366 這 http://stackoverflow.com/questions/6030321/android-retrieving-shared-preferences-of-other-application –

回答

0

我不確定我是否完全理解了您的問題,但有時這個實現將幫助您跨包訪問數據。 使用getSharedPreferences()將數據存儲在共享偏好

此方法將數據存儲在共享偏好

public void dataWriter(){ 
    String strShareValue = "Hello! this is shared data"; 
    SharedPreferences prefs = getSharedPreferences("demopref",Context.MODE_WORLD_READABLE); 
    SharedPreferences.Editor editor = prefs.edit(); 
    editor.putString("demostring", strShareValue); 
    editor.commit(); 
} 

您可以使用此代碼示例

public void dataRead(){ 
Context con; 
    try { 
     con = createPackageContext("PACKAGE NAME THAT SHARES DATA", 0); 
     SharedPreferences pref = con.getSharedPreferences("demopref", Context.MODE_PRIVATE); 
     String dataShared = pref.getString("demostring", "No Value"); 
     } 
    catch (NameNotFoundException e) { 
     Log.e("Not data shared", e.toString()); 
     } 
    } 
} 
+1

感謝您的答覆。我擔心的是,何時創建共享首選項而不指定名稱,但使用默認方法,即使用prefernceactivity並存儲在/data/data/packagename_preference.xml下。在這種情況下,我無法從xml文件讀取首選項值。 – Namrata