I have two Activities. And a static integer called as counter.
So if I press a button in activity 'A' then counter = counter + 1.
Here is the code from activity a:
public static int counter = 0;
cmdOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter = counter + 1;
if (counter == 5)
{
tagihan.txtShip1.setTextColor(Color.parseColor("#000000"));
tagihan.txtNilai1.setTextColor(Color.parseColor("#000000"));
tagihan.txtSupir1.setTextColor(Color.parseColor("#000000"));
}
}
And here it is from activity b :
cmdSuccess.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a.counter = a.counter + 1;
if (a.counter == 5)
{
tagihan.txtShip1.setTextColor(Color.parseColor("#000000"));
tagihan.txtNilai1.setTextColor(Color.parseColor("#000000"));
tagihan.txtSupir1.setTextColor(Color.parseColor("#000000"));
}
}
My problem is when i tried to press a button from activity a 3 times it work perfectly. So the values are 3 now.
But when i tried press a button from activity b, the value is going restart into 0. Actually i didn't destroy activity a.
So what i want is the value is going continouosly even i press from activity a or b.
Any ideas ?
Edited :
I have edit the code. Tagihan activity is what im trying to accomplished. So when the counter is 5, then tagihan activity is changing.
Dont use static data, this is a bad approach and is not a common OOP-way to develope, instead try passing data between activities...
Act1
Intent intent = new Intent(activity2.this, activity1.class);
intent.putExtra("message", message);
startActivity(intent);
Act2:
Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");
Android development web is giving an introduction to this:
http://developer.android.com/training/basics/firstapp/starting-activity.html
After your edit, I can see that you need a "global varfiable" that can be read/write for all the activities:
Solution:
All activities are embedded in an Application, so if you habe fields/members in the application you can access to them with a stadard setter/getter
you need:
Define an application
public class MyApplication extends Application {
private int counterVariable;
public int counterVariable() {
return this.counterVariable;
}
public void setCounterVariable(int someVariable) {
this.counterVariable = someVariable;
}
}
add the App to the manifest:
<application
android:name="MyApplication"
android:icon="#drawable/icon"
android:label="#string/app_name">
Then in your activities get and set the variable like so:
// cast to Application and call the setter
((MyApplication) this.getApplication()).counterVariable(1);
// cast to Application and call the getter
int counter = ((MyApplication) this.getApplication()).getCounterVariable ();
Please use the below code:
// Generalized form of Avoiding the Static value holding:
public class SPDataHandler {
private Context mContext;
private SharedPreferences mPreference;
public SPDataHandler(Context context) {
this.mContext = context;
this.mPreference = mContext.getSharedPreferences("SAMPLE_SP", Context.MODE_PRIVATE);
}
/**
* COMMON SETTER FOR INTEGER DATA
*/
private void setIntegerData(String key, int value) {
SharedPreferences.Editor editor = mPreference.edit();
editor.putInt(key, value);
editor.commit();
}
/**
* COMMON GETTER FOR INTEGER SP DATA
*/
private int getIntegerSpData(String key, int defaultValue) {
return this.mPreference.getInt(key, defaultValue);
}
// Your Getter and Setter
public int getmCount() {
return this.getIntegerSpData("Count", 1);
}
public void setmCount(int cont) {
this.setIntegerData("Count", cont);
}
}
// Your Activity A
SPDataHandler handler = new SPDataHandler(this);
int count = handler.getmCount();
cmdOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count = count + 1;
handler.setmCount(count); // Change the logic based on your requirement
if (count == 5)
{
tagihan.txtShip1.setTextColor(Color.parseColor("#000000"));
tagihan.txtNilai1.setTextColor(Color.parseColor("#000000"));
tagihan.txtSupir1.setTextColor(Color.parseColor("#000000"));
}
}
// Your Activity B
SPDataHandler handler = new SPDataHandler(this);
int count = handler.getmCount();
cmdSuccess.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count = count + 1;
handler.setmCount(count); // Change the logic based on your requirement
if (count == 5)
{
tagihan.txtShip1.setTextColor(Color.parseColor("#000000"));
tagihan.txtNilai1.setTextColor(Color.parseColor("#000000"));
tagihan.txtSupir1.setTextColor(Color.parseColor("#000000"));
}
}
Related
I used the same process for sending data between fragments and it works but now I'm not getting data in Receiver Activity. Even the Log message Tag is not showing as I click on submit button. I checked in Sender Activity Log message and it is showing data but can't get those data in Receiver Activity.
Please help me to get data. Thank you!!
ViewModel Class:
public class ViewModelClass extends ViewModel {
private final MutableLiveData message = new MutableLiveData();
public void setMessage(HomeModelClass data){
message.setValue(data);
}
public MutableLiveData getMessage() {
return message;
}
}
Sender Activity:
public class EditHomeData extends AppCompatActivity {
private ViewModelClass viewModelClass;
HomeModelClass homeModelClassData = new HomeModelClass();
#Override
protected void onCreate(Bundle savedInsatancestate) {
super.onCreate(savedInsatancestate);
setContentView(R.layout.first_page);
viewModelClass = ViewModelProviders.of(this).get(ViewModelClass.class);
setValues();
});
public void setValues() {
if (yes.isChecked()) {
rent_value = String.valueOf(1);
} else if (no.isChecked()) {
rent_value = String.valueOf(0);
}
homeModelClassData.setWard_id(ward_id + "");
homeModelClassData.setToleName(tole_name.getText().toString());
homeModelClassData.setHouseAge(house_age.getText().toString());
homeModelClassData.setRadio(rent_value);
homeModelClassData.setTotal_tenant(editText1.getText().toString());
homeModelClassData.setMale_tenant(editText2.getText().toString());
homeModelClassData.setFemale_tenant(editText3.getText().toString());
homeModelClassData.setHouse_stroyes(spi1);
homeModelClassData.setRoof_types(spi2);
homeModelClassData.setLatitude(lati.getText().toString());
homeModelClassData.setLongitude(longi.getText().toString());
viewModelClass.setMessage(homeModelClassData);
}
Receiver Activity:
public class EditHomeData3 extends AppCompatActivity {
Button submit, cancel;
String ward_id, houseNumber, toleName, house_age, radio, total_tenant, male_tenant, female_tenant, house_stroyes,
roof_types, latitude, longitude, value_updateby;
#Override
protected void onCreate(Bundle savedInsatancestate) {
super.onCreate(savedInsatancestate);
setContentView(R.layout.third_page);
submit = findViewById(R.id.submit_btn);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getDatafromField();
}
});
private void getDatafromField() {
final ViewModelClass model = ViewModelProviders.of(this).get(ViewModelClass.class);
model.getMessage().observe(this, new Observer() {
#Override
public void onChanged(#Nullable Object o) {
if (o instanceof HomeModelClass) {
HomeModelClass homedata = (HomeModelClass) o;
ward_id = homedata.getWard_id();
houseNumber = homedata.getHouseNumber();
toleName = homedata.getToleName();
house_age = homedata.getHouseAge();
radio = homedata.getRadio();
total_tenant = homedata.getTotal_tenant();
male_tenant = homedata.getMale_tenant();
female_tenant = homedata.getFemale_tenant();
house_stroyes = homedata.getHouse_stroyes();
roof_types = homedata.getRoof_types();
latitude = homedata.getLatitude();
longitude = homedata.getLongitude();
value_updateby = String.valueOf("1");
Log.i("GetMessage", houseNumber +"");
}
}
});
}
ViewModels are not shared across Activities - since you pass a different object to ViewModelProviders.of(), you'll get different ViewModel instances.
This was specifically called out in the Single Activity: Why, When, and How talk as a reason to prefer a single Activity architecture in your app.
Yes Indeed, ViewModel are not shared across activities,So either you create different viewmodel for different activies or you could use different fragment with same viewmodel. Because in fragment you can achieved using SharedViewModel
First of all: I searched for my question in StackOverflow.
Android - Using Shared Preferences in separate class?
And I get null expectation.
I am making a simple 2D game for Android Platform. I have to set only one level value for making this game. For making my game; I have created 3 activities. First activity; Takes the level number, and pass to the second one ( playground ). After that; İf gaming is passed, The second activity pass to the third. And When the user clicks to button level will be up ( +1 ). Level number is always 1 or 1 more than. I used to Shared Preference for saving my value but I does not work. How can I do it?
Here is my codes :
public class shared_level {
int level = 1;
private static Context context;
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public final static String PREFS_NAME = "Level_preference_name";
public static void setInt( String key, int level) {
SharedPreferences sharedPref = context.getSharedPreferences(PREFS_NAME,0);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(key, level);
editor.apply();
}
public static int getInt(String key) {
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
return prefs.getInt(key, 0 );
}
}
First actvitiy :
final shared_level shared_level =new shared_level();
Toast.makeText(this, "" + shared_level.getLevel(), Toast.LENGTH_SHORT).show();
pass_to_second.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent git = new Intent(getApplicationContext(), second.class);
git.putExtra("level" ,String.valueOf(shared_level.getLevel()) );
startActivity(git);
MainActivity.this.finish();
}
});
}
Second activity :
Bundle extras = getIntent().getExtras();
final String value = extras.getString("level");
Toast.makeText(this, "Level is : " + " " + value, Toast.LENGTH_SHORT).show();
sayı.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent git = new Intent(getApplicationContext(), third.class);
git.putExtra("level", String.valueOf(value));
startActivity(git);
second.this.finish();
}
});
Third's button activity goes to first :
Bundle extras = getIntent().getExtras();
final String value = extras.getString("level");
final shared_level shared_level =new shared_level();
int new_level =Integer.valueOf(value) + 1;
shared_level.setLevel(new_level);
Toast.makeText(this, "" + shared_level.getLevel(), Toast.LENGTH_SHORT).show();
sayım.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
third.this.finish();
}
});
You should pass context to shared_level class via the constructor.
public class shared_level {
private Context context;
public shared_level(Context context) {
this.context = context;
}
...
}
and create the instance of shared_level class like:
final shared_level shared_level = new shared_level(yourActivity.this);
I have shared prefs to be used throughout my app but right now only four activities. The first activity is a recyclerview with checkboxes and the checked status is saved (in the recycler adapter) for each checkbox using a shared prefs helper class. The next activity is then launched as a tablayout with fragments containing a list of random items.
When the user clicks any of these items in the second activity's fragment, a third activity is launched. Here, I try to retrieve the values from the shared prefs helper class but it returns null, same situation in fourth activity too. Also, when I back press twice to first activity, it also returns null.
I would post my code for all activities but that would just make the question lengthy. Here's my helper class:
public class WalpyPrefsHelper {
public Context context;
public SharedPreferences customizePrefs, tabsCountPrefs;
public SharedPreferences.Editor editor, tabsEditor;
public static final String CUSTOMIZE_TABS_PREFS = "customizeTabsPrefs";
public static final String COUNT_TABS_PREFS = "countTabsPrefs";
public static final String KEY_NATURE = "nature";
public static final String KEY_SPACE = "space";
public static final String KEY_SEASONS = "seasons";
public static final String KEY_ART = "art";
public static final String KEY_SCIFI = "sci_fi";
public static final String KEY_MISC = "misc";
public static final String KEY_COUNT = "count_tabs";
public WalpyPrefsHelper(Context context) {
this.context = context;
customizePrefs = context.getSharedPreferences(CUSTOMIZE_TABS_PREFS, Context.MODE_PRIVATE);
editor = customizePrefs.edit();
tabsCountPrefs = context.getSharedPreferences(COUNT_TABS_PREFS, Context.MODE_PRIVATE);
tabsEditor = tabsCountPrefs.edit();
}
public void saveNaturePrefs(String s){
editor.putString(KEY_NATURE, s).apply();
}
public String getKeyNature(){
return customizePrefs.getString(KEY_NATURE, null);
}
public void removeNaturePrefs(){
editor.remove(KEY_NATURE).apply();
}
public void saveSpacePrefs(String s){
editor.putString(KEY_SPACE, s).apply();
}
public String getKeySpace(){
return customizePrefs.getString(KEY_SPACE, null);
}
public void removeSpacePrefs(){
editor.remove(KEY_SPACE).apply();
}
public void saveSeasonsPrefs(String s){
editor.putString(KEY_SEASONS, s).apply();
}
public String getKeySeasons(){
return customizePrefs.getString(KEY_SEASONS, null);
}
public void removeSeasonPrefs(){
editor.remove(KEY_SEASONS).apply();
}
public void saveArtPrefs(String s){
editor.putString(KEY_ART, s).apply();
}
public String getKeyArt(){
return customizePrefs.getString(KEY_ART, null);
}
public void removeArtPrefs(){
editor.remove(KEY_ART).apply();
}
public void saveSci_FiPrefs(String s){
editor.putString(KEY_SCIFI, s).apply();
}
public String getKeyScifi(){
return customizePrefs.getString(KEY_SCIFI, null);
}
public void removeSci_FiPrefs(){
editor.remove(KEY_SCIFI).apply();
}
public void saveMiscPrefs(String s){
editor.putString(KEY_MISC, s).apply();
}
public String getKeyMisc(){
return customizePrefs.getString(KEY_MISC, null);
}
public void removeMiscPrefs(){
editor.remove(KEY_MISC).apply();
}
public void removeAllPrefs(){
editor.remove(KEY_NATURE).apply();
editor.remove(KEY_SPACE).apply();
editor.remove(KEY_SEASONS).apply();
editor.remove(KEY_ART).apply();
editor.remove(KEY_SCIFI).apply();
editor.remove(KEY_MISC).apply();
}
public void saveCount(int count) {
tabsEditor.putInt(KEY_COUNT, count).apply();
}
public int getSaveCount(){
return tabsCountPrefs.getInt(KEY_COUNT, 0);
}
}
The preferences are saved in first activity recycler adapter like below snippet:
viewholder.customizeSelImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String nature, space, seasons, art, scifi, misc;
switch (position) {
case 0:
nature = prefsHelper.getKeyNature();
if (viewholder.customiseCheckBox.isChecked()) {
viewholder.customiseCheckBox.setChecked(false);
viewholder.customiseCheckBox.setVisibility(View.INVISIBLE);
if (nature != null) {
prefsHelper.removeNaturePrefs(); // infer nullity
if (count > 0) {
count--;
Log.d(TAG, "Count Value:\t" + count);
}
Log.d(TAG, "Position:\t" + position + " is UNChecked");
}
} else {
viewholder.customiseCheckBox.setChecked(true);
viewholder.customiseCheckBox.setVisibility(View.VISIBLE);
count ++;
Log.d(TAG, "Count Value:\t" + count);
prefsHelper.saveNaturePrefs(Constants.NATURE); // save value. Works fine
Log.d(TAG, "Position:\t" + position + " is Checked");
}
break;
In next activity, I am able to retrieve the shared prefs values like below snippet:
String space = prefsHelper.getKeySpace();
String nature = prefsHelper.getKeyNature();
String seasons = prefsHelper.getKeySeasons();
String art = prefsHelper.getKeyArt();
String scifi = prefsHelper.getKeyScifi();
String misc = prefsHelper.getKeyMisc();
after initializing like this: prefsHelper = new WalpyPrefsHelper(this); but in third and fourth activities, those strings above return null values.
----Edited Part---
Second Activity Where Prefs Are Used:
public void setUpTabs() {
prefsHelper = new WalpyPrefsHelper(this);
int count = prefsHelper.getSaveCount();
Log.d(TAG, "Tabs Count:\t" + count);
setUpViewPager(viewPager);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
tabLayout.setupWithViewPager(viewPager);
}
private void setUpViewPager(ViewPager viewPager) {
space = prefsHelper.getKeySpace();
nature = prefsHelper.getKeyNature();
seasons = prefsHelper.getKeySeasons();
art = prefsHelper.getKeyArt();
scifi = prefsHelper.getKeyScifi();
misc = prefsHelper.getKeyMisc();
pagerAdapter = new TabsPagerAdapter(getSupportFragmentManager(), this);
pagerAdapter.addTab(new Top30Fragment(), Constants.Top30);
if (nature != null) {
pagerAdapter.addTab(new NatureFragment(), Constants.NATURE);
}
if(space != null){
pagerAdapter.addTab(new SpaceFragment(), Constants.SPACE);
}
if (seasons != null){
pagerAdapter.addTab(new SeasonsFragment(), Constants.SEASONS);
}
if (art != null){
pagerAdapter.addTab(new ArtFragment(), Constants.ART);
}
if (scifi != null){
pagerAdapter.addTab(new SciFiFragment(), Constants.SCI_FI);
}
if (misc != null){
pagerAdapter.addTab(new MiscFragment(), Constants.MISC);
}
pagerAdapter.addTabAtLastPosition(new PrefsFragment(), Constants.PREFS);
viewPager.setAdapter(pagerAdapter);
}
I have used shared prefs to set the tablayout at app install time but after navigating other activities and back to this, those tabs from prefs are removed, in other scenarios, my last tab then contains the view and data of the nature fragment from prefs.
In adapter and last two activities in sequence, I am getting the key like this but it returns null:
prefsHelper = new WalpyPrefsHelper(this);
Log.d(TAG, "Nature Key:\t" + prefsHelper.getKeyNature());
Also, in the adapter, the value returns null and in other subsequent activities after the second activity. Is this sharedprefs behavior, I have misconfigured somewhere or sharedprefs can't be passed from activity to fragment and adapter context?
I have tried .apply() and .commit() for the editor but same situation occurs.
Anyone understands why? Thanks.
I have fixed this problem by using sqlite to persist and retrieve the values.
Looking at the attached code flow, I could not find any problematic parts. Although each activity has a preference manager class instance created and used, the SharedPrefenrece object itself is shared as one object, so that is not a problem.
Please check again whether the preference value is deleted or not in the flow.
Also, if you attach the part that uses prefsHelper in each activity, troubleshooting will be helpful.
I have a login form with a checkbox to let the app remember the email in LoginActivity. If I press the Log in button the email should be stored in SharedPreferences using the class AppPreferences.
The app remembers the email if I return to home screen by pressing home button and by pressing back.
But if I force close the app shows the default value as defined in the Preferencemanager.getString("value", "default_value"); method.
I have tried a lot of things people suggested on SO, but unfortunately none of the solutions worked. I even tried to solve it by putting all the SharedPreferences code in a separate class (see this question).
Below I put as much code relevant to the question. So both the classes LoginActivity and AppPreferences. There is no error message given by LogCat.
At both the Samsung devices I9100 and P3110 with Android 4.2.2 Cyanogenmod 10.1 and several different emulators this problem occurs. (I read some Samsung S devices with HoneyComb could't save SharedPreferences properly?)
EDIT:
As I forgot to mention, the project is targeted to API 17 and the minSdkVersion = 11. I only save credentials on click of Log in button.
EDIT 2: This problem also occurs if phone reboots
the LoginActivity class:
public class LoginActivity extends Activity
{
private static final String PREF_REMEMBER_EMAIL = "LoginCredentialsRememberEmail";
private static final String PREF_EMAIL = "LoginCredentialsEmail";
private String mEmail;
private EditText mEmailView;
private CheckBox cbRememberEmail;
private AppPreferences appPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
appPreferences = new AppPreferences(LoginActivity.this);
loadUserCredentials();
}
#Override
protected void onResume() {
super.onResume();
loadUserCredentials();
}
#Override
protected void onStart() {
super.onStart();
loadUserCredentials();
}
private void loadUserCredentials() {
String rememberEmail = appPreferences.getPreferenceString(PREF_REMEMBER_EMAIL);
String email = appPreferences.getPreferenceString(PREF_EMAIL);
mEmailView = (EditText) findViewById(R.id.email);
mEmailView.setText((rememberEmail == "1") ? email : "");
cbRememberEmail = (CheckBox) findViewById(R.id.cbRememberEmail);
cbRememberEmail.setChecked(rememberEmail == "1" ? true : false);
mEmail = mPassword = "";
}
private void saveUserCredentials() {
try {
String rememberemail = (((CheckBox) findViewById(R.id.cbRememberEmail)).isChecked()) ? "1" : "0";
appPreferences.setPreferenceString(PREF_REMEMBER_EMAIL, rememberemail);
String email = (rememberemail == "1") ? mEmail : "";
appPreferences.setPreferenceString(PREF_EMAIL, email);
}
public void cbRememberEmailClick(View view) {
boolean checked = ((CheckBox) findViewById(R.id.cbRememberEmail)).isChecked();
if (checked) {
new AlertDialog.Builder(this).setTitle(R.string.remember_email_notification_title).setMessage(R.string.remember_email_notification_message).setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
((CheckBox) findViewById(R.id.cbRememberEmail)).setChecked(true);
}
}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
((CheckBox) findViewById(R.id.cbRememberEmail)).setChecked(false);
}
}).show();
}
}
// ...
}
The AppPreferences class:
public class AppPreferences {
Context context;
private SharedPreferences settings = null;
private static String LOGIN_CREDENTIALS = "com.example.login.credentials";
private static String DEFAULT_STRING = "";
public AppPreferences(Context context) {
this.context = context;
settings = PreferenceManager.getDefaultSharedPreferences(context);
}
private String getKey(String key) {
return LOGIN_CREDENTIALS + "." + key;
}
public String getPreferenceString(String key) {
return settings.getString(getKey(key), DEFAULT_STRING);
}
public void setPreferenceString(String key, String value) throws Exception {
SharedPreferences.Editor editor = settings.edit();
editor.putString(getKey(key), (String) value);
editor.commit();
}
// ...
}
Any help is really appreciated, I'm stuck at this for days and it's really frustrating now.
Thanks in advance.
Dediqated
You don't show the code that calls saveUserCredentials. You should call it in onPause:
#Override
protected void onPause() {
super.onPause();
saveUserCredentials();
}
If you call it in one of the later lifecycle methods (such as onDestroy), it won't be called if the app is force-closed while in the background. (You can defer this to onStop if you are targeting only Honeycomb and later.)
i fixed it by changing the field rememberEmail to a Boolean instead of a string containing a 1 or 0. I dont know why this didn't work but I'm happier about the fact that after 11 days of frustration this is no issue anymore.
Also did I delete all the preference files in folder /data/data/com.example/shared_prefs/
changed code in LoginActivity
// ....
private void loadUserCredentials() {
Boolean rememberEmail = appPreferences.getPreferenceBoolean(PREF_REMEMBER_EMAIL);
String email = appPreferences.getPreferenceString(PREF_EMAIL);
mEmailView = (EditText) findViewById(R.id.email);
mEmailView.setText(rememberEmail ? email : "");
cbRememberEmail = (CheckBox) findViewById(R.id.cbRememberEmail);
cbRememberEmail.setChecked(rememberEmail);
}
private void saveUserCredentials() {
try {
Boolean rememberEmail = ((CheckBox) findViewById(R.id.cbRememberEmail)).isChecked();
appPreferences.setPreferenceBoolean(PREF_REMEMBER_EMAIL, rememberEmail);
String email = (rememberEmail) ? mEmail : "";
appPreferences.setPreferenceString(PREF_EMAIL, email);
}
// ....
and in AppPreferences
// ....
private String getKey(String key) {
key = key.toLowerCase();
return LOGIN_CREDENTIALS + "." + key;
}
// newly added methods below
public String getPreferenceBoolean(String key) {
return settings.getBoolean(getKey(key), DEFAULT_BOOLEAN);
}
public void setPreferenceBoolean(String key, Boolean value) throws Exception {
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(getKey(key), (Boolean) value);
editor.commit();
}
// ....
I hope you won't make the same mistake as I did ;)
I'd recommend you, putting the save method into the onDestroy method
If you are calling saveUserCredentials(); when ever checkbox is checked,This should work perfectly.Also try to initialise preference obj on start of application
I am in a single class, using 2 different methods.
In one method I have:
private void detect();
int facesFound = detector.findFaces(bitmap565, faces);
detector, bitmap565 and faces are all defined in the same method.
In another method, I would like to call the value of facesFound.
So:
private void crop(){
if (facesFound > 1){
}
My issue is, I cannot access that integer from the method because it is cast locally. What is my best way to alter my code to call it?
Edit: to add method:
private final View.OnClickListener btnClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.action_button:
crop();
So are you saying declare an integer at the top of my class that is defined as getting the integer passed back through my new private int detect() method?
Change detect() and crop() to:
private int detect()
{
return detector.findFaces(bitmap565, faces);
}
private void crop(int numberOfFacesFound)
{
if(numberOfFacesFound > 1)
{
}
}
Then, wherever you are calling crop() from:
int numberOfFacesFound = detect();
crop(numberOfFacesFound);