Progress bar for counting checkboxes - java

I need every click on the checkbox to increase the percentage in progressBar.
Example: I have two checkboxes, each corresponding to 50% within the progressBar.
I tried several codes, but none worked, I'm a beginner in java
Can someone help me? Please.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
final CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox);
final CheckBox checkBox2 = (CheckBox) findViewById(R.id.checkBox2);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
if (preferences.contains("checkbox1") && preferences.getBoolean("checkbox1", false) == true) {
checkBox.setChecked(true);
} else {
checkBox.setChecked(false);
}
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (checkBox.isChecked()) {
editor.putBoolean("checkbox1", true);
editor.apply();
} else {
editor.putBoolean("checkbox1", false);
editor.apply();
}
}
});
if (preferences.contains("checkbox2") && preferences.getBoolean("checkbox2", false) == true) {
checkBox2.setChecked(true);
} else {
checkBox2.setChecked(false);
}
checkBox2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (checkBox2.isChecked()) {
editor.putBoolean("checkbox2", true);
editor.apply();
} else {
editor.putBoolean("checkbox2", false);
editor.apply();
}
}
});
}
}

Related

Android - How to save checkbox states and after app is closed, the values saved in CheckBoxes persist?

I've been working on the Android SDK platform, and it is a bit unclear how to save an application's state. I'm creating a menu which has CheckBoxes. I do get the idea of SharedPreferences but I'm not able to get my head around the implementation of SharedPreferences in CheckBoxes.
I want those checkboxes (multiple checkboxes) stay checked/unchecked even if the user relaunches the app.
public class MainActivity extends AppCompatActivity {
protected WebView myWebView;
protected TextView text_selection;
protected TextView mOutputText;
public static final String TAG = "mytag";
protected SharedPreferences sharedPreferences;
protected SharedPreferences.Editor editor;
private final String PREFERENCE_FILE_KEY = "myAppPreference";
private Context context;
protected CheckBox animal, fisheries, dairy;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
animal = (CheckBox)findViewById(R.id.animal);
fisheries = (CheckBox)findViewById(R.id.fisheries);
dairy = (CheckBox)findViewById(R.id.dairy);
//sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
sharedPreferences = getSharedPreferences(PREFERENCE_FILE_KEY, Context.MODE_PRIVATE);
//Context context = getActivity();
//SharedPreferences sharedPref = context.getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putBoolean("animal", false);
editor.putBoolean("fisheries", false);
editor.putBoolean("dairy", false);
//editor.putBoolean("checkbox", checkbox.isChecked()));
editor.commit();
this.myWebView = (WebView) findViewById(R.id.webview);
this.text_selection = findViewById(R.id.text_selected);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl("------");
//mOutputText = (TextView) findViewById(R.id.tv_output);
mOutputText = findViewById(R.id.textView);
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
#Override
public void onComplete(#NonNull Task<InstanceIdResult> task) {
if(task.isSuccessful()){
String token=task.getResult().getToken();
Log.d(TAG, "onComplete: Token: "+token);
mOutputText.setText("Token has been generated");
}else{
mOutputText.setText("Token failed");
}
}
});
}
#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, menu);
if (sharedPreferences.getBoolean("animal", false)) {
// findItem id function return the id of the menu
menu.findItem(R.id.animal).setChecked(true);
} else if (sharedPreferences.getBoolean("fisheries", false)) {
menu.findItem(R.id.fisheries).setChecked(true);
} else if (sharedPreferences.getBoolean("dairy", false)) {
menu.findItem(R.id.dairy).setChecked(true);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
editor = sharedPreferences.edit();
switch (item.getItemId()) {
case R.id.animal:
if (item.isChecked()) {
item.setChecked(false);
editor.putBoolean("animal", false);
} else {
item.setChecked(true);
editor.putBoolean("animal", true);
}
break;
case R.id.fisheries:
if (item.isChecked()) {
item.setChecked(false);
editor.putBoolean("fisheries", false);
} else {
item.setChecked(true);
editor.putBoolean("fisheries", true);
}
break;
case R.id.dairy:
if (item.isChecked()) {
item.setChecked(false);
editor.putBoolean("dairy", false);
} else {
item.setChecked(true);
editor.putBoolean("dairy", true);
}
break;
}
editor.commit();
return super.onOptionsItemSelected(item);
}
}
Below example;
dairy.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
editor.putBoolean("dairy", isChecked);
editor.commit();
}
});
Replace the beginning stuff in your onCreate with the following:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences(PREFERENCE_FILE_KEY, Context.MODE_PRIVATE);
animal = (CheckBox)findViewById(R.id.animal);
fisheries = (CheckBox)findViewById(R.id.fisheries);
dairy = (CheckBox)findViewById(R.id.dairy);
animal.setChecked(getCheckboxStatus("animal"));
animal.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
saveCheckBoxValue("animal", isChecked);
}
}
);
fisheries.setChecked(getCheckboxStatus("fisheries"));
fisheries.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
saveCheckBoxValue("fisheries", isChecked);
}
}
);
dairy.setChecked(getCheckboxStatus("dairy"));
dairy.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
saveCheckBoxValue("dairy", isChecked);
}
}
);
// Your WebView and Firebase stuff
}
private void saveCheckBoxValue(String key, boolean isChecked) {
editor = sharedPreferences.edit();
editor.putBoolean(key, isChecked);
editor.apply();
}
private boolean getCheckboxStatus(String key) {
return sharedPreferences.getBoolean(key, false);
}
Change the onCreateOptionsMenu function to the following:
#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, menu);
menu.findItem(R.id.animal).setChecked(sharedPreferences.getBoolean("animal", false));
menu.findItem(R.id.fisheries).setChecked(sharedPreferences.getBoolean("fisheries", false));
menu.findItem(R.id.dairy).setChecked(sharedPreferences.getBoolean("dairy", false));
return true;
}
Change the onOptionsItemSelected function to:
#Override
public boolean onOptionsItemSelected(MenuItem item){
editor = sharedPreferences.edit();
switch (item.getItemId()) {
case R.id.animal:
editor.putBoolean("animal", item.isChecked());
break;
case R.id.fisheries:
editor.putBoolean("fisheries", item.isChecked());
break;
case R.id.dairy:
editor.putBoolean("dairy", item.isChecked());
break;
}
editor.apply();
return super.onOptionsItemSelected(item);
}

How do I get my theme to programmatically get carried over into other activities?

I've created a function in the settings page of my app which contains a switch - that when pressed - switches to a secondary "Night" theme. I followed this tutorial for the most part. However, I don't know how to carry this night mode into my other activities? I've tried calling the "if switch checked" in my main activity, but it obviously doesn't see that switch. What I mainly need to know is, how do I check a switch state in another activity? And is this even the right way of doing it? Let me know if I've missed anything else in this question.
// ======== CODE FOR THE SETTINGS PAGE ======== //
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
// ======== Night Mode ======== //
SwitchCompat switchCompat;
final SharedPref sharedPref;
sharedPref = new SharedPref(this);
if (sharedPref.loadNightModeState()) {
setTheme(R.style.AppTheme_Night);
getSupportActionBar().setBackgroundDrawable(getDrawable(R.drawable.actionbar));
actionBarDrawerToggle.getDrawerArrowDrawable().setColor(getResources().getColor(R.color.BackgroundLight));
} else setTheme(R.style.AppTheme);
setContentView(R.layout.activity_settings);
switchCompat = (SwitchCompat) findViewById(R.id.night_switch);
if (sharedPref.loadNightModeState()) {
switchCompat.setChecked(true);
}
switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
sharedPref.setNightModeState(true);
restartApp();
} else {
sharedPref.setNightModeState(false);
restartApp();
}
}
});
}
private void restartApp() {
Intent intent = new Intent(getApplicationContext(), SettingsActivity.class);
startActivity(intent);
finish();
}
// ======== SharedPref CODE ======== //
public class SharedPref {
private SharedPreferences sharedPreferences;
public SharedPref(Context context) {
sharedPreferences = context.getSharedPreferences("filename", Context.MODE_PRIVATE);
}
public void setNightModeState(Boolean state) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("NightMode",state);
editor.apply();
}
public Boolean loadNightModeState (){
Boolean state = sharedPreferences.getBoolean("NightMode", false);
return state;
}
In you application class inside onCreate
SharedPreferences sharedPreferences = getSharedPreferences("Your_Shared_pref", Context.MODE_PRIVATE);
boolean nightMode = sharedPreferences.getBoolean(SettingsActivity.DARK_THEME_PREFERENCE_KEY, false);
AppCompatDelegate.setDefaultNightMode(nightMode ? MODE_NIGHT_YES : MODE_NIGHT_NO);
Than in your activity, do this:
switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
AppCompatDelegate.setDefaultNightMode(isChecked ? MODE_NIGHT_YES : MODE_NIGHT_NO);
if (isChecked) {
sharedPref.setNightModeState(true);
recreate();
} else {
sharedPref.setNightModeState(false);
recreate();
}
}
});
#Override
public void recreate() {
finish();
overridePendingTransition(R.anim.anime_fade_in,
R.anim.anime_fade_out);
startActivity(getIntent());
overridePendingTransition(R.anim.anime_fade_in,
R.anim.anime_fade_out);
}
you can find the animation xml online.
I put this between my onCreate and my super.onCreate. The code I used was taken from my settings java page. It turns out that it was pretty easy to figure, I just needed someone to put it into perspective!
#Override
protected void onCreate(Bundle savedInstanceState) {
final SharedPref sharedPref;
sharedPref = new SharedPref(this);
if (sharedPref.loadNightModeState()) {
setTheme(R.style.AppTheme_Night);
//restartApp();
//getSupportActionBar().setBackgroundDrawable(getDrawable(R.drawable.actionbar));
//actionBarDrawerToggle.getDrawerArrowDrawable().setColor(getResources().getColor(R.color.BackgroundLight));
} else setTheme(R.style.AppTheme);
//restartApp();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

progressBar with 5 checkbox

I need progressBar to load the percentage of how many checkboxes are checked.
I tried to use it for 5 checkbox:
"progressbar.setProgress (20)" if it was checked, and if it was not "progressbar.setProgress (-20)"
The progressBar loads only "20%" even if the 5 checkboxes are checked.Can someone help me?
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
final CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox);
final CheckBox checkBox2 = (CheckBox) findViewById(R.id.checkBox2);
final CheckBox checkBox3 = (CheckBox) findViewById(R.id.checkBox3);
final CheckBox checkBox4 = (CheckBox) findViewById(R.id.checkBox4);
final CheckBox checkBox5 = (CheckBox) findViewById(R.id.checkBox5);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
if (preferences.contains("checkbox1") && preferences.getBoolean("checkbox1", false) == true) {
checkBox.setChecked(true);
} else {
checkBox.setChecked(false);
}
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (checkBox.isChecked()) {
editor.putBoolean("checkbox1", true);
progressBar.setProgress(20);
editor.apply();
} else {
editor.putBoolean("checkbox1", false);
progressBar.setProgress(-20);
editor.apply();
}
}
});
if (preferences.contains("checkbox2") && preferences.getBoolean("checkbox2", false) == true) {
checkBox2.setChecked(true);
} else {
checkBox2.setChecked(false);
}
checkBox2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (checkBox2.isChecked()) {
editor.putBoolean("checkbox2", true);
progressBar.setProgress(20);
editor.apply();
} else {
editor.putBoolean("checkbox2", false);
progressBar.setProgress(-20);
editor.apply();
}
}
});
if (preferences.contains("checkbox3") && preferences.getBoolean("checkbox3", false) == true) {
checkBox3.setChecked(true);
} else {
checkBox3.setChecked(false);
}
checkBox3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (checkBox3.isChecked()) {
editor.putBoolean("checkbox3", true);
progressBar.setProgress(20);
editor.apply();
} else {
editor.putBoolean("checkbox3", false);
progressBar.setProgress(-20);
editor.apply();
}
}
});
if (preferences.contains("checkbox4") && preferences.getBoolean("checkbox4", false) == true) {
checkBox4.setChecked(true);
} else {
checkBox4.setChecked(false);
}
checkBox4.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (checkBox4.isChecked()) {
editor.putBoolean("checkbox4", true);
progressBar.setProgress(20);
editor.apply();
} else {
editor.putBoolean("checkbox4", false);
progressBar.setProgress(-20);
editor.apply();
}
}
});
if (preferences.contains("checkbox5") && preferences.getBoolean("checkbox5", false) == true) {
checkBox5.setChecked(true);
} else {
checkBox5.setChecked(false);
}
checkBox5.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (checkBox5.isChecked()) {
editor.putBoolean("checkbox5", true);
progressBar.setProgress(20);
editor.apply();
} else {
editor.putBoolean("checkbox5", false);
progressBar.setProgress(-20);
editor.apply();
}
}
});
}
}
Your problem is you always set it to 20 or -20 instead of updating it from its current value. use
progressBar.setProgress(progressBar.getProgress()+20);
or
progressBar.setProgress(progressBar.getProgress()-20);

First Button Coloured only after reopen application

I already ask this question several time in stack overflow, I hope this time can somebody show me the correct code, I modify my coding many time still same output.
coding:
public class MainActivity extends AppCompatActivity {
Toolbar mToolbar;
Button mRedColor;
Button mGreenColor;
Button mYellowColor;
Button[] b=new Button[2];
SharedPreferences mSharedPreferences;
SharedPreferences.Editor edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSharedPreferences = getSharedPreferences("ButtonColor", MODE_PRIVATE);
edit = getSharedPreferences("ButtonColor", MODE_PRIVATE).edit();
mToolbar = (Toolbar) findViewById(R.id.toolbar);
final Button[] b = new Button[]{(Button) findViewById(R.id.btnRed),
(Button) findViewById(R.id.btnGreen),
(Button) findViewById(R.id.btnYellow),};
mToolbar.setTitle(getResources().getString(R.string.app_name));
if (getColor() != getResources().getColor(R.color.colorPrimary)) {
for (int i = 0 ; i<b.length; i++){
if(b[i].equals(b[0]) ){
b[0].setBackgroundColor(getColor());
b[i].setEnabled(false);
}
else if (b[i].equals(b[1])){
b[1].setBackgroundColor(getColor());
b[i].setEnabled(false);
}else if (b[i].equals(b[2])){
b[2].setBackgroundColor(getColor());
b[i].setEnabled(false);
}
}
}
for (int i = 0; i < b.length; i++) {
b[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) //so we get its id here
{
case (R.id.btnRed):
b[0].setBackgroundColor(getResources().getColor(R.color.colorRed));
storeColor(getResources().getColor(R.color.colorRed));
b[0].setEnabled(false);
break;
case (R.id.btnGreen):
b[1].setBackgroundColor(getResources().getColor(R.color.colorGreen));
storeColor(getResources().getColor(R.color.colorGreen));
b[1].setEnabled(false);
break;
case (R.id.btnYellow):
b[2].setBackgroundColor(getResources().getColor(R.color.colorYellow));
storeColor(getResources().getColor(R.color.colorYellow));
b[2].setEnabled(false);
break;
}
}
});
}
}
#Override
protected void onResume() {
super.onResume();
mSharedPreferences = getSharedPreferences("ButtonColor", MODE_PRIVATE);
edit=getSharedPreferences("ButtonColor", MODE_PRIVATE).edit();
}
#Override
public void onStop () {
super.onStop();
}
private void storeColor(int color){
SharedPreferences mSharedPreferences =
getSharedPreferences("ButtonColor", MODE_PRIVATE);
SharedPreferences.Editor mEditor = mSharedPreferences.edit();
mEditor.putInt("color", color);
mEditor.apply();
}
private int getColor(){
SharedPreferences mSharedPreferences =
getSharedPreferences("ButtonColor", MODE_PRIVATE);
int selectedColor = mSharedPreferences.getInt("color",
getResources().getColor(R.color.colorPrimary));
return selectedColor;
}
}
The problem i face is in here: The first Button only will be coloured permanently after reopen application...., thanks
Try below code. you will able to change all buttons color but it will store only last selected button color.
public class MainActivity extends AppCompatActivity {
Toolbar mToolbar;
Button mRedColor;
Button mGreenColor;
Button mYellowColor;
Button[] b = new Button[2];
SharedPreferences mSharedPreferences;
SharedPreferences.Editor edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color);
mSharedPreferences = getSharedPreferences("ButtonColor", MODE_PRIVATE);
edit = getSharedPreferences("ButtonColor", MODE_PRIVATE).edit();
mToolbar = (Toolbar) findViewById(R.id.toolbar);
final Button[] b = new Button[]{(Button) findViewById(R.id.btnRed),
(Button) findViewById(R.id.btnGreen),
(Button) findViewById(R.id.btnYellow),};
mToolbar.setTitle(getResources().getString(R.string.app_name));
int lastPostion = getButtonPosition();
if (getColor() != getResources().getColor(R.color.colorPrimary)) {
for (int i = 0; i < b.length; i++) {
if (b[i].equals(b[0]) && i == lastPostion) {
b[0].setBackgroundColor(getColor());
b[i].setEnabled(false);
} else if (b[i].equals(b[1]) && i == lastPostion) {
b[1].setBackgroundColor(getColor());
b[i].setEnabled(false);
} else if (b[i].equals(b[2]) && i == lastPostion) {
b[2].setBackgroundColor(getColor());
b[i].setEnabled(false);
}
}
}
for (int i = 0; i < b.length; i++) {
b[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) //so we get its id here
{
case (R.id.btnRed):
b[0].setBackgroundColor(getResources().getColor(android.R.color.holo_red_dark));
storeColor(getResources().getColor(android.R.color.holo_red_dark), 0);
b[0].setEnabled(false);
break;
case (R.id.btnGreen):
b[1].setBackgroundColor(getResources().getColor(android.R.color.holo_green_dark));
storeColor(getResources().getColor(android.R.color.holo_green_dark), 1);
b[1].setEnabled(false);
break;
case (R.id.btnYellow):
b[2].setBackgroundColor(getResources().getColor(android.R.color.black));
storeColor(getResources().getColor(android.R.color.black), 2);
b[2].setEnabled(false);
break;
}
}
});
}
}
#Override
protected void onResume() {
super.onResume();
mSharedPreferences = getSharedPreferences("ButtonColor", MODE_PRIVATE);
edit = getSharedPreferences("ButtonColor", MODE_PRIVATE).edit();
}
#Override
public void onStop() {
super.onStop();
}
private void storeColor(int color, int position) {
SharedPreferences mSharedPreferences =
getSharedPreferences("ButtonColor", MODE_PRIVATE);
SharedPreferences.Editor mEditor = mSharedPreferences.edit();
mEditor.putInt("color", color);
mEditor.putInt("position", position);
mEditor.apply();
}
private int getColor() {
SharedPreferences mSharedPreferences =
getSharedPreferences("ButtonColor", MODE_PRIVATE);
int selectedColor = mSharedPreferences.getInt("color",
getResources().getColor(R.color.colorPrimary));
return selectedColor;
}
private int getButtonPosition() {
SharedPreferences mSharedPreferences =
getSharedPreferences("ButtonColor", MODE_PRIVATE);
int selectedColor = mSharedPreferences.getInt("position", 0);
return selectedColor;
}
}

Change Floating Action Button Background

I am using a floating action button and its image changes when its clicked. i have a flag and i store it in shared preferences. when it is true icon becomes like.png, when it is false icon becomes dislike.png.
I want to change its icon according to flag variable but when the app starts its icon is default which is true.png
How can I set the icon via shared preferences?
public class ReadActivity extends AppCompatActivity {
private FloatingActionButton fab;
private boolean flag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read);
fab = (FloatingActionButton) findViewById(R.id.fab);
getRate(getWindow().getDecorView().getRootView());
if(flag==false){
fab.setImageResource(R.drawable.like);
}
else if(flag==true){
fab.setImageResource(R.drawable.dislike);
}
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getRate(v);
if(flag==false) {
rateUp();
Snackbar.make(v, "Vote +1", Snackbar.LENGTH_LONG).show();
saveRate(v, true);
fab.setImageResource(R.drawable.dislike);
}
else if(flag==true){
rateDown();
Snackbar.make(v, "Vote -1", Snackbar.LENGTH_LONG).show();
saveRate(v, false);
fab.setImageResource(R.drawable.like);
}
}
});
}
public void rateUp() {};
public void rateDown() {};
public void saveRate(View view, boolean flag){
SharedPreferences sharedPreferences = getSharedPreferences("Rates", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(id, flag);
editor.commit();
}
public void getRate(View view){
SharedPreferences sharedPreferences = getSharedPreferences("Rates", MODE_PRIVATE);
flag = sharedPreferences.getBoolean(id, false);
}
}
Try this code :
public class ReadActivity extends AppCompatActivity {
private FloatingActionButton fab;
private string getSharedPreferencesId="getSharedPreferencesId";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read);
fab = (FloatingActionButton) findViewById(R.id.fab);
boolean flag=getRate();
if(flag==false){
fab.setImageResource(R.drawable.like);
}
else if(flag==true){
fab.setImageResource(R.drawable.dislike);
}
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean flag=getRate();
if(flag==false) {
rateUp();
Snackbar.make(v, "Vote +1", Snackbar.LENGTH_LONG).show();
saveRate(true);
fab.setImageResource(R.drawable.dislike);
}
else if(flag==true){
rateDown();
Snackbar.make(v, "Vote -1", Snackbar.LENGTH_LONG).show();
saveRate(false);
fab.setImageResource(R.drawable.like);
}
}
});
}
public void rateUp() {};
public void rateDown() {};
public void saveRate(boolean flag){
SharedPreferences sharedPreferences = getSharedPreferences("Rates", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(getSharedPreferencesId, flag);
editor.commit();
}
public boolean getRate(){
SharedPreferences sharedPreferences = getSharedPreferences("Rates", MODE_PRIVATE);
flag = sharedPreferences.getBoolean(getSharedPreferencesId, false);
}
}
I made some improvements on your code:
public class ReadActivity extends AppCompatActivity {
private FloatingActionButton fab;
private boolean flag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read);
fab = (FloatingActionButton) findViewById(R.id.fab);
flag = getRate();
if(flag)
fab.setImageResource(R.drawable.dislike);
else
fab.setImageResource(R.drawable.like);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flag = getRate();
if(flag) {
rateDown();
Snackbar.make(v, "Vote -1", Snackbar.LENGTH_LONG).show();
saveRate(false);
fab.setImageResource(R.drawable.like);
}
else{
rateUp();
Snackbar.make(v, "Vote +1", Snackbar.LENGTH_LONG).show();
saveRate(true);
fab.setImageResource(R.drawable.dislike);
}
}
});
}
public void rateUp() {};
public void rateDown() {};
public void saveRate(boolean flag){
SharedPreferences sharedPreferences = getSharedPreferences("Rates", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(id, flag);
editor.commit();
}
public boolean getRate(){
SharedPreferences sharedPreferences = getSharedPreferences("Rates", MODE_PRIVATE);
boolean flag = sharedPreferences.getBoolean(id, false);
return flag;
}
}
Also check your activity_read.xml file. If you have set an image on your xml FloatingActionButton, it will always use that image as default.
I will tell you the logic. Assumed you have many different contents and you want to save rating data for each content.
First, you need to store your each content's rating data into somewhere(Local or Remote DB, SharedPreferences, File etc.)
After starting your ReadActivity,
Set your flag to default value you wanted to be.
Set your FAB icon as default.
Get your related content rating data(boolean) from where you stored before.
Check if your rating data is true or false.
If it's true set your icon R.drawable.dislike, else set R.drawable.like
When you clicked the FAB, change your flag value and FAB icon
Save your new boolean value to where you stored before
The important point is, you must have different values for each content you have.
EDIT:
Try using getApplicationContext() before using getSharedPreferences()
Also you can try editor.apply() instead of editor.commit();
commit() and apply() does the same work but there are two differences, apply() works asynchronously and commit() returns boolean value.
public void saveRate(View view, boolean flag){
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("Rates", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(id, flag);
editor.apply();
}
public void getRate(View view){
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("Rates", MODE_PRIVATE);
flag = sharedPreferences.getBoolean(id, false);
}

Categories