I am having a project which uses Shared Preferences for Session Management. Everything is fine with the code but what really annoying is that the app is holding the session in Android Lollipop and above but unfortunately it is not holding the same for Android Kitkat and below. The session is lost whenever the app is closed and you have to lo in again. Following are the codes, I am using:
Session.java
package com.saptak.disputesession;
import android.content.Context;
import android.content.SharedPreferences;
import java.util.HashMap;
/**
* Created by Saptak Das on 27-02-2017.
*/
public class Session {
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
Context context;
public static String KEY_FNAME="namef";
public static String KEY_LNAME="namel";
public static String IS_LOGIN;
public Session(Context context) {
this.context = context;
sharedPreferences=context.getSharedPreferences("userdetails",0);
editor=sharedPreferences.edit();
}
public void CreateLoginSession(String fname,String lname)
{
editor.putString(KEY_FNAME,fname);
editor.putString(KEY_LNAME,lname);
editor.putString(IS_LOGIN,"logged");
editor.commit();
}
public HashMap<String,String> getdetails()
{
HashMap<String,String> details=new HashMap<>();
details.put(KEY_FNAME,sharedPreferences.getString(KEY_FNAME,null));
details.put(KEY_LNAME,sharedPreferences.getString(KEY_LNAME,null));
return details;
}
public boolean loginstatus()
{
if(sharedPreferences.getString(IS_LOGIN,"unlogged").equals("logged"))
{
return true;
}
else
{
return false;
}
}
public void logoutac()
{
editor.clear();
editor.commit();
}
}
Login.java
package com.saptak.disputesession;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
/**
* Created by Saptak Das on 27-02-2017.
*/
public class Login extends Activity {
Button login;
EditText first,last;
Session session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
session=new Session(getApplicationContext());
login=(Button)findViewById(R.id.log);
first=(EditText)findViewById(R.id.fname);
last=(EditText)findViewById(R.id.lname);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
session.CreateLoginSession(first.getText().toString(),last.getText().toString());
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
}
});
}
}
MainActivity.java
package com.saptak.disputesession;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
Session session;
Boolean flag;
TextView tf,tl;
Button logout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
session=new Session(getApplicationContext());
tf=(TextView)findViewById(R.id.xfname);
tl=(TextView)findViewById(R.id.xlname);
logout=(Button)findViewById(R.id.xlogout);
flag=session.loginstatus();
if(flag==false)
{
startActivity(new Intent(getApplicationContext(),Login.class));
finish();
}
HashMap<String,String> details=session.getdetails();
tf.setText(details.get(Session.KEY_FNAME));
tl.setText(details.get(Session.KEY_LNAME));
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
session.logoutac();
startActivity(new Intent(getApplicationContext(),Login.class));
finish();
}
});
}
}
This problem is getting on my nerves now as the app is perfectly coded, please help me out. Thanks in advance!
Update:
Please note, the problem is not about deleting the session, its completely opposite. The session is logging itself out everytime i am closing the app. and this problem is only in case of Android Kitkat and below, works fine for Android Lollipop and above
SharedPreferences allow you to save and retrieve data in the form of key,value pair.
Mistake
public static String IS_LOGIN="logged"; // Init here
FYI
Session are useful when you want to store user data globally through
out the application.
Rectify your method
public void CreateLoginSession(String fname,String lname)
{
editor.remove(KEY_FNAME); //Remove at first
editor.remove(KEY_LNAME);
editor.remove(IS_LOGIN);
editor.putString(KEY_FNAME,fname);
editor.putString(KEY_LNAME,lname);
editor.putString(IS_LOGIN,"logged");
editor.commit();
}
Related
I want to fill the TextView of another activity based on preference on checkBox event but its working please help me to sort the issue..It is forcefully stopping.Please help in the if else statement part .what we need to write in activity 2 to select based on the checkBox in activity 1
Activity 1:
package com.example.rajatanurag.shoppingsites;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
public class Book extends AppCompatActivity {
Button b1,b2;
public static CheckBox cb1,cb2,cb3;
TextView tv1,tv2,tv3;
SharedPreferences sp1;
ImageView iv1,iv2,iv3;
String x,y,z;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
b1=(Button)findViewById(R.id.b1);
b2=(Button)findViewById(R.id.b2);
cb1=(CheckBox)findViewById(R.id.cb1);
cb2=(CheckBox)findViewById(R.id.cb2);
cb3=(CheckBox)findViewById(R.id.cb3);
tv1=(TextView)findViewById(R.id.tv4);
tv2=(TextView)findViewById(R.id.tv2);
tv3=(TextView)findViewById(R.id.tv3);
iv1=(ImageView)findViewById(R.id.iv1);
iv2=(ImageView)findViewById(R.id.iv2);
iv3=(ImageView)findViewById(R.id.iv3);
sp1=getSharedPreferences("SHOPPING",MODE_PRIVATE);
}
public void OnClick1(View view)
{
SharedPreferences.Editor editor = sp1.edit();
if(cb1.isChecked()==true) {
editor.putString("price1", tv1.getText().toString());
editor.putBoolean("x",true);
}
if(cb2.isChecked()==true)
{
editor.putString("price2",tv2.getText().toString());
editor.putBoolean("y",true);
}
if(cb3.isChecked()==true)
{
editor.putString("price3",tv3.getText().toString());
editor.putBoolean("z",true);
}
editor.commit();
Intent i=new Intent(this,MyCart.class);
startActivity(i);
}
}
2.Activity
package com.example.rajatanurag.shoppingsites;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MyCart extends AppCompatActivity {
SharedPreferences sp1;
TextView tv4,tv5,tv6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_cart);
tv4=(TextView)findViewById(R.id.tv4);
sp1=getSharedPreferences("SHOPPING",MODE_PRIVATE);
if(Book.cb1.isChecked()==true){
String price11 = sp1.getString("price1", "");
tv4.setText(price11);
}
if(Book.cb1.isChecked()==true){
String price21=sp1.getString("price2","");
tv5.setText(price21);
}
if(Book.cb1.isChecked()==true){
String price31=sp1.getString("price3","");
tv6.setText(price31);
}
}
}
You shouldn't be using static variables for view members because you might get memory leaks. Also the views you are referencing are destroyed when activity is destroyed, so they are not accessible in your second activity. You can send checkboxes checked values as intent extras.
Put this in your Activity 1 in OnClick1() method:
Intent i=new Intent(this,MyCart.class);
i.putExtra("cb1", cb1.isChecked());
i.putExtra("cb2", cb2.isChecked());
i.putExtra("cb3", cb3.isChecked());
startActivity(i);
This is how you get values in Activity 2 (in onCreate() method):
Intent intent = getIntent();
if(intent.getBooleanExtra("cb1", false)){
String price11 = sp1.getString("price1", "");
tv4.setText(price11);
}
if(intent.getBooleanExtra("cb2", false)){
String price21=sp1.getString("price2","");
tv5.setText(price21);
}
if(intent.getBooleanExtra("cb3", false)){
String price31=sp1.getString("price3","");
tv6.setText(price31);
}
public void OnClick1(View view)
{
if(view.getID() == R.id.cb1)
{
if(cb1.isChecked())
editor.putBoolean("x",true);
else
editor.putBoolean("x",false);
}
}
In your second activity
sp1=getSharedPreferences("SHOPPING",MODE_PRIVATE);
boolean isChecked = sp1.getBoolean("x", false);
if(isChecked){
String price11 = sp1.getString("price1", "");
tv4.setText(price11);
}
I was learning to make a simple login app from youtube, however, when I build the code, although the app runs quite fine but it never assigns the value of 3 to the attempt counter later in the code, only the layout is visible and hence login doesn't work. Can you please help me? If you need any other file, write it in comment, I'll upload it later. Thanks.
package com.shubham.splashscreenemulation;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class UserLogin extends AppCompatActivity {
private static EditText username;
private static EditText password;
private static TextView attempts_left;
private static Button login_btn;
int attempt_counter = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
}
public void LoginButton(){
username = (EditText)findViewById(R.id.editText_user);
password = (EditText)findViewById(R.id.editText_password);
attempts_left = (TextView)findViewById(R.id.textView_attempt_count);
login_btn = (Button)findViewById(R.id.button_login);
attempts_left.setText(Integer.toString(attempt_counter));
login_btn.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
if(username.getText().toString().equals("Shubh") && password.getText().toString().equals("adidev"))
{
Toast.makeText(UserLogin.this, "Login credentials are correct!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent("com.shubham.splashscreenemulation.SplashScreen");
startActivity(intent);
}
else
{
Toast.makeText(UserLogin.this, "Login credentials are not correct!", Toast.LENGTH_SHORT).show();
attempt_counter--;
attempts_left.setText(Integer.toString(attempt_counter));
if(attempt_counter == 0)
{
login_btn.setEnabled(false);
}
}
}
}
);
}
}
You don't call the function LoginButton() in your Activity.
Here some tips : function name starts with lowercase letter like loginButton ( with camelCase ), classes names starts with uppercase letter like AppCompatActivity. This tip is for more readability for the code. Why do you declare Views as static in that function?
package com.shubham.splashscreenemulation;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class UserLogin extends AppCompatActivity {
private static EditText username;
private static EditText password;
private static TextView attempts_left;
private static Button login_btn;
int attempt_counter = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
LoginButton();
}
public void LoginButton(){
username = (EditText)findViewById(R.id.editText_user);
password = (EditText)findViewById(R.id.editText_password);
attempts_left = (TextView)findViewById(R.id.textView_attempt_count);
login_btn = (Button)findViewById(R.id.button_login);
attempts_left.setText(Integer.toString(attempt_counter));
login_btn.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
if(username.getText().toString().equals("Shubh") && password.getText().toString().equals("adidev"))
{
Toast.makeText(UserLogin.this, "Login credentials are correct!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent("com.shubham.splashscreenemulation.SplashScreen");
startActivity(intent);
}
else
{
Toast.makeText(UserLogin.this, "Login credentials are not correct!", Toast.LENGTH_SHORT).show();
attempt_counter--;
attempts_left.setText(Integer.toString(attempt_counter));
if(attempt_counter == 0)
{
login_btn.setEnabled(false);
}
}
}
}
);
}
You can add LoginButton() after setContentView or remove the LoginButton method, move everything inside onCreate.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
username = (EditText)findViewById(R.id.editText_user);
password = (EditText)findViewById(R.id.editText_password);
attempts_left = (TextView)findViewById(R.id.textView_attempt_count);
login_btn = (Button)findViewById(R.id.button_login);
attempts_left.setText(Integer.toString(attempt_counter));
login_btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if(username.getText().toString().equals("Shubh") && password.getText().toString().equals("adidev"))
{
Toast.makeText(UserLogin.this, "Login credentials are correct!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent("com.shubham.splashscreenemulation.SplashScreen");
startActivity(intent);
}
else
{
Toast.makeText(UserLogin.this, "Login credentials are not correct!", Toast.LENGTH_SHORT).show();
attempt_counter--; attempts_left.setText(Integer.toString(attempt_counter));
if(attempt_counter == 0)
{
login_btn.setEnabled(false);
}
}
}
});
}
You can also change your setText to this attempts_left.setText(attempt_counter+"");
I'm working on a Android App and the layout and all the "android" specific stuff made a friend of my. I only was responsible for the "app" itself.
Nevertheless,
I would like to change some settings, e.g. change the server the stats produced by the app, should be transfered.
Here is the Settings.java:
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Date;
public class Settings extends Activity {
private Context mContext;
private SharedPreferences mPrefs;
private SharedPreferences.Editor mPrefEditor;
private EditText textName, textIP;
private RadioButton rdOnline, rdOffline;
private RadioGroup rdGroup;
private Button butSpeichern;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
setContentView(R.layout.activity_settings);
mPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
mPrefEditor = mPrefs.edit();
textName = (EditText) findViewById(R.id.txtBenutzer);
textIP = (EditText) findViewById(R.id.txtIP);
rdOffline = (RadioButton) findViewById(R.id.rdOffline);
rdOnline = (RadioButton) findViewById(R.id.rdOnline);
rdGroup = (RadioGroup) findViewById(R.id.radioDB);
butSpeichern = (Button) findViewById(R.id.btnSpeichern);
butSpeichern.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveSettings();
}
});
//Online default an
rdOnline.setChecked(true);
rdOffline.setChecked(false);
loadSettings();
//ggf. Lan
System.out.println("online");
if(automatischLAN()){
setLan();
}
}
private void saveSettings()
{
mPrefEditor.putBoolean("onlineDB", rdOnline.isChecked());
mPrefEditor.putString("benutzer", textName.getText().toString());
mPrefEditor.putString("ip", textIP.getText().toString());
mPrefEditor.apply();
finish();
}
private void loadSettings() {
textName.setText(mPrefs.getString("benutzer", ""));
textIP.setText(mPrefs.getString("ip", "192.168.0.50"));
rdOnline.setChecked(mPrefs.getBoolean("onlineDB", true));
rdOffline.setChecked(!mPrefs.getBoolean("onlineDB", true));
}
public boolean automatischLAN(){
Calendar cal = new GregorianCalendar();
Date currenttimen = new Date();
cal.setTime(currenttimen);
int freitag = cal.get(Calendar.DAY_OF_WEEK);
int STUNDE = 0;
STUNDE = cal.get(Calendar.HOUR_OF_DAY);
System.out.println(STUNDE);
if(freitag == Calendar.FRIDAY && STUNDE>11 && STUNDE< 14 ) {
System.out.println("lan");
return false;
}
else {
System.out.println("online");
return true;
}
}
public void onBackPressed()
{
saveSettings();
super.onBackPressed();
}
public void setLan(){
rdOnline.setChecked(false);
rdOffline.setChecked(true);
System.out.println("sollte lan sein");
mPrefEditor.putBoolean("onlineDB", rdOnline.isChecked());
}
}
I'm afraid my setLan() method isn't working as the values are not stored in the prefs...
What is the easieast way to check prefs and chance them on each start of the app?
Thanks for your help
You have to commit the changes in the SharedPreference.Editor variable. Replace your function above with the given one
public void setLan(){
rdOnline.setChecked(false);
rdOffline.setChecked(true);
System.out.println("sollte lan sein");
mPrefEditor.putBoolean("onlineDB", rdOnline.isChecked());
mPrefEditor.apply();
}
I am developing an android app, where the user should be able to log in with a Facebook account. The application has worked in the first 5-10 min. I could see the layout where i was prompted to give/deny permissions.
When i try to log in, it shows me the "Loading" message from Facebook API but then returns to the previous layout.
The error message i receive is: "Should not pass a read () permission to a request for publish or manage authorization".
I appreciate any help to resolve this issue..
package com.kampusbilisim.sencebence;
import java.io.*;
import java.net.*;
import org.json.*;
import com.facebook.android.*;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.Facebook.DialogListener;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.*;
import android.util.Log;
import android.view.*;
import android.widget.*;
#SuppressWarnings("deprecation")
public class FullscreenActivity extends Activity {
String TAG = "SenceBence";
private static String APP_ID = "659712077445489";
private Facebook facebook;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
Button btnFbLogin;
private AsyncFacebookRunner mAsyncRunner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_fullscreen);
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
btnFbLogin = (Button) findViewById(R.id.button1);
btnFbLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loginToFacebook();
Toast.makeText(FullscreenActivity.this, "Logging in.. ", Toast.LENGTH_SHORT).show();
}
});
TextView tv = (TextView) findViewById(R.id.girisyazisibeyaz);
tv.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/AvenirNextLTPro-Bold.otf"));
}
#SuppressWarnings("deprecation")
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this, new String[] { "email" , "publish_actions", "publish_checkins", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires", facebook.getAccessExpires());
editor.commit();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
}
}
Sorry about this guys. This must be like the third question I've had to ask about this project alone. =(
What i want to be able to do is toggle the visibility of a radio button using a check box in a preferences activity.
There are no errors in my code and both activities run fine, but there is no change in visibility when the check box is checked or unchecked.
Here is my Activity with the radiobuttons
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import com.medialets.android.analytics.MMAnalyticsManager;
public class Temperature extends Activity {
MMAnalyticsManager mManager;
private EditText text;
public void onStart(Bundle savedInstanceState){
super.onStart();
getPrefs();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.temperature);
text = (EditText)findViewById(R.id.EditText01);
mManager = MMAnalyticsManager.sharedInstance(this);
mManager.start("codeHere", "1.0",
false);
}
#Override
public void onPause() {
super.onPause();
mManager.pause();
}
#Override
public void onResume() {
super.onResume();
mManager.resume();
}
#Override
public void onDestroy() {
super.onDestroy();
mManager.stop();
}
public void myClickHandler(View view){
switch (view.getId()) {
case R.id.Button01:
RadioButton celsiustokelvinButton = (RadioButton) findViewById (R.id.RadioButton05);
RadioButton celsiustofarenheitButton = (RadioButton) findViewById(R.id.RadioButton01);
RadioButton farenheittocelsiusButton = (RadioButton) findViewById(R.id.RadioButton02);
RadioButton farenheittokelvinButton = (RadioButton) findViewById(R.id.RadioButton06);
RadioButton kelvintocelsiusButton = (RadioButton) findViewById (R.id.RadioButton03);
RadioButton kelvintofarenheitButton=(RadioButton) findViewById (R.id.RadioButton04);
float inputValue = Float.parseFloat(text.getText().toString());
if (celsiustofarenheitButton.isChecked()) {
text.setText(String
.valueOf(convertCelsiusToFarenheit(inputValue)));
} if (farenheittocelsiusButton.isChecked()) {
text.setText(String
.valueOf(convertFarenheitToCelsius(inputValue)));
} if (celsiustokelvinButton.isChecked()) {
text.setText(String
.valueOf(convertCelsiusToKelvin(inputValue)));
} if (farenheittokelvinButton.isChecked()) {
text.setText(String
.valueOf(convertFarenheitToKelvin(inputValue)));
} if (kelvintocelsiusButton.isChecked()) {
text.setText(String
.valueOf(convertKelvinToCelsius(inputValue)));
} if (kelvintofarenheitButton.isChecked()) {
text.setText(String
.valueOf(convertKelvinToFarenheit(inputValue)));
}
break;
}}
private float convertFarenheitToCelsius(float fahrenheit){
return ((fahrenheit - 32) * 5 / 9);
}
private float convertCelsiusToFarenheit(float celsius){
return ((celsius * 9) / 5) + 32;
}
private double convertCelsiusToKelvin(float celsius){
return celsius + 273.15;
}
private double convertFarenheitToKelvin(float farenheit){
return ((farenheit-32)/(1.8));
}
private double convertKelvinToCelsius(float kelvin){
return kelvin-273.1;
}
private double convertKelvinToFarenheit(float kelvin){
return kelvin*1.8-459.67;
}
boolean CheckboxPreference;
private void getPrefs() {
// Get the xml/preferences.xml preferences
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
CheckboxPreference = prefs.getBoolean("checkboxPref", true);
}
}
And here is my Preferences Activity
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
public class Preferences extends PreferenceActivity {
private RadioButton btn01;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
btn01 = (RadioButton)findViewById(R.id.RadioButton01);
Preference customPref = (Preference) findPreference("customPref");
customPref.setOnPreferenceClickListener(new OnPreferenceClickListener(){
public boolean onPreferenceClick(Preference preference) {
Toast.makeText(getBaseContext(),"The Custom Preference Has Been Clicked",Toast.LENGTH_LONG).show();
SharedPreferences customSharedPreference = getSharedPreferences("myCutomSharedPrefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = customSharedPreference.edit();
editor.putString("myCustomPref","The preference has been clicked");
editor.commit();
CheckBox();
return true;
}
private void CheckBox() {
final CheckBox ThisCheckBox = (CheckBox) findViewById (R.id.checkboxPref);
ThisCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton compoundButton,boolean test) {
if (ThisCheckBox.isChecked()){
btn01.setVisibility(View.VISIBLE);
} else {
btn01.setVisibility(View.GONE);
}
}
});
};
});
}}
Sorry there is other stuff in there as well such as an analytics plug in
Anyone have any idea as to why this just isn't working
(Just a side note. When looking at the logcat, clicking the checkbox returned no results)
EDIT: OK i've just ammended my code as suggested but i'm afraid that the preferences still do not affect anything. Anybody have any ideas?? =(
It's not working because for visiblity the values you should use are (reference):
0 = VISIBLE
4 = INVISIBLE
8 = GONE