Search code examples
androidlistviewandroid-fragmentssharedpreferencesandroid-preferences

Having trouble getting the SharedPreference number to subtract from a total


Im developing a calorie app , where the user inputs amount they consumed and then displays how many calories they have left. I created a xml for the sharedpreferences where the user puts the goal amount.

Problem : getting the Shared Preference to subtract my list-view total.

right now the app is displaying the total amount. which the text-view is called caloriesTotal. Instead of showing the total want for it to show the remanding.

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>

Solution

  • You can use something like this to save and retrieve integers from 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);
        }
    

    There's also many examples of similar questions on StackOverFlow that show how to use SharedPreferences.

    And here is some documentation on SharedPreferences from developer.android.com: http://developer.android.com/reference/android/content/SharedPreferences.html http://developer.android.com/training/basics/data-storage/shared-preferences.html