I'm having some issue with my application... I have a Settings Activity where the user can pick a theme for the app, then I have a button that says "Back" and returns the user to the main Activity. After that the theme get's saved and everything works fine. But my problem is if the user hit's the "Android back button", my theme doesn't get's saved. There is a way to fix it?
Here is my Settings Activity:
public class SettingsActivity extends Activity implements OnClickListener {
public static final String PREF_NAME = "MyPrefsFile";
public static int newTheme;
public final static int THEME_DARK = R.style.DarkTheme;
public final static int THEME_LIGHT = R.style.LightTheme;
public final static int THEME_COLORS = R.style.ColorsTheme;
public final static int THEME_PERF = R.style.Performance;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
SharedPreferences settings = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
newTheme = settings.getInt("themeCustom", 0);
if(newTheme == THEME_DARK) {
setTheme(R.style.DarkTheme);
} else if(newTheme == THEME_LIGHT){
setTheme(R.style.LightTheme);
} else if(newTheme == THEME_COLORS) {
setTheme(R.style.ColorsTheme);
} else {
setTheme(R.style.Performance);
}
setContentView(R.layout.activity_settings);
findViewById(R.id.button2).setOnClickListener(this);
findViewById(R.id.button3).setOnClickListener(this);
findViewById(R.id.button4).setOnClickListener(this);
findViewById(R.id.button5).setOnClickListener(this);
findViewById(R.id.button6).setOnClickListener(this);
}
#Override
public void onClick(View v) {
SharedPreferences settings = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
SharedPreferences.Editor edit;
edit = settings.edit();
Intent intent = getIntent();
Intent main = new Intent(SettingsActivity.this,MainActivity.class);
switch (v.getId()) {
case R.id.button2:
newTheme = THEME_DARK;
edit.clear();
edit.putInt("themeCustom", newTheme);
edit.commit();
finish();
startActivity(intent);
break;
case R.id.button3:
newTheme = THEME_LIGHT;
edit.clear();
edit.putInt("themeCustom", newTheme);
edit.commit();
finish();
startActivity(intent);
break;
case R.id.button5:
newTheme = THEME_COLORS;
edit.clear();
edit.putInt("themeCustom", newTheme);
edit.commit();
finish();
startActivity(intent);
break;
case R.id.button6:
newTheme = THEME_PERF;
edit.clear();
edit.putInt("themeCustom", newTheme);
edit.commit();
finish();
startActivity(intent);
break;
case R.id.button4:
startActivity(main);
break;
default:
break;
}
}
}
Thank you very much!! :)
You can use onBackpressed()
public void OnBackpressed()
{
// do stuff ( same as what you did in your button click)
}
It is called when the activity has detected the user's press of the back key. The default implementation simply finishes the current activity, but you can override this to do whatever you want.
you should override the onBackPressed() method
#Override
public void onBackPressed() {
super.onBackPressed();
// to do
}
#Override
public void onBackPressed() {
//do whatever to save the settings
super.onBackPressed();
}
This way you can do whatever you want on the button + the original intention of it.
You can use the following way
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("themeCustom", newTheme);
editor.commit();
}
Related
So I have a Spinner and a EditText to login. The array of the Spinner owns "Anonymous" and " Owner" (means "Anonymous" is 0 and "Owner" is 1 in the array). When you choose "Anonymous" the password is "0000" and when you choose "Owner" the password is "1234".
But when I choose "Owner", the password "1234" is wrong and the Logcat shows "Anonymous". How can I make "Owner" selected? Maybe getSelectedItemPosition() is wrong?
My Code:
public class PinEnterActivity extends AppCompatActivity {
Button nextButton;
EditText pinEditText;
Spinner pinRoleSpinner = null;
private String TAG = "PinEnterActivity";
private Byte selectedUserRole = 0;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pin_enter);
nextButton = findViewById(R.id.nextActivity)
pinEditText = findViewById(R.id.pinET);
pinRoleSpinner = findViewById(R.id.roleSpinner);
selectedUserRole = (byte) pinRoleSpinner.getSelectedItemPosition();
switch (selectedUserRole) {
case 0:
Log.i(TAG, "Anonymous");
SharedPreferences sharedpreferences = getSharedPreferences("My_Prefs", 0);
final String password = sharedpreferences.getString("pass", "");
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (pinEditText.getText().toString().equals("0000")) {
Intent intent = new Intent(PinEnterActivity.this, NextActivity.class);
startActivity(intent);
} else {
pinEditText.setError("Password incorrect");
Animation shake = AnimationUtils.loadAnimation(PinEnterActivity.this, R.anim.shake);
pinEditText.startAnimation(shake);
return;
}
}
});
break;
case 1:
Log.i(TAG, "Owner");
SharedPreferences preferences = getSharedPreferences("My_Prefs", 0);
final String password2 = preferences.getString("pass", "");
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (pinEditText.getText().toString().equals("1234")) {
Intent intent = new Intent(PinEnterActivity.this, NextActivity.class);
startActivity(intent);
}else{
pinEditText.setError("Password incorrect");
Animation shake = AnimationUtils.loadAnimation(PinEnterActivity.this, R.anim.shake);
pinEditText.startAnimation(shake);
return;
}
}
});
}
}
I finally found out the right answer.
pinRoleSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch(selectedUserRole) {
case 0:
Log.i(TAG, "Anonymous");
// Code
break;
case 1:
Log.i(TAG, "Owner");
// Code
break;
default;
// Code
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Hi I'm trying to detect whether my app has been opened for the first time. If it has, I need to run an activity and once it's opened for the second time it should not show it again.
This is my code:
fragment:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Intent intent = new Intent(getActivity(), TutorialFeaturedActivity.class);
//startActivity(intent);
SharedPreferences settings = this.getActivity().getSharedPreferences(PREFS_NAME, 0); // Get preferences file (0 = no option flags set)
boolean firstRun = settings.getBoolean("firstRun", true); // Is it first run? If not specified, use "true"
if(firstRun) {
Log.w("onCreate: ","first time" );
Intent intent = new Intent(getActivity(), TutorialFeaturedActivity.class);
startActivity(intent);
SharedPreferences.Editor editor = settings.edit(); // Open the editor for our settings
editor.putBoolean("firstRun", false); // It is no longer the first run
editor.apply(); // Save all changed settings
} else {
Log.w("onCreate: ","second time");
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}
getSpecials();
}
But all it does is start the activity and when I start it again it freezes in a white screen but checking the logs it shows like the else statement is constantly running over and over. I'm fairly new to Android so some help or advice would be greatly appreciated
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
SharedPreferences pref = YourActivityName.this.getSharedPreferences(PREFS_NAME,0);
SharedPreferences.Editor editor= pref.edit();
boolean firstRun = pref.getBoolean("firstRun", true);
if(firstRun)
{
Log.i("onCreate: ","first time" );
editor.putBoolean("firstRun",false);
editor.commit();
Intent intent = new Intent(getActivity(), TutorialFeaturedActivity.class);
startActivity(intent);
}
else
{
Log.i("onCreate: ","second time");
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}
// getSpecials();
}
It looks like your activity is looping because within your else statement, you tell it to restart the activity which lands again in the else statement and so on and so on.
Try using editor.commit if editor.apply not working
editor.putBoolean("firstRun", false);
editor.apply(); // Save all changed settings
editor.commit(); // Save all changed settings
In else case your starting "MainActivity.class".
Why your loading MainActivity from the oncreate of MainActivity ?
it will make a loop.
Remove the start activity from else case.
Try this approach:
public class MainActivity extends Activity {
SharedPreferences prefs = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
}
#Override
protected void onResume() {
super.onResume();
if (prefs.getBoolean("firstRun", true)) {
Intent intent = new Intent(MainActivity.this, TutorialFeaturedActivity.class);
startActivity(intent);
prefs.edit().putBoolean("firstRun", false).commit();
}
else
{
//do nothing
}
getSpecials();
}
}
Please Try this my friend
public class SessionManager {
private static String TAG = SessionManager.class.getSimpleName();
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "ManageRun";
private static final String KEY_IS_RUN = "isRun";
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setLatest(boolean isRun) {
editor.putBoolean(KEY_IS_RUN, isRun);
// commit changes
editor.commit();
Log.d(TAG, "Manage Version session modified!");
}
public boolean isLatest() {
return pref.getBoolean(KEY_IS_RUN, true);
}
}
**In first Activity Check **
private SessionManager session;
session = new SessionManager(getApplicationContext());
if (session.isLatest()) {
session.setLatest(false);
Log.w("onCreate: ","first time" );
Intent intent = new Intent(getActivity(), TutorialFeaturedActivity.class);
startActivity(intent);
}
else
{
Log.w("onCreate: ","second time");
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}
private boolean isFirstTime() {
if (firstTime == null) {
SharedPreferences mPreferences = this.getSharedPreferences("first_time", Context.MODE_PRIVATE);
firstTime = mPreferences.getBoolean("firstTime", true);
if (firstTime) {
SharedPreferences.Editor editor = mPreferences.edit();
editor.putBoolean("firstTime", false);
editor.commit();
}
}
return firstTime;
}
if (isFirstTime()) {
Intent i = new Intent(SplashActivity.this, Intro_slider.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
} else {
final UserFunctions uf = new UserFunctions();
if (uf.isUserLoggedIn(SplashActivity.this)) {
Intent i = new Intent(SplashActivity.this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
} else {
Intent i = new Intent(SplashActivity.this, Social_Login_Activity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
}
Try this code.
I want to launch splash activity only once using SharedPreference, how it could be happen. any help will be highly appreciated. Thanks
Thread thread;
MediaPlayer audio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
audio = MediaPlayer.create(MainActivity.this, R.raw.iphone);
audio.start();
if (first_run == true){
thread = new Thread(){
#Override
public void run() {
try {
sleep(4000);
Intent intent = new Intent(MainActivity.this, SplashTwo.class);
startActivity(intent);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
finish();
audio.release();
}
}
};
thread.start();
}
}
try this:
Declare
public static final String MyPREFERENCES = "MyPrefs";
public static final String ID = "idKey";
SharedPreferences sharedPreferences;
Now in your onCreate():
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
audio = MediaPlayer.create(MainActivity.this, R.raw.iphone);
audio.start();
String first = (sharedPreferences.getString("First", ""));
if (!first.equals("true")) {
thread = new Thread(){
#Override
public void run() {
try {
sleep(4000);
Intent intent = new Intent(MainActivity.this, SplashTwo.class);
startActivity(intent);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("First", "true");
editor.commit();
finish();
audio.release();
}
}
};
thread.start();
}
}
Instead of sharedprefrence ,i would like to suggest you to use static boolean value like - isFirstTime and set it true by default and on second activity (next to splash) set it to false. Whenever you kill app static value will become dead.Check in onCreate of Splash -
if(!isFirstTime){
goToNextActivity();
}else{
//continue splash code
}
If you want to use shared preference then use same Logic ,take a boolean value and save it in shared pref -
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putBoolean("isFirstTime", true);
editor.commit();
and in next activity simply set it to false or clear value. by calling editor.clear(); and put a check in splash if shared pref has some value or have isFirstTime and do next code accordingly.
I am trying to have SharedPreferences once and control it to different methods rather than having different SharedPreferences in different methods. I have SharedPreferences in the onCreate, LoadPreferences, SavePreferences and ClearTextViews methods. I want to make it so that I have preferences saved to the TextViews from entered text in the EditText and then be able to clear them all with a button. Please help me if you can. Here is the relevant code:
public class notesActivity extends Activity implements OnClickListener
{
Button saveNote;
Button clearText;
EditText note;
TextView textSavedNote1, textSavedNote2, textSavedNote3, textSavedNote4, textSavedNote5, textSavedNote6;
SharedPreferences spNote;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes);
saveNote = (Button)this.findViewById(R.id.saveNotes);
saveNote.setOnClickListener(this);
clearText = (Button)this.findViewById(R.id.clearAllText);
clearText.setOnClickListener(this);
textSavedNote1 = (TextView)findViewById(R.id.stringSavedNote1);
textSavedNote2 = (TextView)findViewById(R.id.stringSavedNote2);
textSavedNote3 = (TextView)findViewById(R.id.stringSavedNote3);
textSavedNote4 = (TextView)findViewById(R.id.stringSavedNote4);
textSavedNote5 = (TextView)findViewById(R.id.stringSavedNote5);
textSavedNote6 = (TextView)findViewById(R.id.stringSavedNote6);
note = (EditText)this.findViewById(R.id.notes);
spNote = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = spNote.edit();
edit.putString("note"+saveNote,note.getText().toString());
edit.commit();
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Goes back to the home screen
case R.id.item1: Intent i = new Intent(notesActivity.this, UserSettingActivity.class);
startActivity(i);
case R.id.item2:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
// Refreshes the page.
case R.id.item3:
finish();
startActivity(getIntent());
default:
return super.onOptionsItemSelected(item);
}
}
public void onClick (View v){
if(v==saveNote){
SavePreferences("NOTE1", note.getText().toString());
LoadPreferences();
note.setText("");
if(textSavedNote1.getText().toString().length()>0){
SavePreferences("NOTE2", note.getText().toString());
LoadPreferences();
note.setText("");
}
else{
}
}
else if(v==clearText){
ClearTextViews();
}
}
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedNote1 = sharedPreferences.getString("NOTE1", "");
String strSavedNote2 = sharedPreferences.getString("NOTE2", "");
String strSavedNote3 = sharedPreferences.getString("NOTE3", "");
String strSavedNote4 = sharedPreferences.getString("NOTE4", "");
String strSavedNote5 = sharedPreferences.getString("NOTE5", "");
String strSavedNote6 = sharedPreferences.getString("NOTE6", "");
textSavedNote1.setText(strSavedNote1);
textSavedNote2.setText(strSavedNote2);
textSavedNote3.setText(strSavedNote3);
textSavedNote4.setText(strSavedNote4);
textSavedNote5.setText(strSavedNote5);
textSavedNote6.setText(strSavedNote6);
}
private void ClearTextViews(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
}
}
There are some links that can be helpfull
How to use SharedPreferences in Android to store, fetch and edit values
http://developer.android.com/reference/android/content/SharedPreferences.html
Examples
How to use SharedPreferences
http://android-er.blogspot.com.br/2011/01/example-of-using-sharedpreferencesedito.html
Try the code below.
/*I have added one more button, on click on that button i have set call clearText function and set all text empty, each time before clicking on save button you click first clear button then next value will be inserted in next textview.*/
public class SharedPreferenceJustOneSetOfPreferencesActivity extends Activity implements OnClickListener{
private Button saveNote,clearText,ClearAll;
static TextView textSavedNote1, textSavedNote2, textSavedNote3, textSavedNote4, textSavedNote5, textSavedNote6;
private EditText note;
private SharedPreferences spNote;
private static final String TAG = SharedPreferenceJustOneSetOfPreferencesActivity.class.getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initView();
saveInPreference();
}
private void initView() {
textSavedNote1 = (TextView)findViewById(R.id.textSavedNote1);
textSavedNote2 = (TextView)findViewById(R.id.textSavedNote2);
textSavedNote3 = (TextView)findViewById(R.id.textSavedNote3);
textSavedNote4 = (TextView)findViewById(R.id.textSavedNote4);
textSavedNote5 = (TextView)findViewById(R.id.textSavedNote5);
textSavedNote6 = (TextView)findViewById(R.id.textSavedNote6);
note = (EditText)findViewById(R.id.note);
saveNote = (Button)findViewById(R.id.saveNote);
clearText = (Button)findViewById(R.id.clearText);
ClearAll = (Button)findViewById(R.id.ClearAll);
saveNote.setOnClickListener(this);
clearText.setOnClickListener(this);
ClearAll.setOnClickListener(this);
}
private void saveInPreference() {
spNote = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = spNote.edit();
edit.putString("note"+saveNote,note.getText().toString());
edit.commit();
}
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.layout.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case R.id.item1: Intent i = new Intent(SharedPreferenceJustOneSetOfPreferencesActivity.this, UserSettingActivity.class);
startActivity(i);
case R.id.item2:
Intent intent = new Intent(SharedPreferenceJustOneSetOfPreferencesActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
case R.id.item3:
finish();
startActivity(getIntent());
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View view) {
if (view == saveNote) {
String textvedNote1 =textSavedNote1.getText().toString();
String textvedNote2= textSavedNote2.getText().toString();
String textvedNote3 =textSavedNote3.getText().toString();
String textvedNote4= textSavedNote4.getText().toString();
String textvedNote5 =textSavedNote5.getText().toString();
String textvedNote6= textSavedNote6.getText().toString();
if (textvedNote1.equals("")) {
SavePreferences("NOTE1", note.getText().toString());
Log.e(TAG,"textvedNote1: Inside "+textvedNote1.length());
LoadPreferences();
note.setText("");
}else if (textvedNote2.equals("")&& !textvedNote1.equals("")) {
SavePreferences("NOTE2", note.getText().toString());
Log.e(TAG,"textvedNote2: Inside "+textvedNote1.length());
LoadPreferences();
note.setText("");
} else if (textvedNote3.equals("")&& !textvedNote2.equals("")) {
Log.e(TAG,"textvedNote3: Inside "+textvedNote2.length());
SavePreferences("NOTE3", note.getText().toString());
LoadPreferences();
note.setText("");
} else if (textvedNote4.equals("")&& !textvedNote3.equals("")) {
Log.e(TAG,"textvedNote4: Inside "+textvedNote3.length());
SavePreferences("NOTE4", note.getText().toString());
LoadPreferences();
note.setText("");
} else if (textvedNote5.equals("")&& !textvedNote4.equals("")) {
Log.e(TAG,"textvedNote5: Inside "+textvedNote4.length());
SavePreferences("NOTE5", note.getText().toString());
LoadPreferences();
note.setText("");
} else if (textvedNote6.equals("")&& !textvedNote5.equals("")) {
SavePreferences("NOTE6", note.getText().toString());
Log.e(TAG,"textvedNote6: Inside "+textvedNote5.length());
LoadPreferences();
note.setText("");
}
} else if (view == clearText) {
ClearTextViews();
}else if (view == ClearAll){
ClearTextViews();
textSavedNote1.setText("");
textSavedNote2.setText("");
textSavedNote3.setText("");
textSavedNote4.setText("");
textSavedNote5.setText("");
textSavedNote6.setText("");
}
}
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedNote1 = sharedPreferences.getString("NOTE1", "");
String strSavedNote2 = sharedPreferences.getString("NOTE2", "");
String strSavedNote3 = sharedPreferences.getString("NOTE3", "");
String strSavedNote4 = sharedPreferences.getString("NOTE4", "");
String strSavedNote5 = sharedPreferences.getString("NOTE5", "");
String strSavedNote6 = sharedPreferences.getString("NOTE6", "");
if (!strSavedNote1.equals("")) {
Log.e(TAG,"LoadPreferences1: "+strSavedNote1);
textSavedNote1.setText(strSavedNote1);
} else if (!strSavedNote2.equals("")) {
Log.e(TAG,"LoadPreferences2: "+strSavedNote2);
textSavedNote2.setText(strSavedNote2);
} else if (!strSavedNote3.equals("")) {
Log.e(TAG,"LoadPreferences3: "+strSavedNote3);
textSavedNote3.setText(strSavedNote3);
} else if (!strSavedNote4.equals("")) {
textSavedNote4.setText(strSavedNote4);
} else if (!strSavedNote5.equals("")) {
textSavedNote5.setText(strSavedNote5);
} else if (!strSavedNote6.equals("")) {
textSavedNote6.setText(strSavedNote6);
}
}
private void ClearTextViews(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
}
}
I have it set up so when you click one of the words it will add 10 points and the other will add 5 points but I want it to be typed out in the same textview, however im not sure how to do it because how I have it right now it wants me to change the settings and editor to "settings1" and "editor1" but if I do that it will no longer type the amount of points out in the "test" TextView. I hope I expaned it good enough, thanks for helping
heres my code
public class page1 extends Activity implements OnClickListener
{
TextView Q1A1;
TextView Q1A2;
TextView test;
public static final String PREFS_NAME = "MyPrefsFile";
public static final int testScore = 0;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
Q1A1 = (TextView) findViewById(R.id.Q1A1);
Q1A2 = (TextView) findViewById(R.id.Q1A2);
Q1A1.setOnClickListener(this);
Q1A2.setOnClickListener(this);
test = (TextView) findViewById(R.id.test);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
test.setText(""+settings.getInt("YourScore", 0));
}
public void onClick(View v)
{
switch(v.getId())
{
case R.id.Q1A1:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("YourScore", (testScore + 10));
editor.commit();
//Intent FinalScore = new Intent(this, FinalScore.class);
//startActivity(FinalScore);
break;
case R.id.Q1A2:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("YourScore", (testScore + 5));
editor.commit();
break;
}
}
}
Case statements do not create a new scope, so you are declaring the variables settings and editor twice.
Your code in the two case statements are the exact same except for the number of points being added. Why not create a method that has all the shared code.
private void addPoints(int points) {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("YourScore", (testScore + points));
editor.commit();
}
public void onClick(View v)
{
switch(v.getId())
{
case R.id.Q1A1:
addPoints(10);
break;
case R.id.Q1A2:
addPoints(5);
break;
}
}