Shared preferences true by default for some reason - java

I want my button to show "catch" at the very beginning if there is no key the same as the name of a current pokemon and "release" if there is one and its value is true. I send "false" by default with getBoolean. But for some reason, the first text I see with every new pokemon is "release". What could be wrong?
Edit: I include the entire onCreate method and the button's onClick method along with the layout.
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Catch"
android:onClick="toggleCatch"
android:visibility="visible" />
SharedPreferences catchStorage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pokemon);
requestQueue = Volley.newRequestQueue(getApplicationContext());
url = getIntent().getStringExtra("url");
nameTextView = findViewById(R.id.pokemon_name);
numberTextView = findViewById(R.id.pokemon_number);
type1TextView = findViewById(R.id.pokemon_type1);
type2TextView = findViewById(R.id.pokemon_type2);
pokemonName = getIntent().getStringExtra("name");
catchStorage = getSharedPreferences("catchStorage", Context.MODE_PRIVATE);
Button catchBut = (Button)findViewById(R.id.button);
if(catchStorage.getBoolean(pokemonName, false)){
catchBut.setText("Release");
}
else {
catchBut.setText("Catch");
}
load();
}
public void toggleCatch(View view) {
Button catched = (Button)view;
SharedPreferences.Editor editor = catchStorage.edit();
if(catchStorage.getBoolean(pokemonName, false)){
editor.putBoolean(pokemonName, false);
editor.commit();
catched.setText("Catch");
}
else {
editor.putBoolean(pokemonName, true);
editor.commit();
catched.setText("Release");
}
}

The value of shared preference will be set default value by the system (false in this case) if the variable was never accessed by the user or was never created, if you or the user changed this value, the default value is ignored.
See http://developer.android.com/guide/topics/data/data-storage.html#pref
So either the value is accessed before or it is set some value.
More complete code snippet may help to find the reason.

Related

TextView doesn't change visually, but the date it keeps is correct

After login, I want to change text in TextView near profile on name_user.
But it doesn't change textView visually.
It is worth to mention, that when outputting (Toast), it gives out the data that is needed, but does not visually display it. Everything is fine with the TextView parameters (I think), because if you set the finished text in the parameters( i mean android:text="smth"), it visually displays it.
Java code:
`protected void onCreate(Bundle savedInstanceState) {
yourLayout = getLayoutInflater().inflate(R.layout.layout_navigation_header, null);
profileName = yourLayout.findViewById(R.id.profName); //
Intent intent = getIntent(); // Get data from previous activity.
String name_user = intent.getStringExtra("name");
String email_user = intent.getStringExtra("email");
String password_user = intent.getStringExtra("password");
profileName.setText(name_user); //0 changes, textView still don't change.
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu2);
DrawerLayout drawerLayout = findViewById(R.id.drawerLayout);
Toast toast = Toast.makeText(getApplicationContext(), profileName.getText().toString(),
Toast.LENGTH_SHORT); // for debug, it works and show profileName that contains name_user, but.
toast.show();
findViewById(R.id.imageMenu).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
drawerLayout.openDrawer(GravityCompat.START);
}
});
}`
Part of main XML
`<com.google.android.material.navigation.NavigationView
android:id="#+id/navigationView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:headerLayout="#layout/layout_navigation_header"// layour_navigation_header -here is TextView
app:menu='#menu/navigation_menu'
android:layout_gravity="start"/>`
Part of layour_navigation_header with TextView that I need to change.
`<TextView
android:id="#+id/profName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:textColor="#color/black"
android:textSize="18sp"
android:text="Temporary"
app:layout_constraintBottom_toTopOf="#id/viewSupporter"
app:layout_constraintStart_toEndOf="#id/imageProfile"/>`
Hope you could help me
I tried to move
`yourLayout = getLayoutInflater().inflate(R.layout.layout_navigation_header, null);
profileName = yourLayout.findViewById(R.id.profName); //
Intent intent = getIntent(); // Get data from previous activity.
String name_user = intent.getStringExtra("name");
String email_user = intent.getStringExtra("email");
String password_user = intent.getStringExtra("password");
profileName.setText(name_user); //0 changes, textView still don't change`
before
`super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu2);`
but final result remains the same. It contains data, but not visually displays it.
You're inflating layout_navigation_header layout and setting a value in one of its textviews. But you never seem to place the layout on screen, the layout instance simply gets discarded.
What gets displayed is the activity_menu2 layout you inflate and set as content view with setContentView(). If that layout includes layout_navigation_header or its look-a-like with some mechanism, it's not the same instance you inflated earlier.
To solve the issue, just call setContentView() to set your desired layout, call findViewById() to find the textview and set a text to it.

How to save the state of a button in AndroidStudio?

I am new at programing in Java and I am taking a course of Android application. I am building a button inside an activity. But when I exit the activity, the button changes to it's original state. I know I am not doing anything to save its state, but how do I do it?
Here is the xml file (only the button part):
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Catch"
android:id="#+id/button"
android:onClick="toggleCatch" />
And here is toggleCatch:
private boolean isCaught = false;
#SuppressLint("SetTextI18n")
public void toggleCatch(View view) {
Button button = findViewById(R.id.button);
if (isCaught) {
button.setText("Catch");
isCaught = false;
} else {
button.setText("Release");
isCaught = true;
}
}
What could I do to make it work?
you should store the data that indicate on it state in some place:
1. SQLlite
2. Server
3. SharedPreference
and then when you create the activity you set the state of the btn based on the data you loaded.
if you do it just for practice, I believe that the sharepreference will be just fine.
https://developer.android.com/training/data-storage/shared-preferences
to store any data locally in the sharedPreference:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("SOME_NAME_FOR_YOUR_VARIABLE_EX_BTN_STATE", trueOrFalse);
editor.commit();
to get the saved data:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
boolean stateBtn = sharedPref.getBoolean("SOME_NAME_FOR_YOUR_VARIABLE_EX_BTN_STATE", defaultValueForExTrue);
sharedPref.getBoolean can be used also for sharedPref.getString, sharedPref.getInt Etc..
hope that helped..
My recommendation for you is to read about the subjects above.(SQLlite, SharedPreference)
You need to save button state in persistent storage; there are several types of persistent storage that Android supports, like SharedPreference, DataBase, internal/external storage File... The most appropriate for your question is the SharedPreference as it stores small data.
To achieve that in your code sample
public static final String PREFS_NAME = "PREFS_NAME";
public static final String BUTTON_STATUS = "status";
private boolean isCaught = false;
#SuppressLint("SetTextI18n")
public void toggleCatch(View view) {
Button button = findViewById(R.id.button);
if (isCaught) {
button.setText("Catch");
isCaught = false;
} else {
button.setText("Release");
isCaught = true;
}
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(BUTTON_STATUS, isCaught);
editor.apply();
}
And you need to retrieve the value again from the shared preference when the app is launched, so in your activity onCreate() method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
isCaught = prefs.getBoolean(BUTTON_STATUS, false);
if (isCaught) {
button.setText("Release");
} else {
button.setText("Catch");
}
}

How to save button State into SharedPreferences in Android

I want create content application, i load data from JSON and when users click on button save this content into SQLitedatabase.
I want use this library for button.
And for checkable button, I use this code
I write below codes, when click on button i save this content into SQLitedatabase, but i can't save button sate into SharedPreferences!
When click on button (boolean checked) button is turn on, and when click again on the button turn off this button.
I want when click on button, turn on this button and save in SharedPreferences and when go to other activity and again back this activity, see turn on this button NOT turn off. when click again this button at that time turn off button!
Activity codes:
private ShineButton postShow_favPost;
private String favData = "FavPrefsList";
private Boolean favState;
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.post_show_page);
bindActivity();
//Give Data
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
title = bundle.getString("title");
image = bundle.getString("image");
content = bundle.getString("content");
dateTime = bundle.getString("dateTime");
author = bundle.getString("author");
category = bundle.getString("category");
categoryID = bundle.getString("categoryID");
}
mAppBarLayout.addOnOffsetChangedListener(this);
//// Save Fav state
final SharedPreferences saveFavPrefs = getSharedPreferences(favData, MODE_PRIVATE);
final SharedPreferences.Editor editor = saveFavPrefs.edit();
favState = saveFavPrefs.getBoolean("isChecked", false);
postShow_favPost = (ShineButton) mToolbar.findViewById(R.id.post_FavImage);
postShow_favPost.init(this);
postShow_favPost.setOnCheckStateChangeListener(new ShineButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(View view, boolean checked) {
if (checked == true) {
editor.putBoolean("isChecked", true);
editor.commit();
//////////// Database
favDB = new FavHelper(context);
long addNewFAV = favDB.insertFAV(title, image, content, dateTime, author, category);
if (addNewFAV < 0) {
TastyToast.makeText(context, "Not save in database", TastyToast.LENGTH_LONG, TastyToast.ERROR);
} else {
TastyToast.makeText(context, "Save in database", TastyToast.LENGTH_LONG, TastyToast.SUCCESS);
}
////////////////////
} else {
editor.putBoolean("isChecked", false);
editor.commit();
Toast.makeText(context, "Checked False", Toast.LENGTH_SHORT).show();
}
}
});
How can i fix my issue ?
Well you need to save the state when you click the button.
For example :
postShow_favPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (postShow_favPost.isChecked()){
editor.putBoolean("isChecked", true);
editor.apply();
}
else{
editor.putBoolean("isChecked", false);
editor.apply();
}
}
});
Then you have to load it in your onCreate():
#Override
protected void onCreate(Bundle savedInstanceState)
{
SharedPreferences saveFavPrefs = getSharedPreferences(favData, MODE_PRIVATE);;
postShow_favPost.setChecked(saveFavPrefs.getBoolean("isChecked", true));
}
Maybe this example will help you.
EDIT
Ok let's presume in your f function you just finished doing whatever you're doing to your database, after that, set the state as on or off, let's say you want on.
So :
public void loadPrefs(SharedPreferences prefs){
favState = prefs.getBoolean("isChecked",false);
}
public void f(SharedPreferences.Editor editor){
//database stuff
editor.putBoolean("isChecked", true); // or false
editor.apply();
loadPrefs(prefs);
// in here your state will be saved for your button as soon as you
finish working with your database, after that in your onResume() you
may change that state to false(off) in case you want it just for that post
}

How to save an answer in a riddle game without creating a database?

I've created a question and answer game with different levels, each level consisting a question. I didn't create it with a database. I just used string. When the user answers a question in level one he is taken to level two but when the user returns back to level one, he has to type the answer again even though he's solved it before. Is there anyway in JAVA to keep the answer in the type panel (if the user's solved it) without having to create a database?? Also, while typing in the type panel, the user has to delete the "Type here..." and then answer. Is there anyway that when user taps to type the "Type here..." is automatically erased?
Here's my level one activity.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
android:weightSum="1"
android:textAlignment="center"
android:id="#+id/level1">
<TextView
android:layout_width="300dp"
android:layout_height="200dp"
android:text="What has 88 keys but cannot open a single door?"
android:id="#+id/que1"
android:width="255dp"
android:textSize="30dp"
android:layout_margin="50dp"
android:textStyle="italic"
android:gravity="center" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/type1"
android:layout_gravity="center_horizontal"
android:text="Type here..." />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check answer..."
android:id="#+id/check1"
android:layout_gravity="center_horizontal" />
</LinearLayout>
and here's my Oneactivity.java
package com.golo.user.gaunkhanekatha;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.os.Handler;
public class OneActivity extends Activity {
public SharedPreferences preferences; //ADDED THIS LINE
public Button check;
public EditText typeh;
private Toast toast;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one);
toast = Toast.makeText(OneActivity.this, "", Toast.LENGTH_SHORT);
check = (Button)findViewById(R.id.check1); //R.id.button is the id on your xml
typeh = (EditText)findViewById(R.id.type1); //this is the EditText id
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
//Here you must get the text on your EditText
String Answer = (String) typeh.getText().toString(); //here you have the text typed by the user
//You can make an if statement to check if it's correct or not
if(Answer.equals("Piano") || (Answer.equals("Keyboard")))
{
preferences = PreferenceManager.getDefaultSharedPreferences(v.getContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("Level 1 question 1 ", 1); //Depends of the level he have passed.
editor.apply();
///Correct Toast
toast.setText("Correct");
toast.setGravity(Gravity.TOP | Gravity.LEFT, 500, 300);
toast.show();
Intent i = new Intent(OneActivity.this, TwoActivity.class);
startActivity(i);
finish();
}
else{
//It's not the correct answer
toast.setText("Wrong! Try again...");
toast.show();
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
if(toast!= null) {
toast.cancel();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_aboutus, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Also, the toast is displayed where there's keyboard. Is there anyway to move the toast screen to somewhere on the screen where it is clearly visible?
I'll give to you two methods to do it :
Create a LevelEarned class as follows :
public class LevelEarned {
public static int level = 0;
}
Everytime you get an Intent (because user has answered the question correctly) just type :
LevelEarned.level = 1; // 1 depends with the level you have answered correctly
And the best method that it's that I'd use to this it's called SharedPreferences
You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).
The first thing you have to do is store this data on SharedPreferences and you do it with an Editor as follows :
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(v.getContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("player_level",1); //Depends of the level he have passed.
editor.apply();
NOTE
I guess you will do it immediately when the user accepts the question so, you'll do it on a Button click so you'll have to pass as a context v.getContext() if you are not on a ButtonClick and you are on your onCreate() just call this to refer your context.
To get the stored data (level) you'll need to do this :
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
int level = preferences.getInt("player_level", 0);
Let's explain to you a little bit.
The first parameter it's the key to find the SharedPreference so it won't change and the second one is a default value that it's used in case it doesn't find any "player_level" SharedPreferences.
Hope it helps to you to keep going in your code :)
EDIT2
Create SharedPreferences preferences as a global variable as follows :
public SharedPreferences preferences;
Then inside of your onClick() method add those lanes :
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
//Here you must get the text on your EditText
String Answer = (String) typeh.getText().toString(); //here you have the text typed by the user
//You can make an if statement to check if it's correct or not
if(Answer.equals("4") || (Answer.equals("four")))
{
preferences = PreferenceManager.getDefaultSharedPreferences(v.getContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("player_level",1); //Depends of the level he have passed.
editor.apply();
//Create a Toast because it's correct
Toast.makeText(OneActivity.this, "Correct!",
Toast.LENGTH_LONG).show();
}
else{
//It's not the correct answer
Toast.makeText(OneActivity.this, "Wrong! Try Again",
Toast.LENGTH_LONG).show();
}
}
});
And where you want to know the level you only will have to do :
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
int level = preferences.getInt("player_level", 0); //level is the current level of the player.
EDIT 3
Create a class as follows :
public static class LevelPlayer(){
public int static getLevelPlayer(){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
int level = preferences.getInt("player_level", 0); //level is the current level of the playe
return level;
}
}
And every time you want to ask the level of the player you do :
int Level = LevelPlayer.getLevelPlayer(); //that's the level
So after every question you can ask the level and put the next question.
EDIT4
I've made some changes, delete your lvl class and put this code :
public class lvl{
public Context mcontext;
public lvl(Context context){
this.mcontext = context;
}
public int getLevelPlayer(){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mcontext);
int level = preferences.getInt("player_level", 0); //level is the current level of the playe
return level;
}
Then on your MainActivity(or wherever you have to know what's the level of the player) you have to put this :
public levelplayer mlevelplayer;
Then inside on your onCreate() add this :
mlevelplayer = new levelplayer(this);
int level = mlevelplayer.getLevelPlayer();
You can use SharedPreferences
To Write to shared preference
SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
to read
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
it is simple. Just create a file to store information. You can do it in two ways.
one is to save a simple xml or json, the second one is to create a model of your answer and serialize a collection of them and save them in file.
Remember that you should do it in some kind of structure way: json, xml, serialized class. it is much simpler to work in future with that
You have a few options that you could try.
One option is as #Stultuske stated, you could try an XML or a TXT file stored on the users device. This (as well as a database) would persist between application sessions.
The other option that you have is you could create a singleton class.
For example, a class called Globals (as below) :
public class Globals {
private static Globals instance;
private String questionOneAnswer;
private Globals(){}
public String getQuestionOne()
{
return this.questionOneAnswer;
}
public void setQuestionOne(String questionOne)
{
this.questionOneAnswer = questionOne;
}
public static synchronized Globals getInstance()
{
if(instance==null)
{
instance=new Globals();
}
return instance;
}
}
This can then be called with Globals g = Globals.getInstance(); . This will only persist through your application instance; however, so if you are wanting to store it throughout app launches you can try the XML/TXT or SharedPreferences as stated by #shaikhmanzoor .
Also it is customary to define variable names with camelCase - ie answers rather than Answers, or typeH rather than typeh. Have a look here for the guidelines for Google Java coding.
For your first question just use SharedPreferences to save and fetch the data like this
SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("level_no_answer", answer_given_by_user);
editor.commit();
and for your second question, you are using android:text="Type here..." in EditText. just replace that line by android:hint="Type here..."

How to call a method from layout with variables

I may be going about this the wrong way - applying what I know from other API's - so, if so, perhaps you can point me in a different direction. The fact is, I can't seem to find any examples for exactly what I am doing. I'm trying to call a method from the xml layout. I want to call the same method from various checkboxes, basically on a click of any checkbox, I want to store the isChecked state in the SharedPreferences file. This is my xml and java:
<CheckBox
android:layout_width="194dp"
android:layout_height="wrap_content"
android:text="#string/Chri"
android:id="#+id/chkbxChristmas"
android:checked="false"
android:onClick="savePreferencesData(#string/Chri,#+id/chkbxChristmas)"/>
public void savePreferencesData(String preference,int id) {
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = prefs.edit();
CheckBox cb1 = (CheckBox) findViewById(id);
editor.putBoolean(preference, cb1.isChecked());
// Commit the edits!
editor.commit();
};
As you can see, I'm trying to pass the checkbox ID and the #string/Chri string value (I use this value as the tag in the SharedPreferences file) so the method knows which preference to update.
Is it even possible to pass the variables, and is there a better way to identify which checkbox is calling the method?
I appreciate the help!
Just a quick update: For some reason I could not get the Lister to function... here is my code:
public void saveHanuPref(View view) {
final CheckBox checkBox = ( CheckBox ) findViewById( R.id.chkbxHanukkah );
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if ( isChecked )
{
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(getString(R.string.Hanu), checkBox.isChecked());
editor.commit();
}
}
});
}
Calling this simple method from the activity xml (using onClick) did work:
public void saveChriPref(View view) {
CheckBox checkBox = ( CheckBox ) findViewById( R.id.chkbxChristmas );
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(getString(R.string.Chri), checkBox.isChecked());
editor.commit();
};
Thanks again for the help.
The right way would be to set an OnCheckedChangeListener
CheckBox checkBox = ( CheckBox ) findViewById( R.id.chkbxChristmas );
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if ( isChecked )
{
// perform logic
}
}
});
The method you declare in your onClick() method of the button can take only one input type - it is the View which holds that button. No other data can be specified.
Said that, the method in onCLick should be only the name of the method, no parameters etc.
android:onClick = "savePreferencesData()"
Assuming, you are using the Activity class, this is how the method should be created.
public void savePreferencesData(View v) {
// do what you want
}
The method you declared in the xml file should be present in the same Activity class only. Said that, other buttons in other XML files cannot re-use this method.
is there a better way to identify which checkbox is calling the
method?
Try the below code sample:
YOUR_CHECKBOX_NAME.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(YOUR_CHECKBOX_NAME.isChecked()) {
System.out.println("Checked");
} else {
System.out.println("Un-Checked");
}
}
});

Categories

Resources