Question

I'm a noob working on my first app that consists of the following:

  1. Main Activity which simply has one CheckBox which upon an onClick starts/stops my service.
  2. Service which runs a method (quick database query) every 60 seconds.

After getting everything working, I realized that my CheckBox was not saving its state. After a bit more searching I figured I should be using CheckBoxPreference rather than CheckBox.

My question(s) before I start researching HOW to do this: Is it possible to have a preference screen setup as the main activity? If so, does anyone know of any examples of this or can anyone provide an outline of what I'll need to look into using?

I'm just looking for some guidance as I continue to research. I'm trying to learn so I like to understand WHY.

I created my MyPreferenceActivity.class and it looks like my preferences are saved and returned correctly. Now, I'm having an issue with this error "This method must return a result of type boolean." This occurs on this line of my code:

public boolean onPreferenceClick(Preference preference)

Sorry I'm not getting the toolbar for formatting.

MyPreferenceActivity.class

package com.example.android.myprogram;

import android.content.Intent;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceClickListener;


public class MyPreferenceActivity extends PreferenceActivity {
    private static final String TAG = "MyPreferenceActivity";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
        PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
        getPreferenceManager().findPreference("checkbox").setOnPreferenceClickListener(new OnPreferenceClickListener()
        {
            Intent myIntent = new Intent(getApplicationContext(), MyService.class);
            @Override
            public boolean onPreferenceClick(Preference preference)
            {
                startService(myIntent);
            }
        });
    }
}
Was it helpful?

Solution

What you are saying is that you want to use a PreferenceActivity as the main Activity, I think that's possible because it inherits from the Activity class.

But

  1. I have newer seen such a construction (maybe because it's a strange approach)
  2. The only thing a PreferenceActivity does is to managa an xml file which is saved in the apps private area, with only one checkbox it's a fast thing to do for your self!

I'm looking forward to your ansatz!

OTHER TIPS

Again, I found my answer after digging around. Basic Java 101 here.. I had to add:

return true;

At least now I understand the concept.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top