How to save the state of toggle button android - android

I need to save the information about the toggle button when the user kill the app or restarted i want to display the previous state of the button Thanks
public class MainActivity extends ActionBarActivity {
ToggleButton toggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android.support.v7.app.ActionBar menu = getSupportActionBar();
menu.setDisplayShowHomeEnabled(true);
menu.setLogo(R.mipmap.ic_launcher);
menu.setDisplayUseLogoEnabled(true);
}
#Override
protected void onResume() {
super.onResume();
toggle = (ToggleButton) findViewById(R.id.togglebutton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
enableNotifications();
} else {
makeDialog();
}
}
});
}

Use shared prefernces for the same.
togButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int notification_status = Integer.parseInt(mPreferences.getString("status", "-1"));
SharedPreferences.Editor editor=mPreferences.edit();
Log.i("notification_status="+notification_status,"888");
if(notification_status==-1){
editor.putString("status", "1");
holder.notification_btn.setBackgroundResource(R.drawable.notification_on);
//do your stuff
}else if(notification_status==1){
editor.putString("status", "0");
holder.notification_btn.setBackgroundResource(R.drawable.notification_off);
//do your stuff
}else if(notification_status==0){
editor.putString("status", "1");
holder.notification_btn.setBackgroundResource(R.drawable.notification_on);
//do your stuff
}
editor.commit();
}
});

Use shared preferences as following class
public class YourPreferenes {
private Context mContext;
private SharedPreferences mPrefs;
private static YourPreferenes mYourPreferenes;
private YourPreferenes(Context ctx){
mContext = ctx;
mPrefs = mContext.getSharedPreferences("ATSPreferenes", Context.MODE_PRIVATE);
}
public static ATSPreferenes getInstance(Context ctx){
if(mYourPreferenes == null){
mYourPreferenes = new YourPreferenes(ctx);
}
return mYourPreferenes;
}
public void setButtonState(boolean btnstate){
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean("btnstate", btnstate);
editor.commit();
}
public boolean getButtonState(){
return mPrefs.getBoolean("btnstate", false);
}
}
And get your saved togalbutton stat even you kill your app.

Related

SharedPreferences issue in Android Studio

I'm trying since 2 days and have exhaustively tried various things but I'm not able to get this work. Kindly help.
I have an Android Studio provided default Settings page where I have kept only 1 SwitchPreference where I intend to play or pause background music on all activities depending upon the Switch position.This is my Audio class.
public class AudioPlay {
public static MediaPlayer mediaPlayer;
private static SoundPool soundPool;
public static boolean isplayingAudio=false;
public static void playAudio(Context c, int id){
mediaPlayer = MediaPlayer.create(c,id);
soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
if(!mediaPlayer.isPlaying())
{ isplayingAudio=true; mediaPlayer.start(); }
}
public static void stopAudio(){ isplayingAudio=false; mediaPlayer.stop(); }
public static void pauseAudio() {isplayingAudio=false;mediaPlayer.pause();}
public static void resumeAudio() {isplayingAudio=true;mediaPlayer.start();}
}
and this is my Settings class.
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
AudioPlay.playAudio(getBaseContext(),R.raw.app_bg_music);
AudioPlay.mediaPlayer.setLooping(true);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings_pref, new SettingsFragment())
.commit();
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); }
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
sharedPrefs.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
boolean test = sharedPreferences.getBoolean("play_music", false);
if(test) {AudioPlay.resumeAudio(); AudioPlay.mediaPlayer.setLooping(true);}
else {AudioPlay.pauseAudio();}
}
});
}
public static class SettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey)
{ setPreferencesFromResource(R.xml.root_preferences, rootKey); }
}
#Override
protected void onPause() {
super.onPause();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean isChecked = sharedPreferences.getBoolean("play_music", false);
if(isChecked) {AudioPlay.resumeAudio(); AudioPlay.mediaPlayer.setLooping(true);}
else {AudioPlay.pauseAudio();}
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean isChecked = sharedPreferences.getBoolean("play_music", false);
if(isChecked) {AudioPlay.resumeAudio(); AudioPlay.mediaPlayer.setLooping(true);}
else {AudioPlay.pauseAudio();}
}
}
and to start with, I'm calling the SharedPreference from OnPause and OnResume methods in MainActivity as well as from Settings class.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean isChecked = sharedPreferences.getBoolean("play_music", false);
if(isChecked) {AudioPlay.resumeAudio(); AudioPlay.mediaPlayer.setLooping(true);}
else {AudioPlay.pauseAudio();}
I think, I fixed it myself.Multiple tests doesn't show any problem.Please let me know if this could be done in a better way.My
Settings Fragment class
public class SettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener {
SharedPreferences sharedPreferences;
#Override
public void onCreatePreferences(Bundle bundle, String rootKey) {
addPreferencesFromResource(R.xml.root_preferences);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equals("sync")){
boolean on = sharedPreferences.getBoolean("sync", false);
if(on){
Toast.makeText(getActivity(), "Switch enabled", Toast.LENGTH_SHORT).show();
if(AudioPlay.mediaPlayer == null) { AudioPlay.playAudio(getContext(),R.raw.app_bg_music_orig); AudioPlay.mediaPlayer.setLooping(true);}
else {AudioPlay.resumeAudio();}
}
else {
Toast.makeText(getActivity(), "Switch disabled", Toast.LENGTH_SHORT).show();
if(AudioPlay.mediaPlayer == null) { Log.i("Switch position",""+on); }
else {AudioPlay.pauseAudio();}
}
}
}
#Override
public void onStart() {
super.onStart();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onStop() {
super.onStop();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
}
My
Settings class
public class SettingsActivity extends AppCompatActivity {
SharedPreferences.OnSharedPreferenceChangeListener listener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
getSharedPreferences("sync",MODE_PRIVATE).registerOnSharedPreferenceChangeListener(listener);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, new SettingsFragment())
.commit();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean my_bg_music = preferences.getBoolean("sync",true);
if(my_bg_music){
if(AudioPlay.mediaPlayer == null) { AudioPlay.playAudio(this,R.raw.app_bg_music_orig); AudioPlay.mediaPlayer.setLooping(true);}
else {AudioPlay.resumeAudio();}
}
else{
if(AudioPlay.mediaPlayer == null) { Log.i("Switch position",""+my_bg_music); }
else {AudioPlay.pauseAudio();}
}
}
#Override
public void onResume() {
getSharedPreferences("sync",MODE_PRIVATE).registerOnSharedPreferenceChangeListener(listener);
super.onResume();
}
#Override
public void onPause() {
getSharedPreferences("sync",MODE_PRIVATE).unregisterOnSharedPreferenceChangeListener(listener);
super.onPause();
}
}

onsharedpreferencechangelistener not work in android app

I wrote this code that works with sharedPreference ,
in sosbutton I changed sharedPreference ,I want when sharedPreference changed ,
onsharedpreferencechangelistener fire .
I wrote this code but onsharedpreferencechangelistener didn't fire.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SharedPreferences prefs = getSharedPreferences("demopref", Context.MODE_WORLD_READABLE);
final Button sosBtn=(Button) findViewById(R.id.button);
sosBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String data = prefs.getString("demostring", "No Value");
SharedPreferences.Editor editor = prefs.edit();
editor.putString("demostring","HI...");
editor.commit();
////////////////////////////////
}
});
SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
Toast.makeText(getApplicationContext(),"changed : " + key,Toast.LENGTH_LONG).show();
}
};
prefs.registerOnSharedPreferenceChangeListener(listener);
}
}
please help me :(
thanks in advance
I solved my problem:
public class MainActivity extends Activity {
SharedPreferences pref;
SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if(key.equals("demopref"))
Toast.makeText(getApplicationContext(),"Hello2---"+key,Toast.LENGTH_LONG).show();
}
};
#SuppressWarnings("deprecation")
int i=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
////////////////////////////////////////
final Button sosBtn = (Button) findViewById(R.id.button);
sosBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = pref.edit();
editor.putString("demopref","HI"+String.valueOf(i));
i++;
editor.commit();
/////////////////////////////////
}
});
}
#Override
protected void onResume() {
pref.registerOnSharedPreferenceChangeListener(listener);
super.onResume();
}
#Override
protected void onPause() {
pref.unregisterOnSharedPreferenceChangeListener(listener);
super.onPause();
}
}
MODE_WORLD_READABLE is deprecated, try MODE_PRIVATE
Try this may be help you...
your not given reference to your
SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
here is my code
public class MainActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SharedPreferences prefs = getSharedPreferences("demopref", Context.MODE_PRIVATE);
final Button sosBtn=(Button) findViewById(R.id.button);
sosBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String data = prefs.getString("demostring", "No Value");
SharedPreferences.Editor editor = prefs.edit();
editor.putString("demostring","HI...");
editor.commit();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(listener);
////////////////////////////////
}
});
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
Toast.makeText(getApplicationContext(),"changed : " + key,Toast.LENGTH_LONG).show();
}
};
prefs.registerOnSharedPreferenceChangeListener(listener);
}
}

Android: stay connected with checkbox

I want to add a checkbox in login-phase that, when it is clicked the app remember the user also when he exits without logout,
but when this checkbox isn't clicked the user access to several activities but when he exits without logout there is still the logout.
This is my code:
public class MainActivity extends Activity implements OnClickListener{
private EditText username=null;
private EditText password=null;
private Button login, registration;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String user = "nameKey";
public static final String pass = "passwordKey";
SharedPreferences sharedpreferences;
public boolean isChecked = false;
public boolean isunChecked = true;
private CheckBox check;
String a,b, result,z, clic;
Class<?> activityClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
username = (EditText)findViewById(R.id.editText1);
password = (EditText)findViewById(R.id.editText2);
registration = (Button)findViewById(R.id.button2);
login = (Button)findViewById(R.id.button1);
TextView text2 = (TextView) findViewById(R.id.tv);
login.setOnClickListener(this);
registration.setOnClickListener(this);
check = (CheckBox) findViewById(R.id.checkBox);
check.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1 : {
login.setEnabled(false);
registra.setEnabled(true);
registra.setClickable(false);
username.setFocusable(false);
password.setFocusable(false);
if (check.isChecked()) {
clic = "Checked";
System.out.println("CheckBox is checked");
}
else{
clic = "no_Checked";
System.out.println("CheckBox is unchecked");
}
LoginTask task = new LoginTask(username,password);
task.execute(null,null,null);
break;
}
case R.id.button2: {
registration.setEnabled(false);
login.setEnabled(true);
login.setClickable(false);
registration(v);
break;
}
}
}
public class LoginTask extends AsyncTask<Void, Void, String> {
public LoginTask(EditText username2, EditText password2) {
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result.equals("ok")){
Toast.makeText(MainActivity.this, "ok", Toast.LENGTH_SHORT).show();
}
else {
login.setEnabled(true);
login.setClickable(true);
registration.setEnabled(true);
registration.setClickable(true);
username.setFocusableInTouchMode(true);
password.setFocusableInTouchMode(true);
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected String doInBackground(Void... params) {
String result = null;
Editor editor = sharedpreferences.edit();
try {
[....]
String u = username.getText().toString();
String p = password.getText().toString();
editor.putString(user, u);
editor.putString(pass, p);
if(clic.equals("checked
editor.putBoolean("isChecked", isChecked);
System.out.println("clic");
}else{
editor.putBoolean("isChecked", isunChecked);
System.out.println("no_clic");
}
editor.commit();
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(intent);
}
catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
return result=e.getMessage();
}
return result="ok";
}
}
#Override
protected void onResume() {
sharedpreferences=getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);
if(isChecked = sharedpreferences.getBoolean("isChecked", true)){
Toast.makeText(MainActivity.this, "login", Toast.LENGTH_SHORT).show();
if (sharedpreferences.contains(user))
{
if(sharedpreferences.contains(pass)){
Toast.makeText(MainActivity.this, "login", Toast.LENGTH_SHORT).show();
System.out.println(" CheckBox is checked");
try {
SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
activityClass = Class.forName(prefs.getString("activity1", FirstActivity.class.getName()));
prefs.getString("activity2", SecondActivity.class.getName());
} catch(ClassNotFoundException ex) {
}
Intent i = new Intent(this, activityClass);
startActivity(i);
}
}
}else{
Toast.makeText(MainActivity.this, "logout", Toast.LENGTH_SHORT).show();
System.out.println("logout");
//logout();
}
super.onResume();
}
public void registration (View view){
Intent intent1;
intent1 = new Intent (this, Registration.class);
startActivity(intent1);
}
public void onPause() {
super.onPause();
this.finish();
}
public void closing() {
finish();
}
this code doesn't work, because when the checkbox isn't checked the user is logged yet. maybe I'm wrong to place the control on the checkbox? How can I solve this problem?
your user is remebered because when you pause the app, all attributes hold active. you have to destroy the main activity launcher to delete these values To hold the session if you click checkbox I recommend you to use a data base where you remember the user, password and active.

onPreferenceClick and OnPreferenceClickListener

I'm attempting to evaluate my preferences in my java code in order to enable/disable other options it they chose not to do other options... So far i'm trying to only implement the OnPreferenceClickListener however i never see the toast from the changes. What am i doing wrong? There seem to be alot of other questions like this but i cannot see my error in reference to them.
public class UserSettingActivity extends PreferenceActivity implements OnPreferenceClickListener{
SharedPreferences mPreferences;
Boolean frequency;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
#Override
public boolean onPreferenceClick(Preference preference) {
mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
frequency = mPreferences.getBoolean("frequency", true);
Context context = getApplicationContext();
Toast.makeText(context, "Hello toast 0!", Toast.LENGTH_LONG).show();
if (!frequency) {
Context context2 = getApplicationContext();
Toast.makeText(context2, "Hello toast 1!", Toast.LENGTH_LONG).show();
} else if (preference.getKey().equals("schedulestop")) {
} else if (preference.getKey().equals("priority")) {
} else {
Context context3 = getApplicationContext();
Toast.makeText(context3, "Hello toast 0!", Toast.LENGTH_LONG).show();
}
return false;
}
}
You have to register for PreferenceClickListener each individual preference
somePreference.setOnPreferenceClickListener(this);
or you can use getSharedPreferences().registerOnSharedPreferenceChangeListener for all preferences.
public class UserSettingActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener{
SharedPreferences mPreferences;
Boolean frequency;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
#SuppressWarnings("deprecation")
#Override
protected void onPause()
{
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#SuppressWarnings("deprecation")
#Override
protected void onResume()
{
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#SuppressWarnings("deprecation")
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("schedulestop")) {
// do something
}
else if (key.equals(......
}
}
first implement "OnSharedPreferenceChangeListener"
PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener
Then
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
settings.registerOnSharedPreferenceChangeListener(this);
}
THEN
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
switch (key) {
case "pref_key_auto_delete":
boolean notificationStatus = SP.getBoolean(key, false);
Log.d("stat", String.valueOf(notificationStatus));
break;
case "pref_key_notification_list":
String downloadType = SP.getString(key, "n/a");
Log.d("stat", String.valueOf(downloadType));
break;
}

Android Password Change Activity

I want to implement a password change activity in my application, and here is the code which I've written for my activity, but I think that I should declare the String Password variable to somewhere else, because my new password changes successfully and works until I close the application,and when I run it again the old password is the right one.I'm really new to Android development, any answers/suggestions will be appreciated.
Change_Password code:
public class Change_Password extends Activity {
//----
public SharedPreferences prefs;
private String prefName = "MyPref";
private static final String TEXT_VALUE_KEY = "nothing";
//-----
public static String Password="soha";
public static String getPassword()
{
return Password;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.change_password);
Button btnCancel=(Button)findViewById(R.id.btnCancel);
btnCancel.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
finish();
}
});
final EditText txtNewPassword=(EditText)findViewById(R.id.txtNewPassword);
final EditText txtCurrentPassword=(EditText)findViewById(R.id.txtCurrentPassword);
final EditText txtConfirmPassword=(EditText)findViewById(R.id.txtConfirmNewPassword);
Button btnSave=(Button)findViewById(R.id.btnSave);
btnSave.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if(txtConfirmPassword.getText().toString().equalsIgnoreCase("") |
txtCurrentPassword.getText().toString().equalsIgnoreCase("") |
txtCurrentPassword.getText().toString().equalsIgnoreCase(""))
{
Toast.makeText(getBaseContext(),"Please Complete the Information", Toast.LENGTH_SHORT).show();
}
else
if(!txtNewPassword.getText().toString().equalsIgnoreCase(txtConfirmPassword.getText().toString()))
{
Toast.makeText(getBaseContext(),
"These Passwords Don't Match !", Toast.LENGTH_SHORT).show();
}
else
if(!getPassword().equalsIgnoreCase(txtCurrentPassword.getText().toString()))
{
Toast.makeText(getBaseContext(),
"Current Password is Incorrect!", Toast.LENGTH_SHORT).show();
}
else
{
///------- //---save the values in the EditText view to preferences---
prefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(TEXT_VALUE_KEY, txtNewPassword.getText().toString());
//---saves the values---
editor.commit();
///--------
//Password=txtNewPassword.getText().toString();
Toast.makeText(getBaseContext(),
Password, Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onAttachedToWindow() {
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
super.onAttachedToWindow();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_HOME)
BackToMainIntent();
else if(keyCode==KeyEvent.KEYCODE_BACK)
{
BackToMainIntent();
}
return false;
}
public void BackToMainIntent()
{
Intent intent = new Intent(this, Main.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
And Here my main activity:
public class mainC extends Activity {
private EditText uPass;
private Button loginBtn;
private Button Btn_Exit;
private ImageView Image;
///------
public SharedPreferences prefs;
private String prefName = "MyPref";
private static final String TEXT_VALUE_KEY = "1234";
////----------
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginpage);
Image=(ImageView)findViewById(R.id.NFCImage);
Image.setAlpha(100);
Btn_Exit=(Button)this.findViewById(R.id.Btn_exit_app);
Btn_Exit.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent _Intent =new Intent(Intent.ACTION_MAIN);
_Intent.addCategory(Intent.CATEGORY_HOME);
_Intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(_Intent);
}
});
setUpViews();
}
#Override
protected void onResume() {
super.onResume();
uPass.setText("");
uPass.setInputType(InputType.TYPE_CLASS_TEXT| InputType.TYPE_TEXT_VARIATION_PASSWORD);
uPass.setTextColor(Color.parseColor("#888888"));
}
private void setUpViews() {
uPass=(EditText)findViewById(R.id.usrPassTxt);
uPass.setOnFocusChangeListener(new View.OnFocusChangeListener(){
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
uPass.setInputType(InputType.TYPE_CLASS_TEXT| InputType.TYPE_TEXT_VARIATION_PASSWORD);
uPass.setText("");
}
}
});
loginBtn=(Button)findViewById(R.id.Btn_Login);
loginBtn.setOnClickListener(new OnClickListener() {
private String pass;
Intent myIntent;
public void onClick(View v) {
pass=uPass.getText().toString();
///-----
SharedPreferences prefs = getSharedPreferences(prefName, MODE_PRIVATE);
String passtemp = prefs.getString(TEXT_VALUE_KEY, "nothing");
if( pass.equalsIgnoreCase(passtemp))
///-----
//if( pass.equalsIgnoreCase(Change_Password.getPassword()))
{
myIntent=new Intent(mainC.this,Main.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
System.out.println("---IF---");
}
else{
myIntent=new Intent(mainC.this,ErrorPage.class);
System.out.println("---ELSE---");
}
startActivity(myIntent);
}
});
}
#Override
public void onBackPressed() {
finish();
}
}
The problem here is that your are running all in memory, I mean, you have your Password variable (static) in memory, you assigned it when the password is changed and its ok.
But when you start the appliccation again, the value of password is 1234 because you have code it! xD, you have to store de password somewhere else, for example using SharedPreferences.
Here
if( pass.equalsIgnoreCase(Change_Password.getPassword()))
you are trying to call a method from previous Activity which is not valid way fro sharing data between Activities or Other Components of Application .
In your case, you can use SharedPreferences for Storing password instead of using static fields or methods
see these tutorials of we use SharedPreferences in our application :
http://developer.android.com/guide/topics/data/data-storage.html
http://saigeethamn.blogspot.in/2009/10/shared-preferences-android-developer.html
http://android-er.blogspot.in/2011/01/example-of-using-sharedpreferencesedito.html

Categories

Resources