2013-04-21 31 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;

让我知道是否有任何问题。

相关问题