无法将SharedPreference编号从总计中减去

时间:2016-04-29 19:41:48

标签: android listview android-fragments sharedpreferences android-preferences

开发卡路里应用程序,用户输入他们消耗的金额 然后显示他们剩下多少卡路里。我为共享偏好创建了一个xml,用户放置目标数量。

问题:让共享首选项减去列表视图总数。

现在该应用正在显示总金额。其中text-view称为caloriesTotal。而不是显示它想要显示重新发送的总需要。

FragmentHome.java

 public class FragmentHome extends DialogFragment implements View.OnClickListener {
      private TextView caloriesTotal;
      private ListView listView;
      private LinearLayout mLayout;
      ImageButton AddEntrybtn;
      CalorieDatabase calorieDB;
      Context context;
      private int foodCalories;
      Button mButton;
      //Database
      private DatabaseHandler dba;
      private ArrayList<Food> dbFoods = new ArrayList<>();
      private CustomListViewAdapter foodAdapter;
      private Food myFood ;
      //fragment
      private android.support.v4.app.FragmentManager fragmentManager;
      private FragmentTransaction fragmentTransaction;
      public FragmentHome() {
         // Required empty public constructor
      }
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup
      container,Bundle savedInstanceState) {
          View myView = inflater.inflate(R.layout.fragment_home, false);
          AddEntrybtn = (ImageButton) myView.findViewById(R.id.AddItems);
          AddEntrybtn.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View arg0) {
                  ((appMain) getActivity()).loadSelection(1);
              }
          });
      caloriesTotal = (TextView) myView.findViewById(R.id.tv_calorie_amount);
      listView = (ListView) myView.findViewById(R.id.ListId);
      refreshData();
      return myView;
      }
      public void refreshData (){
      dbFoods.clear();
      dba = new DatabaseHandler(getContext());
      ArrayList<Food> foodsFromDB = dba.getFoods();
      int totalCalorie = dba.totalCalories();
      String formattedCalories = Utils.formatNumber(totalCalorie);
      //setting the editTexts:
      String Prefs="" ;
      caloriesTotal.setText("Total Calories: " + formattedCalories  );
      SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
      SharedPreferences.Editor editor = sp.edit();
      editor.putString("prefs_key_current_calorie_amount", String.valueOf(Prefs));
      editor.apply();
      //Loop
      for (int i = 0; i < foodsFromDB.size(); i ++){
          String name = foodsFromDB.get(i).getFoodName();
          String date = foodsFromDB.get(i).getRecordDate();
          int cal = foodsFromDB.get(i).getCalories();
          int foodId = foodsFromDB.get(i).getFoodId();
          Log.v("Food Id", String.valueOf(foodId));
          myFood= new Food();
          myFood.setFoodId(foodId);
          myFood.setFoodName(name);
          myFood.setCalories(cal);
          myFood.setRecordDate(date);
          dbFoods.add(myFood);
     }
     dba.close();
     //setting food Adapter:
     foodAdapter = new CustomListViewAdapter(getActivity(), 
     R.layout.row_item,dbFoods);
     listView.setAdapter(foodAdapter);
     foodAdapter.notifyDataSetChanged();
     }
     @Override
     public void onActivityCreated(Bundle savedInstanceState) {
         super.onActivityCreated(savedInstanceState);
         Bundle username = getActivity().getIntent().getExtras();
         String username1 = username.getString("Username");
         TextView userMain= (TextView) getView().findViewById(R.id.User);
         userMain.setText(username1);
     }
     @Override
     public void onClick(View v) {
         switch (v.getId()) {
         case R.id.AddItems:
         AddEntry addEntry = new AddEntry();
         fragmentTransaction = fragmentManager.beginTransaction();
         fragmentTransaction.addToBackStack(null);
         fragmentTransaction.replace(R.id.FragmentHolder,addEntry)
         .commit();
         break;
         case R.id.action_settings:
         Intent preferenceScreenIntent = new Intent(getContext(), 
         PreferenceScreenActivity.class);
         startActivity(preferenceScreenIntent);
         break;
         }
     }
} 

activity_preference.xml

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceCategory android:title="User Settings">
        <EditTextPreference
            android:title="Daily Calorie Amount"
            android:inputType="number"
            android:key="@string/prefs_key_daily_calorie_amount"
            android:summary="@string/prefs_description_daily_calorie_amount" />
    </PreferenceCategory>
</PreferenceScreen>

1 个答案:

答案 0 :(得分:1)

您可以使用类似的东西来保存和检索SharedPreferences中的整数:

savePrefs("calories", totalCalories);
totalCalories = loadPrefs("calories", totalCalories);

    //save prefs
    public void savePrefs(String key, int value) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt(key, value);
        editor.apply();

    //get prefs
    public int loadPrefs(String key, int value) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        return sharedPreferences.getInt(key, value);
    }

StackOverFlow上还有许多类似问题的例子,展示了如何使用SharedPreferences。

以下是developer.android.com上有关SharedPreferences的一些文档: http://developer.android.com/reference/android/content/SharedPreferences.html http://developer.android.com/training/basics/data-storage/shared-preferences.html