2013-04-21 67 views
0

我有一個listview與選擇模式,它的工作。我想將選中的項目保存爲共享首選項,然後將其用於其他活動。但是,我的SharedPreferences不能保存我的字符串正確,並保存另一個我從未在我的代碼中調用的文件調用DATA_Preferences。 結果是我的下一個活動得到錯誤的值..爲什麼我的SharedPreference創建另一個文件名DATA_Preferences?

這裏是我的代碼,我用它來保存我的字符串,並將其命名爲另一個活動使用:

public void onClick(View v) { 

      SparseBooleanArray checked = listView.getCheckedItemPositions(); 
      ArrayList<DBLokasi> selectedItems = new ArrayList<DBLokasi>(); 

      // Item position in adapter 
      SharedPreferences prefs = getSharedPreferences("DATA_COOR", Context.MODE_PRIVATE); 
      SharedPreferences.Editor prefsEditor = prefs.edit(); 

      for (int i = 0; i < checked.size(); i++) { 


       int position = checked.keyAt(i); 
       // Add slected if truee 
       if (checked.valueAt(i)) 
        selectedItems.add(adapter.getItem(position)); 

       prefsEditor.putFloat(POINT_LATITUDE_KEY + i, Float.parseFloat(values.get(position).getLat())); 
       prefsEditor.putFloat(POINT_LONGITUDE_KEY + i, Float.parseFloat(values.get(position).getLng())); 


      } 
      prefsEditor.commit(); 

      String[] outputStrArr = new String[selectedItems.size()]; 



      for (int i = 0; i < selectedItems.size(); i++) { 
       outputStrArr[i] = String.valueOf(selectedItems.get(i)); 
      } 


      Bundle b = new Bundle(); 


      Location location = new Location("POINT_LOCATION"); 

      for (int i = 0; i < checked.size(); i++) { 

       location.setLatitude(prefs.getFloat(POINT_LATITUDE_KEY + i, 0)); 
       location.setLongitude(prefs.getFloat(POINT_LONGITUDE_KEY + i, 0)); 

       double latitude = prefs.getFloat(POINT_LATITUDE_KEY + i, 0); 
       double longitude = prefs.getFloat(POINT_LONGITUDE_KEY + i, 0); 
       prefsEditor.commit(); 

       b.putDouble("Latitude" + i, latitude); 
       b.putDouble("Longitude" + i, longitude); 



       } 

      int banyakPilih = checked.size(); 
      b.putInt("banyakPilih", banyakPilih); 

      Intent intent = new Intent(getApplicationContext(), 
        HasilPilihanActivity.class); 

      // Create a bundle object 
      b.putStringArray("selectedItems", outputStrArr); 

      // Add the bundle to the intent. 
      intent.putExtras(b); 

      // start the ResultActivity 
      startActivity(intent); 
     } 

保存我的DATA_COOR.xml Prefernces文件名,它保存我的字符串,但我有另一個文件,我的資源管理器中保存我的首選項與文件名DATA_Preferences。有些機構可以給我解決方案嗎?由於之前..

回答

0

定義私有SharedPreferences mediaPrefs = null;

把這個構造函數mediaPrefs = this.getSharedPreferences("Testing", 1);

把下面的方法來源:

public void storeStateString(String prefsKeys, Float prefsValue) { 
     SharedPreferences.Editor prefEditor = mediaPrefs.edit(); 
     prefEditor.putFloat(prefsKeys, prefsValue); 
     prefEditor.commit(); 
    } 

使用此方法來存儲喜歡的狀態:

storeStateString("POINT_LATITUDE_KEY"+i,Float.parseFloat(values.get(position).getLat()));

現在你可以打通此偏好:

Float finalValue = mediaPrefs.getFloat("POINT_LATITUDE_KEY1","2.0l"); 

其中2.0升是defalut值,如果mediaPrefs爲null;

讓我知道是否有任何問題。

相關問題