I have a preference activity in which I have a PreferenceCheckBox.
My preference activity:
package com.tjs.balr;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class SettingsActivity extends PreferenceActivity{
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource( R.xml.preferences);
}
}
My checkbox:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="Audio">
<CheckBoxPreference
android:id="#+id/checkSound"
android:summary="Turn sounds on or off"
android:defaultValue="true"
android:title="Sounds"
android:key="soundPref"
/>
</PreferenceCategory>
</PreferenceScreen>
In my main activity I try to get the value of my checkbox using:
private void showUserSettings() {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
musicPlaying = sharedPrefs.getBoolean("checkSound", true);
if(musicPlaying){
Toast.makeText(this, "music is turned on", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "music is turned off ", Toast.LENGTH_SHORT).show();
}
}
A LOT of people here on stackoverflow describe musicPlaying = sharedPrefs.getBoolean("checkSound", true); as the way to get the value of the checkbox, but in my case it stays true. Mainly because I say the default value of checkSound is true. Am I forgetting something in order to change the value of my PreferenceCheckBox? To my understanding of an PreferenceActivity all data is saved automatically, is this correct?
In getBoolean(key, defaultValue) , you need to pass the Key not the id.
You get always true because he dont find the CheckBox with checkSound as key so it return the default value (true in your case).
To fix that, just change
musicPlaying = sharedPrefs.getBoolean("checkSound", true);
to
musicPlaying = sharedPrefs.getBoolean("soundPref", true);
Related
I have an issue, i have to set a whole host of settings prior to running my main app. These are done through an on-boarding process, however this is not being reflected in my main settings once in the main app.
During on-boarding i set:
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
int radioId = checkedId;
radioButton = getActivity().findViewById(radioId);
String str = (String) radioButton.getText();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MyApplication.getAppContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(kDirection, str).apply();
editor.commit();
}
});
My Preference:
<PreferenceCategory app:title="Directions">
<ListPreference
app:key="kDirectionSetting"
app:entryValues="#array/directions"
android:entries="#array/directions"
app:useSimpleSummaryProvider="true"
app:title="Direction Preference"
/>
</PreferenceCategory>
This is reflected in my preferences If i open them in device file explorer before i open the preferences screen. Then when the main menu is opened and the preference screen loaded the String is changed to an unset default value from my array, the same every time.
How do i get the reflected changes to show in my settings first time?
I think that if you have the same key for both your ListPreference and the initial Preference value that you stored, then you will get the ListPreference to edit the initial value. However, do this to set the default value to the ListPreference:
#Override
public void onCreate(Bundle savedInstanceState) {
ListPreference kDirectionPref = (ListPreference) findPreference("kDirectionSetting");
kDirectionPref.setDefaultValue(prefs.getString("kDirection"));
So basically, what I'm saying is that you should ensure that you use the same key to put values for your Preference, i.e. in the first piece of code, kDirection should be changed to "kDirectionSetting".
I want my button to show "catch" at the very beginning if there is no key the same as the name of a current pokemon and "release" if there is one and its value is true. I send "false" by default with getBoolean. But for some reason, the first text I see with every new pokemon is "release". What could be wrong?
Edit: I include the entire onCreate method and the button's onClick method along with the layout.
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Catch"
android:onClick="toggleCatch"
android:visibility="visible" />
SharedPreferences catchStorage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pokemon);
requestQueue = Volley.newRequestQueue(getApplicationContext());
url = getIntent().getStringExtra("url");
nameTextView = findViewById(R.id.pokemon_name);
numberTextView = findViewById(R.id.pokemon_number);
type1TextView = findViewById(R.id.pokemon_type1);
type2TextView = findViewById(R.id.pokemon_type2);
pokemonName = getIntent().getStringExtra("name");
catchStorage = getSharedPreferences("catchStorage", Context.MODE_PRIVATE);
Button catchBut = (Button)findViewById(R.id.button);
if(catchStorage.getBoolean(pokemonName, false)){
catchBut.setText("Release");
}
else {
catchBut.setText("Catch");
}
load();
}
public void toggleCatch(View view) {
Button catched = (Button)view;
SharedPreferences.Editor editor = catchStorage.edit();
if(catchStorage.getBoolean(pokemonName, false)){
editor.putBoolean(pokemonName, false);
editor.commit();
catched.setText("Catch");
}
else {
editor.putBoolean(pokemonName, true);
editor.commit();
catched.setText("Release");
}
}
The value of shared preference will be set default value by the system (false in this case) if the variable was never accessed by the user or was never created, if you or the user changed this value, the default value is ignored.
See http://developer.android.com/guide/topics/data/data-storage.html#pref
So either the value is accessed before or it is set some value.
More complete code snippet may help to find the reason.
I've created a question and answer game with different levels, each level consisting a question. I didn't create it with a database. I just used string. When the user answers a question in level one he is taken to level two but when the user returns back to level one, he has to type the answer again even though he's solved it before. Is there anyway in JAVA to keep the answer in the type panel (if the user's solved it) without having to create a database?? Also, while typing in the type panel, the user has to delete the "Type here..." and then answer. Is there anyway that when user taps to type the "Type here..." is automatically erased?
Here's my level one activity.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
android:weightSum="1"
android:textAlignment="center"
android:id="#+id/level1">
<TextView
android:layout_width="300dp"
android:layout_height="200dp"
android:text="What has 88 keys but cannot open a single door?"
android:id="#+id/que1"
android:width="255dp"
android:textSize="30dp"
android:layout_margin="50dp"
android:textStyle="italic"
android:gravity="center" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/type1"
android:layout_gravity="center_horizontal"
android:text="Type here..." />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check answer..."
android:id="#+id/check1"
android:layout_gravity="center_horizontal" />
</LinearLayout>
and here's my Oneactivity.java
package com.golo.user.gaunkhanekatha;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.os.Handler;
public class OneActivity extends Activity {
public SharedPreferences preferences; //ADDED THIS LINE
public Button check;
public EditText typeh;
private Toast toast;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one);
toast = Toast.makeText(OneActivity.this, "", Toast.LENGTH_SHORT);
check = (Button)findViewById(R.id.check1); //R.id.button is the id on your xml
typeh = (EditText)findViewById(R.id.type1); //this is the EditText id
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
//Here you must get the text on your EditText
String Answer = (String) typeh.getText().toString(); //here you have the text typed by the user
//You can make an if statement to check if it's correct or not
if(Answer.equals("Piano") || (Answer.equals("Keyboard")))
{
preferences = PreferenceManager.getDefaultSharedPreferences(v.getContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("Level 1 question 1 ", 1); //Depends of the level he have passed.
editor.apply();
///Correct Toast
toast.setText("Correct");
toast.setGravity(Gravity.TOP | Gravity.LEFT, 500, 300);
toast.show();
Intent i = new Intent(OneActivity.this, TwoActivity.class);
startActivity(i);
finish();
}
else{
//It's not the correct answer
toast.setText("Wrong! Try again...");
toast.show();
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
if(toast!= null) {
toast.cancel();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_aboutus, 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);
}
}
Also, the toast is displayed where there's keyboard. Is there anyway to move the toast screen to somewhere on the screen where it is clearly visible?
I'll give to you two methods to do it :
Create a LevelEarned class as follows :
public class LevelEarned {
public static int level = 0;
}
Everytime you get an Intent (because user has answered the question correctly) just type :
LevelEarned.level = 1; // 1 depends with the level you have answered correctly
And the best method that it's that I'd use to this it's called SharedPreferences
You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).
The first thing you have to do is store this data on SharedPreferences and you do it with an Editor as follows :
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(v.getContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("player_level",1); //Depends of the level he have passed.
editor.apply();
NOTE
I guess you will do it immediately when the user accepts the question so, you'll do it on a Button click so you'll have to pass as a context v.getContext() if you are not on a ButtonClick and you are on your onCreate() just call this to refer your context.
To get the stored data (level) you'll need to do this :
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
int level = preferences.getInt("player_level", 0);
Let's explain to you a little bit.
The first parameter it's the key to find the SharedPreference so it won't change and the second one is a default value that it's used in case it doesn't find any "player_level" SharedPreferences.
Hope it helps to you to keep going in your code :)
EDIT2
Create SharedPreferences preferences as a global variable as follows :
public SharedPreferences preferences;
Then inside of your onClick() method add those lanes :
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
//Here you must get the text on your EditText
String Answer = (String) typeh.getText().toString(); //here you have the text typed by the user
//You can make an if statement to check if it's correct or not
if(Answer.equals("4") || (Answer.equals("four")))
{
preferences = PreferenceManager.getDefaultSharedPreferences(v.getContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("player_level",1); //Depends of the level he have passed.
editor.apply();
//Create a Toast because it's correct
Toast.makeText(OneActivity.this, "Correct!",
Toast.LENGTH_LONG).show();
}
else{
//It's not the correct answer
Toast.makeText(OneActivity.this, "Wrong! Try Again",
Toast.LENGTH_LONG).show();
}
}
});
And where you want to know the level you only will have to do :
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
int level = preferences.getInt("player_level", 0); //level is the current level of the player.
EDIT 3
Create a class as follows :
public static class LevelPlayer(){
public int static getLevelPlayer(){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
int level = preferences.getInt("player_level", 0); //level is the current level of the playe
return level;
}
}
And every time you want to ask the level of the player you do :
int Level = LevelPlayer.getLevelPlayer(); //that's the level
So after every question you can ask the level and put the next question.
EDIT4
I've made some changes, delete your lvl class and put this code :
public class lvl{
public Context mcontext;
public lvl(Context context){
this.mcontext = context;
}
public int getLevelPlayer(){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mcontext);
int level = preferences.getInt("player_level", 0); //level is the current level of the playe
return level;
}
Then on your MainActivity(or wherever you have to know what's the level of the player) you have to put this :
public levelplayer mlevelplayer;
Then inside on your onCreate() add this :
mlevelplayer = new levelplayer(this);
int level = mlevelplayer.getLevelPlayer();
You can use SharedPreferences
To Write to shared preference
SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
to read
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
it is simple. Just create a file to store information. You can do it in two ways.
one is to save a simple xml or json, the second one is to create a model of your answer and serialize a collection of them and save them in file.
Remember that you should do it in some kind of structure way: json, xml, serialized class. it is much simpler to work in future with that
You have a few options that you could try.
One option is as #Stultuske stated, you could try an XML or a TXT file stored on the users device. This (as well as a database) would persist between application sessions.
The other option that you have is you could create a singleton class.
For example, a class called Globals (as below) :
public class Globals {
private static Globals instance;
private String questionOneAnswer;
private Globals(){}
public String getQuestionOne()
{
return this.questionOneAnswer;
}
public void setQuestionOne(String questionOne)
{
this.questionOneAnswer = questionOne;
}
public static synchronized Globals getInstance()
{
if(instance==null)
{
instance=new Globals();
}
return instance;
}
}
This can then be called with Globals g = Globals.getInstance(); . This will only persist through your application instance; however, so if you are wanting to store it throughout app launches you can try the XML/TXT or SharedPreferences as stated by #shaikhmanzoor .
Also it is customary to define variable names with camelCase - ie answers rather than Answers, or typeH rather than typeh. Have a look here for the guidelines for Google Java coding.
For your first question just use SharedPreferences to save and fetch the data like this
SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("level_no_answer", answer_given_by_user);
editor.commit();
and for your second question, you are using android:text="Type here..." in EditText. just replace that line by android:hint="Type here..."
I'm in the middle of making an app and I'm running into a road block.
Basically I have a checkbox... If the checkbox is checked, it is supposed enable the entry of text in an edit text preference, and use that value. But here's where the problem lies... If the box is unchecked it uses the value in the EditTextPreference. If the box is checked, it uses the hard coded value.
Part of my activity:
private void loadURI()
{
PreferenceManager.setDefaultValues(this, R.xml.settings, true);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
if (settings.getBoolean("default_uri", false)){
String defaultURI = getString(R.string.dream_uri);
this.mWebView.loadUrl(defaultURI);
}
else {
String customURI = settings.getString("custom_uri", "");
this.mWebView.loadUrl(customURI);
}
}
Settings.xml:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="Backdrop Settings" >
<CheckBoxPreference
android:title="Use Custom Backdrop URL"
android:id="#id/checkBox1"
android:key="default_uri"
android:defaultValue="true"/>
<EditTextPreference
android:title="Custom Backdrop URL"
android:summary="Tap here to enter custom URL"
android:id="#id/editText1"
android:defaultValue="Enter Custom URL here"
android:key="custom_uri"
android:dependency="default_uri" />
<CheckBoxPreference
android:title="Use a Custom Slideshow Period?"
android:key="slide_duration"
android:defaultValue="false"/>
<ListPreference
android:title="Slideshow Duration"
android:summary="How long should each slide be displayed?"
android:key="list_duration"
android:dependency="slide_duration"/>
</PreferenceCategory>
<PreferenceCategory
android:title="Other">
<Preference
android:title="Test Dream"
android:summary="Tap here to test the dream"
android:key="testDream" />
<Preference
android:title="About"
android:key="AboutApp"
android:summary="About this app" />
</PreferenceCategory>
</PreferenceScreen>
And my Preferences activity:
public class mollySettings extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
Preference button = findPreference("testDream");
button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference arg0) {
final Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.android.systemui", "com.android.systemui.Somnambulator");
startActivity(intent);
return true;
}
});
Preference about = findPreference("AboutApp");
about.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference arg1) {
final Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.death2all110.flogging.molly", "com.death2all110.flogging.molly.About");
startActivity(intent);
return true;
}
});
}
}
Thanks in advance, and please let me know if there is anything else you need
Got it figured out.
I added an exclamation point to the if statement. So the loadURI method is now:
private void loadURI()
{
PreferenceManager.setDefaultValues(this, R.xml.settings, true);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
if (!settings.getBoolean("default_uri", false)){
String defaultURI = getString(R.string.dream_uri);
this.mWebView.loadUrl(defaultURI);
}
else {
String customURI = settings.getString("custom_uri", "");
this.mWebView.loadUrl(customURI);
}
}
Instead of:
private void loadURI()
{
PreferenceManager.setDefaultValues(this, R.xml.settings, true);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
if (settings.getBoolean("default_uri", false)){
String defaultURI = getString(R.string.dream_uri);
this.mWebView.loadUrl(defaultURI);
}
else {
String customURI = settings.getString("custom_uri", "");
this.mWebView.loadUrl(customURI);
}
}
I've currently got a preferences screen, and I've created a custom class that extends DialogPreference and is called from within my Preferences. My preferences data seems store/retrieve from SharedPreferences without an issue, but I'm trying to add 2 more sets of settings from the DialogPreference.
Basically I have two issues that I have not been able to find. Every site I've seen gives me the same standard info to save/restore data and I'm still having problems. Firstly I'm trying to save a username and password to my SharedPreferences (visible in the last block of code) and if possibly I'd like to be able to do it in theonClick().
My preferences XML that calls my DialogPreference:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory>
<com.rone.optusmon.AccDialog
android:key="AccSettings"
android:title="Account Settings"
android:negativeButtonText="Cancel"
android:positiveButtonText="Save" />
</PreferenceCategory>
</PreferenceScreen>
My Custom DialogPreference Class file:
package com.rone.optusmon;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.preference.DialogPreference;
import android.preference.PreferenceManager;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class AccDialog extends DialogPreference implements DialogInterface.OnClickListener {
private TextView mUsername, mPassword;
private EditText mUserbox, mPassbox;
CharSequence mPassboxdata, mUserboxdata;
private CheckBox mShowchar;
private Context mContext;
private int mWhichButtonClicked;
public AccDialog(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
}
#Override
protected View onCreateDialogView() {
// Access default SharedPreferences
#SuppressWarnings("unused")
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext);
#SuppressWarnings("unused")
LinearLayout.LayoutParams params;
LinearLayout layout = new LinearLayout(mContext);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setPadding(10, 10, 10, 10);
layout.setBackgroundColor(0xFF000000);
mUsername = new TextView(mContext);
mUsername.setText("Username:");
mUsername.setTextColor(0xFFFFFFFF);
mUsername.setPadding(0, 8, 0, 3);
mUserbox = new EditText(mContext);
mUserbox.setSingleLine(true);
mUserbox.setSelectAllOnFocus(true);
mPassword = new TextView(mContext);
mPassword.setText("Password:");
mPassword.setTextColor(0xFFFFFFFF);
mPassbox = new EditText(mContext);
mPassbox.setSingleLine(true);
mPassbox.setSelectAllOnFocus(true);
mShowchar = new CheckBox(mContext);
mShowchar.setOnCheckedChangeListener(mShowchar_listener);
mShowchar.setText("Show Characters");
mShowchar.setTextColor(0xFFFFFFFF);
mShowchar.setChecked(false);
if(!mShowchar.isChecked()) {
mPassbox.setTransformationMethod(new PasswordTransformationMethod());
}
layout.addView(mUsername);
layout.addView(mUserbox);
layout.addView(mPassword);
layout.addView(mPassbox);
layout.addView(mShowchar);
return layout;
}
public void onClick(DialogInterface dialog, int which) {
mWhichButtonClicked = which;
// if statement to set save/cancel button roles
if (mWhichButtonClicked == -1) {
Toast.makeText(mContext, "Save was clicked\nUsername: " + mUserbox.getText().toString() +"\nPassword is: " + mPassbox.getText().toString(), Toast.LENGTH_SHORT).show();
// Save user preferences
SharedPreferences settings = getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = settings.edit();
editor.putString("usernamekey", mUserbox.getText().toString());
editor.putString("passwordkey", mPassbox.getText().toString());
editor.commit();
}
else {
Toast.makeText(mContext, "Cancel was clicked", Toast.LENGTH_SHORT).show();
}
}
}
My main activity test code:
public void onResume() {
super.onResume();
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
StringBuilder builder = new StringBuilder();
builder.append("\nThe monitor will refresh every "+ pref.getString("refreshfreq", "30 minutes"));
builder.append("\nThe skin chosen is "+ pref.getString("skinkey", "null"));
builder.append("\nThe style chosen is "+ pref.getString("stylekey", "% used"));
builder.append("\nThe font chosen is "+ pref.getString("fontkey", "Calibri"));
builder.append("\nThe font color is "+ pref.getString("fontcolkey", "White"));
builder.append("\nYour username is "+ pref.getString("usernamekey", "not set yet"));
builder.append("\nYour password is "+ pref.getString("passwordkey", "not set yet"));
Toast.makeText(Optusmon.this, builder.toString(), Toast.LENGTH_LONG).show();
}
In my SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); line, Eclipse says "The method getDefaultSharedPreferences(AccDialog) is undefined for the type AccDialog". I've attempted to change the context to my preferences class, use a blank context and I've also tried naming my SharedPrefs and using getSharedPreferences() as well. I'm just not sure exactly what I'm doing here.
As I'm quite new to Java/Android/coding in general, could you please be as detailed as possible with any help, eg. which of my files I need to write the code in and whereabouts in that file should I write it (i.e. onCreate(), onClick(), etc)
In the onCreate() you returned before execute this line, so Eclipse says it's unreachable.
In your onClick() try:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext);
should be OK
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext);