簡體   English   中英

共享偏好值未被保存

[英]Shared Preference Value not being Saved

我正在開發一個應用程序,其中用戶在共享首選項中輸入一個值,並被檢索以減去卡路里數。

現在,我的卡路里應用程序硬編碼為 2000。用戶每天消耗的限制為 2000。 我希望用戶能夠更改共享首選項的消耗量,但由於某種原因,它沒有被保存。 這就是我硬編碼它的原因。

PreferenceScreenActivity.java

public class PreferenceScreenActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_preference);

        // Replace the default view with the preference fragment

        getFragmentManager().beginTransaction().replace(R.id.preference_container,
        new PreferenceScreenFragment()).commit();
    }

    public static class PreferenceScreenFragment extends PreferenceFragment 
    {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.activity_preference);
        }
    }
}

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:defaultValue="2000"
            android:key="@string/prefs_key_daily_calorie_amount"
            android:summary="@string/prefs_description_daily_calorie_amount"
        />
    </PreferenceCategory>
</PreferenceScreen>

片段首頁.JAVA

public class FragmentHome extends DialogFragment 
implements View.OnClickListener  {
    private TextView caloriesTotal;

    private TextView caloriesRemain;

    private ListView listView;
    private LinearLayout mLayout;

    ImageButton AddEntrybtn;
    CalorieDatabase calorieDB;
    Context context;

    int goalCalories;
    AlarmManager am;

    private int  CaloriesRemain;
    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, container, false);

        AddEntrybtn = (ImageButton) myView.findViewById(R.id.AddItems);

        AddEntrybtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                ((appMain) getActivity()).loadSelection(4);
            }
        });

        caloriesTotal = (TextView) myView.findViewById(R.id.tv_calorie_amount);
        caloriesRemain = (TextView) myView.findViewById(R.id.calorieRemain);
        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);
        String formattedRemain = Utils.formatNumber( 2000-   totalCalorie);
        *Hard coded 2000 amount here * *this works and does get 2000 but
        want to get the shared value here **

        //setting the editTexts:
        caloriesTotal.setText("Total Calories: " + formattedCalories);
        caloriesRemain.setText(formattedRemain);

        CaloriesRemain = loadPrefs(formattedRemain, totalCalorie);

        SharedPreferences prefs =  
            PreferenceManager.getDefaultSharedPreferences(getContext());
        PreferenceManager.setDefaultValues(getActivity(),  
            R.xml.activity_preference, false);

        String 
            etCalorieRemain=prefs.getString("prefs_key_daily_calorie_amount", 
            "default_edit_text_value");

        goalCalories = 
            Integer.parseInt(prefs.getString("prefs_key_daily_calorie_amount",
            "2000"));


        //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();
    }

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

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


    @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 onDetach() {
        super.onDetach();

        startActivity( new Intent(getContext(),MainActivity.class));
    }


    @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;
        }
    }
}

如我所見,您有CaloriesRemain變量和savePrefs()方法,但您無處使用變量和方法的值。

看,如果您使用 PreferenceFragment - 它會自動從 SharedPreferences 保存和加載您的首選項。

如果您需要在代碼中使用 SharedPreferences 中的值 - 您應該通過您的密鑰( @string/prefs_key_daily_calorie_amount )請求它們。

目前您使用CaloriesRemain = loadPrefs(formattedRemain, totalCalorie); ,但不要使用formattedRemain您應該使用您的密鑰@string/prefs_key_daily_calorie_amount 然后在您的代碼中使用CaloriesRemain變量。

希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM