Trying to compare scores - android

I am trying to compare 2 scores that I have made oldScore and best_score(both in Main_Screen). I think the problem is that the ints are not saving properly. There are no errors but if the best_Score is lower than the old_score it still changes it in the textview even though the best_score should be higher than the old_score. Hopefully I can learn from this :)
Main_Screen
public class Main_Screen extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
getSupportActionBar().hide();
//SETS CUSTOM FONT
TextView main_screen_titleone = (TextView)findViewById(R.id.main_screen_titleone);
TextView main_screen_titletwo = (TextView)findViewById(R.id.main_screen_titletwo);
TextView best_score_tv = (TextView)findViewById(R.id.best_score_tv);
TextView best_score_number_tv = (TextView)findViewById(R.id.best_score_number_tv);
Typeface myCustomFont = Typeface.createFromAsset(getAssets(), "fonts/LemonMilk.otf");
main_screen_titleone.setTypeface(myCustomFont);
main_screen_titletwo.setTypeface(myCustomFont);
best_score_tv.setTypeface(myCustomFont);
best_score_number_tv.setTypeface(myCustomFont);
//******************;
int best_score = retrieveInt("BEST_SCORE");
int oldScore = Integer.valueOf(best_score_number_tv.getText().toString());
if (best_score > oldScore){
best_score_number_tv.setText(best_score + "");
}
}
public void startTheGame(View view){
Intent intent = new Intent(this, press_screen.class);
startActivity(intent);
}
public int retrieveInt(String key){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
return sp.getInt(key, 0);
}
Press_Screen
public class press_screen extends ActionBarActivity {
private int time_left;
private int amountOfTapsNumber;
private int bestScore;
TextView amountOfTaps;
TextView timeLeftNumber;
TextView time_left_tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_press_screen);
getSupportActionBar().hide();
amountOfTaps = (TextView)findViewById(R.id.amount_of_taps);
timeLeftNumber = (TextView)findViewById(R.id.time_left_number_tv);
time_left_tv = (TextView)findViewById(R.id.time_left_tv);
Typeface myCustomFont = Typeface.createFromAsset(getAssets(), "fonts/LemonMilk.otf");
amountOfTaps.setTypeface(myCustomFont);
timeLeftNumber.setTypeface(myCustomFont);
time_left_tv.setTypeface(myCustomFont);
timer.start();
}
//Create Timer
CountDownTimer timer = new CountDownTimer(21000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
timeLeftNumber = (TextView) findViewById(R.id.time_left_number_tv);
time_left = Integer.valueOf(timeLeftNumber.getText().toString()) - 1;
timeLeftNumber.setText(time_left + "");
}
#Override
public void onFinish() {
if(amountOfTapsNumber > bestScore){
bestScore = amountOfTapsNumber;
saveInfo("BEST_SCORE", bestScore);
}
TextView best_score_number_tv = (TextView)findViewById(R.id.best_score_number_tv);
Intent goBackToMainActivity = new Intent(press_screen.this, Main_Screen.class);
startActivity(goBackToMainActivity);
}
};
#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_press_screen, 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);
}
public void triggerTapOnMainButton(View view) {
amountOfTaps = (TextView) findViewById(R.id.amount_of_taps);
amountOfTapsNumber = Integer.valueOf(amountOfTaps.getText().toString()) + 1;
amountOfTaps.setText(amountOfTapsNumber + "");
}
public void saveInfo(String key, int bestScore){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = sp.edit();
edit.putInt("BEST_SCORE", bestScore);
edit.commit();
}
}

When your timer finishes, you send your tapsNumber on the Intent to MainActivity, like this:
Intent goBackToMainActivity = new Intent(press_screen.this, Main_Screen.class);
Bundle bundle = new Bundle();
bundle.putInt("lastScore", amountOfTapsNumber);
goBackToMainActivity.putExtras(bundle);
startActivity(goBackToMainActivity);
Then, in your MainActivity onCreate(), check if your Intent has the oldScore. If it does, compare it to the best_score.
int lastScore = 0;
if(getIntent() !=null && getIntent().getIntExtra("lastScore",0)>0)
lastScore = getIntent().getIntExtra("lastScore",0);
//comparing the lastScore with the bestScore
if (lastScore > best_Score){
best_score_number_tv.setText(lastScore + "");
}
else{
best_score_number_tv.setText(best_Score + "");
}
This way your bestScore will be updated if your lastScore is higher than your old best_score.

Related

How to Implemanting putExtras SQLite in action menu toolbar Android

I have read many tutorial about CRUD SQLite, but most of them use Cursor to get values data and Button to call EditScreen. Any one lead me how to implementing i.putExtras in my Edit Menu Toolbar, please? I want to show again my data in EditText Form.
public class DetailStaffActivity extends AppCompatActivity {
private DBHandler dbHandler;
private TextView txt_resultnomor, txt_resultnama, txt_resulttempatlahir, txt_resulttanggallahir;
private List<Staff> staffList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.staff_details);
dbHandler = new DBHandler(this);
//ambil data
Intent i=getIntent();
final String nomor=i.getExtras().getString("nomor");
final String nama=i.getExtras().getString("nama");
final String tempatlahir = i.getExtras().getString("tempat_lahir");
final String tanggallahir=i.getExtras().getString("tanggal_lahir");
//inisialisasi dulu
txt_resultnomor = (TextView) findViewById(R.id.txt_resultnomor);
txt_resultnama = (TextView) findViewById(R.id.txt_resultnama);
txt_resulttempatlahir = (TextView) findViewById(R.id.txt_resulttempatlahir);
txt_resulttanggallahir = (TextView) findViewById(R.id.txt_resulttanggallahir);
//set inisial dengan data yang telah diambil di dengan intent
txt_resultnomor.setText(nomor);
txt_resultnama.setText(nama);
txt_resulttempatlahir.setText(tempatlahir);
txt_resulttanggallahir.setText(tanggallahir);
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_detail, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_edit) {
public void onItemClick(View view, int position) { //here, error when set position in this menu//
// TODO Handle item click
Intent in = new Intent(this, UpdateStaffActivity.class);
Staff staff = staffList.get(position);
String getNama = staffList.get(position).getNama();
in.putExtra("nama", getNama);
startActivity(in);
return true;
}
if (id == R.id.action_delete) {
return true;
}
if (id == R.id.action_settings) {
// Intent i = new Intent(this, About.class);
//startActivity(i);
}
return super.onOptionsItemSelected(item);
}
}
Please, how implementing putExtras in
if (id == R.id.action_edit) { }
I got error when set position in this menu. Thanks.
Just remove this line
public void onItemClick(View view, int position) { //here, error when set position in this menu//
// TODO Handle item click
Intent in = new Intent(this, UpdateStaffActivity.class);
Staff staff = staffList.get(position);
String getNama = staffList.get(position).getNama();
And write like this.
if (id == R.id.action_edit) {
Intent in = new Intent(this, UpdateMuriddActivity.class);
in.putExtra("nomor", txt_resultnomor.getText().toString());
in.putExtra("nama", txt_resultnama.getText().toString());
in.putExtra("tempat_lahir", txt_resulttempatlahir.getText().toString());
startActivity(in);
Hope its help.

Android: unable to read from sharedpreferences

So i have a slight problem. I have a feeling its something simple that i must be overlooking. In my second fragment im writing to sharedpreferences a certain number of keys and applying() afterwords. After i have finished writing my data to the sharedpreferences, i replace the current fragment(fragment#2), with the home fragment(fragment#1). Upon loading this fragment i call readPreferences(), which should read the data stored ealier and write the data to the various textviews i have on the home fragment. This does not happen. Im unsure at this time if its due to a write error or a read error. your help is as always, appreciated. Thanks.
Second Fragment
package lucaclock.moticlock;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class secondFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private TimePicker timePicker;
private int hour = 0;
private int min = 0;
private String mParam1;
private String mParam2;
public SharedPreferences sharedPreferences;
public SharedPreferences.Editor prefEditor;
public static final String alarmPreferences = "alarmPreferences";
public static final String alarmTimeKey = "alarmTimeKey";
public static final String alarmNameKey = "alarmNameKey";
public static final String alarmOccuranceKey = "alarmOccuranceKey";
public static final String alarmVolumeKey = "alarmVolumeKey";
public static final String alarmSnoozeKey = "alarmSnoozeKey";
public static final String alarmVisibleKey = "alarmVisibleKey";
public int snoozeTime;
public secondFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static secondFragment newInstance(String param1, String param2) {
secondFragment fragment = new secondFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_second, container, false);
sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
final Button btnOK = (Button) view.findViewById(R.id.btnOK);
final TimePicker tp = (TimePicker) view.findViewById(R.id.timePicker);
//Stage 1 Components
final EditText edAlarmName = (EditText) view.findViewById(R.id.edAlarmName);
edAlarmName.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View view, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
edAlarmName.setText("");
}
return false;
}
});
final EditText edAlarmTime = (EditText) view.findViewById(R.id.edTime);
final EditText edOccurance = (EditText) view.findViewById(R.id.edOccurance);
edOccurance.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
dialogOccurance(view);
return true;
}
return false;
}
});
final SeekBar seekVolume = (SeekBar) view.findViewById(R.id.seekVolume);
seekVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
{
TextView tv = (TextView) view.findViewById(R.id.txtVolume);
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
tv.setText("How Loud?");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
// TODO Auto-generated method stub
tv.setText("Volume: " + Integer.toString(progress));
//Toast.makeText(getApplicationContext(), String.valueOf(progress), Toast.LENGTH_LONG).show();
}
});
final RadioButton rad5min = (RadioButton) view.findViewById(R.id.radSnooze5min);
final RadioButton rad10min = (RadioButton) view.findViewById(R.id.radSnooze10min);
rad5min.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
if(rad5min.isChecked() == true)
{
rad10min.setChecked(false);
snoozeTime = 5;
}
}
});
rad10min.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
if(rad10min.isChecked() == true)
{
rad5min.setChecked(false);
snoozeTime = 10;
}
}
});
final EditText edCustomSnooze = (EditText) view.findViewById(R.id.edSnoozeTime);
edCustomSnooze.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View view, MotionEvent motion)
{
edCustomSnooze.setText("");
if(motion.getAction() == MotionEvent.ACTION_DOWN)
{
rad5min.setChecked(false);
rad10min.setChecked(false);
snoozeTime = 0;
}
return false;
}
});
Button btnSave = (Button) view.findViewById(R.id.btnSaveAlarm);
TextView txtOccur = (TextView) view.findViewById(R.id.txtOccur);
final TextView txtVolume = (TextView) view.findViewById(R.id.txtVolume);
TextView txtSnooze = (TextView) view.findViewById(R.id.txtSnooze);
final Button btnCancel = (Button) view.findViewById(R.id.btnCancel);
btnOK.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
String minString = null;
tp.setIs24HourView(false);
hour = tp.getCurrentHour();
min = tp.getCurrentMinute();
if(min < 10)
{
minString = new StringBuilder().append(Integer.toString(0)).append(min).toString();
}
else
minString = new StringBuilder().append(Integer.toString(min)).toString();
//tv.setText(formatTime(hour, minString));
//storeSetAlarmTime(formatTime(hour, minString));
setVisibleStage(0, view);
setVisibleStage(1, view);
edAlarmTime.setText(formatTime(hour, minString));
//HomeFragment hFrag = new HomeFragment();
//replaceFragment(hFrag);
}
});
btnCancel.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
HomeFragment hFrag = new HomeFragment();
replaceFragment(hFrag);
}
});
btnSave.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
edAlarmName.clearFocus();
edAlarmTime.clearFocus();
edOccurance.clearFocus();
edCustomSnooze.clearFocus();
//INPUT VALIDATION
//ALL INPUT IS OK. NO NULL VALUES ANYWHERE. PROCEED...
if(validateInput(edAlarmTime, edAlarmName, edOccurance, seekVolume, rad5min, rad10min, edCustomSnooze))
{
saveData(view, edAlarmName.getText().toString(), edAlarmTime.getText().toString(), edOccurance.getText().toString(), seekVolume.getProgress(), snoozeTime, sharedPreferences);
//dialogBuilder("Alarm Saved", "Your alarm has been saved");
}
else
dialogBuilder("Validation Error", "Fix your input and try again");
}
});
edAlarmTime.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View view, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
}
return false;
}
});
return view;
}
public void dialogBuilder(String title, String message)
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
public void dialogOccurance(final View view)
{
CharSequence colors[] = new CharSequence[] {"Once", "Daily", "Weekly"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("How often will this alarm repeat?");
builder.setItems(colors, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
TextView tv = (TextView) view.findViewById(R.id.edOccurance);
if(which == 0)
{
tv.setText("ONCE");
}
else if(which == 1)
tv.setText("DAILY");
else if(which == 2)
tv.setText("WEEKLY");
}
});
builder.show();
}
public void saveData(View view, String alarmName, String alarmTime, String occurance, int volume, int snoozeTime, SharedPreferences sharedPreferences)
{
prefEditor = sharedPreferences.edit();
prefEditor.putString(alarmTimeKey, alarmTime);
prefEditor.putString(alarmNameKey, alarmName);
prefEditor.putString(alarmOccuranceKey, occurance);
prefEditor.putInt(alarmVolumeKey, volume);
prefEditor.putInt(alarmSnoozeKey, snoozeTime);
prefEditor.putBoolean(alarmVisibleKey, true);
prefEditor.commit();
if(!sharedPreferences.getBoolean(alarmVisibleKey, true))
{
dialogBuilder("ERROR", "We tried writing the data, however we cant verify it exists");
}
else
{
dialogBuilder("Write Successfull", "true");
}
Toast.makeText(getActivity().getApplicationContext(), "Alarm Added", Toast.LENGTH_LONG).show();
HomeFragment hFrag = new HomeFragment();
replaceFragment(hFrag);
}
public void setVisibleStage(int stage, View view)
{
//Stage 0 Components
TimePicker tp = (TimePicker) view.findViewById(R.id.timePicker);
Button btnOK = (Button) view.findViewById(R.id.btnOK);
Button btnCancel = (Button) view.findViewById(R.id.btnCancel);
//Stage 1 Components
EditText edAlarmName = (EditText) view.findViewById(R.id.edAlarmName);
EditText edAlarmTime = (EditText) view.findViewById(R.id.edTime);
EditText edOccurance = (EditText) view.findViewById(R.id.edOccurance);
SeekBar seekVolume = (SeekBar) view.findViewById(R.id.seekVolume);
RadioButton rad5min = (RadioButton) view.findViewById(R.id.radSnooze5min);
RadioButton rad10min = (RadioButton) view.findViewById(R.id.radSnooze10min);
EditText edCustomSnooze = (EditText) view.findViewById(R.id.edSnoozeTime);
Button btnSave = (Button) view.findViewById(R.id.btnSaveAlarm);
TextView txtOccur = (TextView) view.findViewById(R.id.txtOccur);
TextView txtVolume = (TextView) view.findViewById(R.id.txtVolume);
TextView txtSnooze = (TextView) view.findViewById(R.id.txtSnooze);
if(stage == 0)
{
//STAGE 0 = ANALOG CLOCK DISPLAY ONLY
tp.setVisibility(view.INVISIBLE);
btnOK.setVisibility(view.INVISIBLE);
btnCancel.setVisibility(view.INVISIBLE);
}
else if(stage == 1)
{
//STAGE 1 = EVERYTHING ELSE VISIBLE
edAlarmName.setVisibility(view.VISIBLE);
edAlarmTime.setVisibility(view.VISIBLE);
txtOccur.setVisibility(view.VISIBLE);
edOccurance.setVisibility(view.VISIBLE);
txtVolume.setVisibility(view.VISIBLE);
seekVolume.setVisibility(view.VISIBLE);
txtSnooze.setVisibility(view.VISIBLE);
rad5min.setVisibility(view.VISIBLE);
rad10min.setVisibility(view.VISIBLE);
edCustomSnooze.setVisibility(view.VISIBLE);
btnSave.setVisibility(view.VISIBLE);
}
}
public void replaceFragment(Fragment fragment)
{
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, fragment);
//fragmentTransaction.addToBackStack(fragment.toString());
fragmentTransaction.commit();
}
public boolean validateInput(EditText edAlarmTime, EditText edAlarmName, EditText edOccurance, SeekBar seekVolume, RadioButton rad5min, RadioButton rad10min, EditText customSnooze)
{
String alarmTimeOK = edAlarmTime.getText().toString();
String alarmNameOK = edAlarmName.getText().toString();
String OccuranceOK = edOccurance.getText().toString();
int volumeOK = seekVolume.getProgress();
boolean FiveMinChecked = rad5min.isChecked();
boolean TenMinChecked = rad10min.isChecked();
String customSnoozeOK = customSnooze.getText().toString();
if(alarmTimeOK.matches("") || !alarmTimeOK.contains(":"))
return false;
else if(alarmNameOK.matches("") || alarmNameOK.contains("Alarm Name"))
return false;
else if(OccuranceOK.matches("") || OccuranceOK.contains("Choose Occurance"))
return false;
else if(volumeOK == 0)
return false;
else if(FiveMinChecked && customSnoozeOK.matches("Enter your own"))
return true;
else if(TenMinChecked && customSnoozeOK.matches("Enter your own"))
return true;
else if(FiveMinChecked == false && customSnoozeOK.matches("Enter your own"))
return false;
else if(TenMinChecked == false && customSnoozeOK.matches("Enter your own"))
return false;
else
return true;
}
public String formatTime(int hour, String minString)
{
String formattedString = null;
if(hour > 12)
{
formattedString = new StringBuilder().append(Integer.toString(hour - 12)).append(":").append(minString).append("PM").toString();
}
else
formattedString = new StringBuilder().append(Integer.toString(hour)).append(":").append(minString).append("AM").toString();
return formattedString;
}
}
Home Fragment
public class HomeFragment extends Fragment{
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private boolean alarm1Active = false;
//private boolean alarm1Visible = false;
//public String alarm1Name;
//public String alarm1Time;
//public String alarm1Occurance;
//public int alarm1Snooze;
//public int alarm1Volume;
//public boolean fragmentSwitch;
SharedPreferences sharedPreferences;
SharedPreferences.Editor prefEditor;
public static final String alarmPreferences = "alarmPreferences";
public static final String alarmTimeKey = "alarmTimeKey";
public static final String alarmNameKey = "alarmNameKey";
public static final String alarmOccuranceKey = "alarmOccuranceKey";
public static final String alarmVolumeKey = "alarmVolumeKey";
public static final String alarmSnoozeKey = "alarmSnoozeKey";
public static final String alarmVisibleKey = "alarmVisibleKey";
public boolean devMode = true;
public HomeFragment() {
// Required empty public constructor
}
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
final View view = inflater.inflate(R.layout.fragment_home, container, false);
//CODE HERE
readPreferences(view);
FloatingActionButton fabAddAlarm = (FloatingActionButton) view.findViewById(R.id.fabRefresh);
fabAddAlarm.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getActivity().getApplicationContext(), "Reading Preferences", Toast.LENGTH_LONG).show();
readPreferences(view);
}
});
return view;
}
public void readPreferences(View view)
{
TextView tvAlarm1Name = (TextView) view.findViewById(R.id.tvAlarm1Name);
TextView tvAlarm1Time = (TextView) view.findViewById(R.id.tvAlarm1Time);
TextView tvAlarm1Occurance = (TextView) view.findViewById(R.id.tvAlarm1Occurance);
Switch swAlarm1Active = (Switch) view.findViewById(R.id.swEnableAlarm1);
Button btnEditAlarm1 = (Button) view.findViewById(R.id.btnEditAlarm1);
TextView status = (TextView) view.findViewById(R.id.tvNoAlarms);
sharedPreferences = getActivity().getSharedPreferences(alarmPreferences, Context.MODE_PRIVATE);
String alarm1Name = sharedPreferences.getString(alarmNameKey, null);
String alarm1Time = sharedPreferences.getString(alarmTimeKey, null);
String alarm1Occurance = sharedPreferences.getString(alarmOccuranceKey, null);
int alarm1Snooze = sharedPreferences.getInt(alarmSnoozeKey, 0);
int alarm1Volume = sharedPreferences.getInt(alarmVolumeKey, 0);
boolean alarm1Visible = sharedPreferences.getBoolean(alarmVisibleKey, false);
if(!alarm1Visible)
{
status.setVisibility(View.VISIBLE);
status.setText("You have no alarms set!");
}
else if(alarm1Visible)
{
status.setVisibility(View.INVISIBLE);
tvAlarm1Time.setVisibility(View.VISIBLE);
tvAlarm1Name.setVisibility(View.VISIBLE);
tvAlarm1Occurance.setVisibility(View.VISIBLE);
btnEditAlarm1.setVisibility(View.VISIBLE);
swAlarm1Active.setVisibility(View.VISIBLE);
tvAlarm1Time.setText(alarm1Time);
tvAlarm1Name.setText(alarm1Name);
tvAlarm1Occurance.setText(alarm1Occurance);
}
}
}
While saving string on SharedPreferences make sure that you are not saving null. It will instead clear the preference key.
prefEditor.putString(alarmOccuranceKey, occurance);
Make sure that occurance is not null.
Please use commit() to save the data. Also you can create a simple reusable class for SharedPreferences. Please refer to my customized class for the same: https://codebegetter.wordpress.com/2016/08/04/shared-preferences-reusable-class/
Based on the comments in one of the answers it looks like you have applied a solution. However, based on the code you posted here was the issue:
You are not storing and retrieving values from the same SharedPreferences file. When you store values you are using a custom named SharedPreferences file. When you try to retrieve those values you are referencing the SharedPreferences file that is specific to the Activity which hosts your secondFragment. (Which, in a way, is actually custom named as well...the framework bases it on your Activity name).
When you write values to SharedPreferences in your secondFragment you call:
sharedPreferences = getActivity().getSharedPreferences(alarmPreferences, Context.MODE_PRIVATE);
//...
prefEditor = sharedPreferences.edit();
When you attempt to read those values in your HomeFragment you call:
sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
These two code snippets don't reference the same SharePreferences file. The most direct solution would be to update the code in your HomeFragment so that you obtain the same SharePreferences file where you stored your values like so:
sharedPreferences = getActivity().getSharedPreferences(alarmPreferences, Context.MODE_PRIVATE);

Add a note counter to android notebook project using shared preferences

I have a notebook sample project and I want to add a "note counter" to it using shared preferences and each time the user adds a note increment the counter in createNote() method. I also added a TextView to show the counter, but the counter is always zero and doesnt increment by creating a new note! ! Help me please!
public class MainActivity extends ListActivity {
private static final int EDITOR_ACTIVITY_REQUEST = 1001;
private static final int MENU_DELETE_ID = 1002;
private int currentNoteId;
private NotesDataSource datasource;
List<NoteItem> notesList;
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
datasource = new NotesDataSource(this);
refreshDisplay();
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(""+count);
}
private void refreshDisplay() {
notesList = datasource.findAll();
ArrayAdapter<NoteItem> adapter =
new ArrayAdapter<NoteItem>(this, R.layout.list_item_layout, notesList);
setListAdapter(adapter);
}
#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) {
if (item.getItemId() == R.id.action_create) {
createNote(null);
}
return super.onOptionsItemSelected(item);
}
public void createNote(View v) {
NoteItem note = NoteItem.getNew();
Intent intent = new Intent(this, NoteEditorActivity.class);
intent.putExtra(NoteItem.KEY, note.getKey());
intent.putExtra(NoteItem.TEXT, note.getText());
startActivityForResult(intent, EDITOR_ACTIVITY_REQUEST);
int defaultValue = getPreferences(MODE_PRIVATE).getInt("count_key", count);
++defaultValue;
getPreferences(MODE_PRIVATE).edit().putInt("count_key", defaultValue).commit();
count = getPreferences(MODE_PRIVATE).getInt("count_key", count);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
NoteItem note = notesList.get(position);
Intent intent = new Intent(this, NoteEditorActivity.class);
intent.putExtra(NoteItem.KEY, note.getKey());
intent.putExtra(NoteItem.TEXT, note.getText());
startActivityForResult(intent, EDITOR_ACTIVITY_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == EDITOR_ACTIVITY_REQUEST && resultCode == RESULT_OK) {
NoteItem note = new NoteItem();
note.setKey(data.getStringExtra(NoteItem.KEY));
note.setText(data.getStringExtra(NoteItem.TEXT));
datasource.update(note);
refreshDisplay();
}
}
}
Your help is appreciated. Thanks!
Based on discussion and answer given by #Rahul Tiwari...do the following modifications in your code.....
First create the instance TextView variable
//your instance variables
int count;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
//your code...
tv = (TextView) findViewById(R.id.textView1);
count = getSharedPreferences("NAME_FOR_SHARED_PREFERENCES", Context.MODE_PRIVATE).getInt("count_key", 0);
updateTextView();
}
void updateTextView(){
tv.setText(""+count);
}
//your code till here....
public void createNote(View v) {
NoteItem note = NoteItem.getNew();
SharedPreferences sharedPref = getSharedPreferences("NAME_FOR_SHARED_PREFERENCES", Context.MODE_PRIVATE);
sharedPref.edit().putInt("count_key", ++count).commit();
updateTextView()
/*for intial testing commenting this code block
Intent intent = new Intent(this, NoteEditorActivity.class);
intent.putExtra(NoteItem.KEY, note.getKey());
intent.putExtra(NoteItem.TEXT, note.getText());
startActivityForResult(intent, EDITOR_ACTIVITY_REQUEST);
*/
}
//your code.
Then you can start app multiple times and check want is the count value.
Note: When naming your shared preference files, you should use a name
that's uniquely identifiable to your app, such as
"com.example.myapp.PREFERENCE_FILE_KEY" for more detail refer
your counter is not being refreshed as you are not changing text in your text view after changing the count.
you need to use
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(""+count);
at the end of your createNote function
use getDefaultSharedPreferences to access your shared preference across activities in your app. refer this answer for example.

How do I make my ArrayList<ColorSaver> persistent in android?

I have the ArrayList...
ArrayList<ColorSaver> tempList = new ArrayList<ColorSaver>();
and I want it so that when the user closes the app or leaves the app, all the ColorSaver objects in the ArrayList will be there when the user reopens the app. I would prefer to use the SharedPreferences but I can't do that because the list is a custom object...
I have looked around and found out that I can do a serializable but I tried that and failed horribly, so if somebody could guide me through the serializable deal that would be great. Oh and where do I put the code, like in onCreate() in my mainActivity or in the activity that is displaying the ArrayList
My mainActivity class
public class MainActivity extends Activity {
ArrayList<ColorSaver> tempList = new ArrayList<ColorSaver>();
private static final String TAG = "Main Activity";
public static final String PREFS_NAME = "MyPrefsFile";
final Intent intent = new Intent();
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
final NumberPicker rednp = (NumberPicker) findViewById(R.id.redNumberPicker1);
final NumberPicker bluenp = (NumberPicker) findViewById(R.id.blueNumberPicker);
final NumberPicker greennp = (NumberPicker) findViewById(R.id.greenNumberPicker);
switch(item.getItemId())
{
case R.id.save:
Log.i(TAG, "Save item clicked!");
Intent intent = new Intent(this, SaveActivity.class);
intent.putExtra("RedValue", rednp.getValue());
intent.putExtra("BlueValue", bluenp.getValue());
intent.putExtra("GreenValue", greennp.getValue());
intent.putExtra("temparray", tempList);
startActivity(intent);
return true;
case R.id.recall:
Log.i(TAG, "Recall item clicked!");
Intent intent2 = new Intent(this, RecallActivity.class);
intent2.putExtra("temparray", tempList);
startActivity(intent2);
return true;
default:
return super.onOptionsItemSelected(item);
}//End Switch
}
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//ArrayList<ColorSaver> tempList = new ArrayList<ColorSaver>();
Bundle extras = getIntent().getExtras();
final SurfaceView sView = (SurfaceView) findViewById(R.id.surfaceView1);
final NumberPicker np = (NumberPicker) findViewById(R.id.redNumberPicker1);
np.setMaxValue(255);
np.setMinValue(0);
final NumberPicker np2 = (NumberPicker) findViewById(R.id.greenNumberPicker);
np2.setMaxValue(255);
np2.setMinValue(0);
final NumberPicker np3 = (NumberPicker) findViewById(R.id.blueNumberPicker);
np3.setMaxValue(255);
np3.setMinValue(0);
if( extras != null )
{
np.setValue(extras.getInt("savedRValue"));
//np.setValue(intent.getIntExtra("savedRValue", 255));
np2.setValue(extras.getInt("savedGValue"));
//np2.setValue(intent.getIntExtra("savedGValue", 255));
np3.setValue(extras.getInt("savedBValue"));
//np3.setValue(intent.getIntExtra("savedBValue", 255));
tempList = (ArrayList<ColorSaver>) extras.getSerializable("array");
sView.setBackgroundColor(Color.argb(255, np.getValue(), np2.getValue(), np3.getValue()));
}
else
{
Log.i(TAG, "I just don't get it...WTF");
}
np.setOnValueChangedListener( new NumberPicker.
OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal)
{
int rednum, greennum, bluenum;
rednum = np.getValue();
greennum = np2.getValue();
bluenum = np3.getValue();
sView.setBackgroundColor(Color.argb(255, rednum, greennum, bluenum));
}
});
//GREEN NUMBERPICKER LISTENER
np2.setOnValueChangedListener( new NumberPicker.
OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal)
{
int rednum, greennum, bluenum;
rednum = np.getValue();
greennum = np2.getValue();
bluenum = np3.getValue();
sView.setBackgroundColor(Color.argb(255, rednum, greennum, bluenum));
}
});
np3.setOnValueChangedListener( new NumberPicker.
OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal)
{
int rednum, greennum, bluenum;
rednum = np.getValue();
greennum = np2.getValue();
bluenum = np3.getValue();
sView.setBackgroundColor(Color.argb(255, rednum, greennum, bluenum));
}
});
}//End onCreate()
#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;
}//END onCreateOptionsMenu()
}//END CLASS
My saveActivity, where the user saves their color combo to the ArrayList...
public class SaveActivity extends Activity implements Serializable {
private static final String TAG = "Save Activity";
public ArrayList<ColorSaver> savedColors = new ArrayList<ColorSaver>();
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save);
// Show the Up button in the action bar.
setupActionBar();
Bundle extras = getIntent().getExtras();
final Intent intent1 = new Intent(this, MainActivity.class);
Button saveButton = (Button) findViewById(R.id.saveButton1);
final EditText nameField = (EditText) findViewById(R.id.colorNameField);
//final Intent intent = new Intent();
savedColors = (ArrayList<ColorSaver>) extras.getSerializable("temparray");
//Making sure the savedColors arrayList has something in it.
if( savedColors.isEmpty() )
{
ColorSaver temp = new ColorSaver("Rockies Purple", 180, 80, 255);
savedColors.add(temp);
}
saveButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Bundle extras = getIntent().getExtras();
int redcolor, greencolor, bluecolor;
redcolor = extras.getInt("RedValue");
greencolor = extras.getInt("GreenValue");
bluecolor = extras.getInt("BlueValue");
String colorName = nameField.getText().toString();
//Build the new color and add it to the arrayList
ColorSaver saver = new ColorSaver(colorName, redcolor, greencolor, bluecolor);
savedColors.add(saver);
intent1.putExtra("array", savedColors);
Log.i(TAG, savedColors.get(savedColors.size()-1).getColorName());
startActivity(intent1);
}
});
}//END OnCreate()
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.save, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}//END CLASS
My recallActivity where the user recalls their color combos...
public class RecallActivity extends SaveActivity {
private static final String TAG = "Recall Activity";
ArrayList<ColorSaver> colorsArray = new ArrayList<ColorSaver>();
SaveActivity sActivity = new SaveActivity();
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recall);
// Show the Up button in the action bar.
setupActionBar();
final Intent intent1 = new Intent(this, MainActivity.class);
final Spinner colorList = (Spinner) findViewById(R.id.colorsSpinner);
Button grabButton = (Button) findViewById(R.id.grabButton);
Bundle extras = getIntent().getExtras();
colorsArray = (ArrayList<ColorSaver>) extras.getSerializable("temparray");
//Load the spinner with the saved colors
addColorNames(colorsArray);
grabButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
ColorSaver selectedItem = (ColorSaver) colorList.getSelectedItem();
int redValue, greenValue, blueValue;
String name;
redValue = selectedItem.getRedValue();
greenValue = selectedItem.getGreenValue();
blueValue = selectedItem.getBlueValue();
name = selectedItem.getColorName();
intent1.putExtra("savedRValue", redValue);
intent1.putExtra("savedGValue", greenValue);
intent1.putExtra("savedBValue", blueValue);
intent1.putExtra("savedName", name);
intent1.putExtra("array", colorsArray);
startActivity(intent1);
}//END onClick
});
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.recall, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}// END onOptionsItemSelected(MenuItem item)
public void addColorNames(ArrayList<ColorSaver> colorsArray1)
{
colorsArray = colorsArray1;
//if( !colorsArray.isEmpty() )
//{
Spinner colorsSpinner = (Spinner) findViewById(R.id.colorsSpinner);
ArrayAdapter<ColorSaver> dataAdapter
= new ArrayAdapter<ColorSaver>
(RecallActivity.this, android.R.layout.simple_spinner_item, colorsArray);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
colorsSpinner.setAdapter(dataAdapter);
Log.i(TAG, savedColors.get(savedColors.size() - 1).toString());
//}
//else
//{
// Log.i(TAG, "colorsSpinner came out to be null....WTF???");
//}
}//End addColorNames()
}//END CLASS
I am greatful of any help!
Take a look at Android's Parcelable implementation.
So, I'm just guessing on your ColorSaver class since it wasn't posted, but you would implement it the following way:
ColorSaver.java
public class ColorSaver implements Parcelable {
private String mName;
private int mRed;
private int mGreen;
private int mBlue;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeString(mName);
out.writeInt(mRed);
out.writeInt(mGreen);
out.writeInt(mBlue);
}
public static final Parcelable.Creator<ColorSaver> CREATOR
= new Parcelable.Creator<ColorSaver>() {
public ColorSaver createFromParcel(Parcel in) {
return new ColorSaver(in);
}
public ColorSaver[] newArray(int size) {
return new ColorSaver[size];
}
};
private ColorSaver(Parcel in) {
mName = in.readString();
mRed = in.readInt();
mGreen = in.readInt();
mBlue = in.readInt();
}
}
MyActivity.java
public class MyActivity extends Activity {
private static final String COLOR_SAVER_LIST = "com.example.android.ColorSaverList";
private List<ColorSaver> colorSaverList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null && savedInstanceState.containsKey(COLOR_SAVER_LIST)) {
colorSaverList = new ArrayList<ColorSaver>();
colorSaverList = savedInstanceState.getParcelableArrayList(COLOR_SAVER_LIST);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(COLOR_SAVER_LIST, colorSaverList);
}
}

Dynamically change size of multiple textview from code (without a "on disk" xml theme)?

I have 10 TextViews in my code and i would like to change font size on all of them. On my layout i have used a #style to define common properties however i don't know how to change them all from code once layout is on screen.
What i dont want to do is update N objects but write only in one place. I know that i could use applyTheme but this assumes that you have an XML theme somewhere on disk, i want to be able to scale fonts to any size so this solution is not practical.
Any idea?
See similar questions:
How to programmatically setting style attribute in a view
android dynamically change style at runtime
android : set textView style at runtime
It sounds like its not possible to change an individual style element at runtime. You could apply a different theme, but then you would need a different theme for every font size you want to support. Annoying, but possible.
Otherwise, you have to come up with a way to reduce the pain of updating all of the textViews. You could store the size in your application class, so it is accessible by all of your activities, and then in onCreate update the size for each TextView.
Here is the whole code for dynamically change font size and theme
MainActivity:
public class MainActivity extends AppCompatActivity {
TextView textViewMain;
Button buttonChangeFont;
int size, value;
SharedPreferences pref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
changeTheme();
setContentView(R.layout.activity_main);
//References
textViewMain = findViewById(R.id.textViewMain);
buttonChangeFont = findViewById(R.id.buttonChangeFont);
//Set Onclick on button
buttonChangeFont.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent goToPreview = new Intent(MainActivity.this, PreviewActivity.class);
startActivity(goToPreview);
}
});
int value = pref.getInt("value", 0);
textViewMain.setTextSize(value);
}
private void changeTheme() {
String theme = pref.getString("theme", "default");
if (theme != null && theme.equals("default")) {
setTheme(R.style.AppTheme);
} else if (theme != null && theme.equals("black")) {
setTheme(R.style.BlackTheme);
} else {
setTheme(R.style.BlueTheme);
}
}
public void getSize() {
editor = pref.edit();
size = getIntent().getIntExtra("size", 14);
if (size == 14) {
value = 14;
editor.putInt("value", value);
} else if (size == 20) {
value = 20;
textViewMain.setTextSize(value);
editor.putInt("value", value);
} else {
value = 30;
textViewMain.setTextSize(value);
editor.putInt("value", value);
}
editor.commit();
}
#Override
protected void onStart() {
getSize();
super.onStart();
}
}
PreviewActivity:
public class PreviewActivity extends AppCompatActivity {
TextView textViewSmall, textViewMedium, textViewLarge, textViewPreview;
Button buttonOK;
String size;
int value;
SharedPreferences pref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
setContentView(R.layout.activity_preview);
//TextView References
textViewLarge = findViewById(R.id.textViewLarge);
textViewMedium = findViewById(R.id.textViewMedium);
textViewSmall = findViewById(R.id.textViewSmall);
textViewPreview = findViewById(R.id.textViewPreview);
//Button References
buttonOK = findViewById(R.id.buttonOK);
//Set Onclick listener to TextView and Button
textViewSmall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textViewPreview.setTextSize(14);
size = "small";
}
});
textViewMedium.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textViewPreview.setTextSize(20);
size = "medium";
}
});
textViewLarge.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textViewPreview.setTextSize(30);
size = "large";
}
});
buttonOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (size) {
case "small":
value = 14;
break;
case "medium":
value = 20;
break;
case "large":
value = 30;
break;
}
Intent i = new Intent(PreviewActivity.this, MainActivity.class);
i.putExtra("size", value);
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu options from the res/menu/menu_catalog.xml file.
// This adds menu items to the app bar.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
editor = pref.edit();
// User clicked on a menu option in the app bar overflow menu
switch (item.getItemId()) {
case R.id.default_theme:
textViewPreview.setBackgroundColor(Color.WHITE);
textViewPreview.setTextColor(Color.DKGRAY);
editor.putString("theme", "default");
editor.commit();
changeTheme();
return true;
case R.id.black_theme:
textViewPreview.setBackgroundColor(Color.BLACK);
textViewPreview.setTextColor(Color.WHITE);
editor.putString("theme", "black");
editor.commit();
changeTheme();
return true;
case R.id.blue_theme:
textViewPreview.setBackgroundColor(Color.BLUE);
textViewPreview.setTextColor(Color.RED);
editor.putString("theme", "blue");
editor.commit();
changeTheme();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void changeTheme() {
String theme = pref.getString("theme", "default");
if (theme != null && theme.equals("default")) {
setTheme(R.style.AppTheme);
} else if (theme != null && theme.equals("black")) {
setTheme(R.style.BlackTheme);
} else {
setTheme(R.style.BlueTheme);
}
}
}
I am using my own custom theme. To create a custom theme you can reference this article on custom theme creation.

Categories

Resources