0

I have two packages in my android app: the MainActivity that handles my NavigationDrawer in the first package, and the fragments of the NavigationDrawer in the second package. Now I created a settings_fragment in the second package for some user settings, and a preferences.xml file in res/xml.

My question: How can these fragments get those preferences, and how to save them? There is a checkbox in my settings_fragment.xml, and I want this checkbox to decide between two actions. For example

  • checkbox checked: calculate_round()

  • checkbox not checked: calculate()

    How do I manage that?


MainActivity.java:

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        FragmentManager fm = getFragmentManager();
        fm.beginTransaction().replace(R.id.content_frame, new MainFragment()).commit();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.

        FragmentManager fm = getFragmentManager();

        int id = item.getItemId();

        if (id == R.id.notenrechner) {
            // Handle the camera action
            fm.beginTransaction().replace(R.id.content_frame, new NotenrechnerFragment()).commit();
        } else if (id == R.id.begriffe) {
            fm.beginTransaction().replace(R.id.content_frame, new BegriffeFragment()).commit();
        } else if (id == R.id.settings) {
            fm.beginTransaction().replace(R.id.content_frame, new SettingsFragment()).commit();
        } else if (id == R.id.teilen) {

        } else if (id == R.id.bewerten) {

        } else if (id == R.id.beenden) {
            fm.beginTransaction().replace(R.id.content_frame, new BeendenFragment()).commit();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}
Community
  • 1
  • 1

1 Answers1

0

First of all, you have to save the value of checkbox in SharedPreferences. Add this code to your settings_fragment's just after calling addPreferencesFromResource(),

CheckBoxPreference checkBoxPreference = (CheckBoxPreference) findPreference("key");
checkBoxPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() {
    @Override
    public boolean onPreferenceClick(Preference preference) {
        boolean checked = ((CheckBoxPreference)preference).isChecked();
        SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean("checkboxValue", checked);
        editor.commit();
        return false;
    }
});

Then you can get this value and decide upon the retrieved value,

boolean checked = sharedPreferences.getBoolean("checkboxValue", <defaultvalue>);
if(checked) {
    calculate_round();
} else {
    calculate();
}
Msp
  • 2,493
  • 2
  • 20
  • 34
  • What do I have to write instead of "checkBoxPreference"? I thought it's the name of my res/xml or the android:key of my checkbox preference in that res/xml but it's not... – FeuerMania Dec 26 '15 at 16:30
  • In my settings_fragment (6th line of the first code) it says "cannot resolve method 'getPreferences(int)' " – FeuerMania Dec 26 '15 at 19:30
  • I tried something... I changed SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE); to SharedPreferences sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE); – FeuerMania Dec 26 '15 at 20:13
  • That works but in the fragment which should use the preferences where i had to add the second code it says "cannot resolve symbol sharedPreferences" and is underlined red – FeuerMania Dec 26 '15 at 20:15
  • Okay, finally I added `private SharedPreferences sharedPreferences;` to the fragment which should use the preferences and I changed `` to `true`, now everything seemed to work but when i start my emulator it says **.MainActivity}: java.lang.RuntimeException: Content has view with id attribute 'android.R.id.list' that is not a ListView class** - What did I do wrong? – FeuerMania Dec 26 '15 at 22:08
  • Are you using `android.R.id.list` in your code? Add the stacktrace or MainActivity code – Msp Dec 27 '15 at 04:28
  • Find my answer above, `MainActivity` was too long for a comment – FeuerMania Dec 27 '15 at 11:52
  • Check your xml files. In one of them, you have added a view with id `android.R.id.list`. Change it to something else – Msp Dec 27 '15 at 15:43
  • I checked every xml file... But I did not find a view with id `android.R.id.list`. I also checked the Component Trees in every xml file if there was one, but I did not find the mistake – FeuerMania Dec 27 '15 at 18:29
  • If there would be a ListView in one of my xml files, there also would be an import `import android.widget.listview` but I really cannot find it – FeuerMania Dec 28 '15 at 19:30