I'm currently trying to program an app which requires the user to key in their name. This is the "Login" page.
public class Login extends Activity
{
EditText username;
#Override
public void onCreate(Bundle savedInstanceState)
{
username = (EditText)findViewById(R.id.username);
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
Button loginButton = (Button) findViewById(R.id.loginBtn);
loginButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent intent = new Intent("com.example.MainActivity");
Bundle extras = new Bundle();
extras.putString("name", username.getText().toString());
intent.putExtras(extras);
startActivity(intent);
}
});
}
protected void onDestroy() {
super.onDestroy();
}
protected void onPause() {
super.onPause();
saveAsPreferences();
}
protected void onRestart() {
super.onRestart();
saveAsPreferences();
}
protected void onResume() {
super.onResume();
retrievePreferences();
}
protected void onStart() {
super.onStart();
retrievePreferences();
}
protected void onStop() {
super.onStop();
saveAsPreferences();
}
public void saveAsPreferences()
{
SharedPreferences prefs = getSharedPreferences("preferences", MODE_PRIVATE);
String Name = username.getText().toString();
SharedPreferences.Editor editor = prefs.edit();
editor.putString("name", Name);
editor.commit();
}
public void retrievePreferences()
{
SharedPreferences prefs = getSharedPreferences("preferences",MODE_PRIVATE);
if(prefs.contains("name"))
{
String Name = prefs.getString("name", "");
username.setText(Name);
}
}
}
and this is my Result page
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle bundle = getIntent().getExtras();
String Name = bundle.getString("name");
TextView welcomeUser = (TextView) findViewById(R.id.welcomeUser);
welcomeUser.setText("Hello " + Name + "!");
}
why isn't my codes working? Thanks!
Note: I've linked the pages correctly before I start on passing data.
You should change the order like in your Login Activity
setContentView(R.layout.login);
username = (EditText)findViewById(R.id.username);
First you need to setContentView(..) then reference Views.
do in this way . in your login class don't use Bundle . use intent.putExtra("name",username); and then in your main activity class . getIntent().getStringExtra("name"); this will return the username and define your Edittext aftert setContentView
Related
I have an app that has 3 activities:
MessagesActivity
LoginActivity
RegisterActivity
The LoginActivity contains 2 EditTexts and a CheckBox that keeps the user signed in. And of course 2 Buttons: one for signing in and the other for registering an account.
I have added an intent in the LoginActivity so when logged in, the MessagesActivity is shown. And another intent in the MessagesActivity for when reading from SharedPreferences if the CheckBox is not checked, switching to LoginActivity.
The problem is that I don't know how to do that. I'm still new to SharedPreferences. And even when logging in and the inputs are true, the app doesn't switch to MessagesActivity. It shows the LoginActivity again.
I want help in that please if anyone know how to do it.
RegisterActivity.java
public class RegisterActivity extends AppCompatActivity {
private EditText registerUsername;
private EditText registerEmail;
private EditText registerPassword;
private EditText registerConfirmPassword;
private Button registerRegisterButton;
private Button registerLoginButton;
private ProgressBar registerProgressBar;
private FirebaseFirestore firebaseFirestore;
private String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
registerUsername = findViewById(R.id.register_username);
registerEmail = findViewById(R.id.register_email);
registerPassword = findViewById(R.id.register_password);
registerConfirmPassword = findViewById(R.id.register_confirm_password);
registerRegisterButton = findViewById(R.id.register_register_button);
registerLoginButton = findViewById(R.id.register_login_button);
registerProgressBar = findViewById(R.id.register_progressBar);
firebaseFirestore = FirebaseFirestore.getInstance();
registerLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent loginIntent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(loginIntent);
finish();
}
});
registerRegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String username = registerUsername.getText().toString();
String email = registerEmail.getText().toString();
String password = registerPassword.getText().toString();
String confirmPassword = registerConfirmPassword.getText().toString();
if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(email) && !TextUtils.isEmpty(password) && !TextUtils.isEmpty(confirmPassword)) {
if (password.equals(confirmPassword)) {
registerProgressBar.setVisibility(View.VISIBLE);
Map<String, String> usersMap = new HashMap<>();
usersMap.put("username", username);
usersMap.put("email", email);
usersMap.put("password", password);
userID = registerUsername.getText().toString();
firebaseFirestore.collection("Users").document(userID).set(usersMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toasty.success(RegisterActivity.this, "Successfully Registered", Toast.LENGTH_SHORT).show();
Intent messagesIntent = new Intent(RegisterActivity.this, MessagesActivity.class);
startActivity(messagesIntent);
finish();
registerProgressBar.setVisibility(View.INVISIBLE);
}
});
} else {
Toasty.error(RegisterActivity.this, "Passwords Don't Match", Toast.LENGTH_SHORT).show();
}
}
}
});
}}
LoginActivity.java
public class LoginActivity extends AppCompatActivity {
private EditText loginUsername;
private EditText loginPassword;
private CheckBox loginKeepSignedIn;
private Button loginLoginButton;
private Button loginRegisterButton;
private ProgressBar loginProgressBar;
private FirebaseFirestore firebaseFirestore;
private String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginUsername = findViewById(R.id.login_username);
loginPassword = findViewById(R.id.login_password);
loginKeepSignedIn = findViewById(R.id.login_keep_signed_in);
loginLoginButton = findViewById(R.id.login_login_button);
loginRegisterButton = findViewById(R.id.login_register_button);
loginProgressBar = findViewById(R.id.login_progressBar);
firebaseFirestore = FirebaseFirestore.getInstance();
if (loginKeepSignedIn.isChecked()) {
SharedPreferences preferences = getSharedPreferences("Preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("keepSignedIn", true);
editor.apply();
}
loginRegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(registerIntent);
finish();
}
});
loginLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String username = loginUsername.getText().toString();
final String password = loginPassword.getText().toString();
if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password)) {
loginProgressBar.setVisibility(View.VISIBLE);
userID = loginUsername.getText().toString();
firebaseFirestore.collection("Users").document(userID).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
String userUsername = task.getResult().getString("username");
String userPassword = task.getResult().getString("password");
if (userUsername.equals(username) && userPassword.equals(password)) {
Toast.makeText(LoginActivity.this, "Everything is equal", Toast.LENGTH_SHORT).show();
Toasty.info(LoginActivity.this, "Switching to Messages Activity", Toast.LENGTH_SHORT).show();
Intent messagesIntent = new Intent(LoginActivity.this, MessagesActivity.class);
startActivity(messagesIntent);
LoginActivity.this.finish();
} else {
Toast.makeText(LoginActivity.this, "There is something not equal", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(LoginActivity.this, "Task is not successful",Toast.LENGTH_SHORT).show();
}
loginProgressBar.setVisibility(View.INVISIBLE);
}
});
}
}
});
}}
MessagesActivity.java
public class MessagesActivity extends AppCompatActivity {
private Toolbar messagesToolbar;
private Button logoutBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messages);
messagesToolbar = findViewById(R.id.messages_toolbar);
setSupportActionBar(messagesToolbar);
getSupportActionBar().setTitle("Messages");
logoutBtn = findViewById(R.id.logout);
SharedPreferences preferences = getSharedPreferences("Preferences", MODE_PRIVATE);
boolean keepSignedIn = preferences.getBoolean("keepSignedIn", false);
if (!keepSignedIn) {
Intent loginIntent = new Intent(MessagesActivity.this, LoginActivity.class);
startActivity(loginIntent);
finish();
}
logoutBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent loginIntent = new Intent(MessagesActivity.this, LoginActivity.class);
startActivity(loginIntent);
finish();
}
});
}
}
Well you just need to create an instance of SharedPreferences and store the value you need. It can either be a boolean , String e.t.c. Also you can store the preferences in a .xml file with a name you choose or let the system choose a name for you.
Use this piece of code to learn.
public class PrefsExample extends AppCompatActivity {
final String sharedPreferencesName = "chosenName";
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
//this allows the system to create a system wide sharedprefs file
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//this uses the name provided as the string above
//sharedPreferences = this.getSharedPreferences(sharedPreferencesName, MODE_PRIVATE);
//save the value(s) using
editor = sharedPreferences.edit();
editor.putBoolean("Logged", true);
editor.putString("Log In", "True");
editor.putInt("LoggedIn", 1);
//try out more options of the editor
//after editing,always apply to save
editor.apply();
//for read operations
readPrefs();
super.onCreate(savedInstanceState);
}
public void readPrefs() {
//again use this if only your prefs are system wide
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//and this if using a specified name
//sharedPreferences = this.getSharedPreferences(sharedPreferencesName, MODE_PRIVATE);
//retrieve your value using
String pref = sharedPreferences.getString("Log In","");
//use the get method of SharedPreferences to get but supply a default value eg for string "",for int 0,for boolean false e.t.c
//from here use a loop to check if values retrieved and values stored match and decide on which activity to proceed to from there
}}
I am trying to design an Android application, in that application i have sent the data from First Activity to Second Activity. In the Second Activity I am using this code
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
to save the data when application moves to landscape to portrait mode but in my application even i am using both of these but the data is not being saved. On rotation the data is getting destroyed which application is having in EditText View.
Please Check the below code, give the suggestions where i am doing the mistake to save the data
MainActivity.java
public class MainActivity extends AppCompatActivity {
EditText name,age;
TextView text_name,text_age;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name=(EditText) findViewById(R.id.name);
age=(EditText) findViewById(R.id.age);
text_name=(TextView) findViewById(R.id.name_edit);
text_age=(TextView) findViewById(R.id.name_age);
btn=(Button) findViewById(R.id.click);
//Button Click to send data to another activity
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Bundle bundle=new Bundle();
String user_name=name.getText().toString();
String user_age=age.getText().toString();
bundle.putString("UName",user_name);
bundle.putString("UAge",user_age);
Intent intent=new Intent(MainActivity.this,SecondClass.class);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
}
SecondClass.java
public class SecondClass extends Activity {
EditText name,age;
TextView text_name,text_age;
String namer,ager;
private String savedName,savedAge;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity_layout);
name=(EditText) findViewById(R.id.name);
age=(EditText) findViewById(R.id.age);
text_name=(TextView) findViewById(R.id.name_edit);
text_age=(TextView) findViewById(R.id.name_age);
if (savedInstanceState!=null)
{
savedInstanceState.get(savedName);
name.setText(savedName);
savedInstanceState.get(savedAge);
age.setText(savedAge);
}
if (savedInstanceState==null)
{
Intent i=getIntent();
Bundle bundle=i.getExtras();
namer=bundle.getString("UName");
name.setText(namer);
ager=bundle.getString("UAge");
age.setText(ager);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(savedName,namer);
outState.putString(savedAge,ager);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState!=null)
{
savedInstanceState.get(savedName);
name.setText(savedName);
savedInstanceState.get(savedAge);
age.setText(savedAge);
}
if (savedInstanceState==null)
{
Intent i=getIntent();
Bundle bundle=i.getExtras();
namer=bundle.getString("UName");
name.setText(namer);
ager=bundle.getString("UAge");
age.setText(ager);
}
}
}
You put and get value in saved instance with a key, and first put your data in
'outState' then call '
super.onSaveInstanceState(outState);
try this:
public class SecondClass extends Activity {
private static final String SAVED_NAME="savedName";
private static final String SAVED_AGE="savedAge";
EditText name,age;
TextView text_name,text_age;
String namer,ager;
private String savedName,savedAge;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity_layout);
name=(EditText) findViewById(R.id.name);
age=(EditText) findViewById(R.id.age);
text_name=(TextView) findViewById(R.id.name_edit);
text_age=(TextView) findViewById(R.id.name_age);
if (savedInstanceState!=null)
{
namer = savedInstanceState.get(SAVED_NAME);
name.setText(namer);
ager = savedInstanceState.get(SAVED_AGE);
age.setText(ager);
}
if (savedInstanceState==null)
{
Intent i=getIntent();
Bundle bundle=i.getExtras();
namer=bundle.getString("UName");
name.setText(namer);
ager=bundle.getString("UAge");
age.setText(ager);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString(savedName,namer);
outState.putString(savedAge,ager);
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState!=null)
{
namer = savedInstanceState.get(SAVED_NAME);
name.setText(namer);
ager = savedInstanceState.get(SAVED_AGE);
age.setText(ager);
}
if (savedInstanceState==null)
{
Intent i=getIntent();
Bundle bundle=i.getExtras();
namer=bundle.getString("UName");
name.setText(namer);
ager=bundle.getString("UAge");
age.setText(ager);
}
}
}
I have added Facebook Login code inside fragment. Everything works fine,i can login into my app but when i change fragment or reopen app after login every data are gone i.e email,name,birthday.it doesn't shows any data.so, what should i do to save those data.
code
public class ProfileFragment extends Fragment{
ProfileTracker profileTracker;
RelativeLayout fbbg;
RelativeLayout rl;
LoginButton btnLogin;
CallbackManager callbackManager;
AccessTokenTracker accessTokenTracker;
CircleImageView profilePicture;
TextView email;
TextView gender;
TextView facebookName;
TextView birthday;
SharedPreferences pref;
public static final List<String> mPermissions = new ArrayList<String>() {{
add("public_profile");
add("email");
add("user_photos");
add("user_birthday");
}};
#Nullable
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstantState) {
View view = inflater.inflate(R.layout.profile, container, false);
FacebookSdk.sdkInitialize(getActivity());
btnLogin = (LoginButton)view.findViewById(R.id.view);
email = (TextView)view.findViewById(R.id.un2);
facebookName = (TextView)view.findViewById(R.id.username);
birthday = (TextView)view.findViewById(R.id.bd2);
gender = (TextView)view.findViewById(R.id.gnd2);
profilePicture = (CircleImageView)view.findViewById(R.id.profile_image);
rl = (RelativeLayout) view.findViewById(R.id.rl);
fbbg = (RelativeLayout) view.findViewById(R.id.relativeLayout);
callbackManager = CallbackManager.Factory.create();
btnLogin.setReadPermissions(mPermissions);
btnLogin.setFragment(this);
btnLogin.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.d("JSON", ""+response.getJSONObject().toString());
try {
fbbg.setVisibility(View.GONE);
rl.setVisibility(View.VISIBLE);
email.setText(object.getString("email"));
gender.setText(object.getString("gender"));
facebookName.setText(object.getString("name"));
birthday.setText(object.getString("birthday"));
Glide.with(getActivity())
.load("https://graph.facebook.com/" + object.getString("id") + "/picture?type=large")
.into(profilePicture);
pref = getActivity().getSharedPreferences("", getActivity().MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("name", String.valueOf(facebookName));
editor.putString("email", String.valueOf(email));
editor.putString("gender", String.valueOf(gender));
editor.putString("birthday", String.valueOf(birthday));
editor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,birthday");
request.setParameters(parameters);
request.executeAsync();
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken,
AccessToken currentAccessToken) {
if (currentAccessToken == null) {
facebookName.setText("");
email.setText("");
gender.setText("");
birthday.setText("");
profilePicture.setImageResource(R.drawable.user);
}
}
};
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
}
};
accessTokenTracker.startTracking();
profileTracker.startTracking();
}
#Override
public void onCancel() {
Toast.makeText(getActivity(),"Cancled to Login Facebook", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException exception) {
Toast.makeText(getActivity(),"Error to Login Facebook", Toast.LENGTH_SHORT).show();
}
}); return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pref = getActivity().getSharedPreferences("", getActivity().MODE_PRIVATE);
pref.getString("name", "asdfgh");
pref.getString("email", "qwerty");
pref.getString("gender", "zxcvb");
pref.getString("birthday", "kdhfaj");
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
onResume();
}
}, 2000);
}
}
After login pic
After reopening app pic
#Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
AppEventsLogger.activateApp(getActivity());
}
No need to do this.
whenever you are resuming the fragment then that time it is creating the fresh instance of your facebook profile thats why data loss is happening.
on resume just reload fragment dont create new instace.
whenever you get data from facebook api immediately store it to shared preferences. after that you can fetch that data whenever you require.
public UpdateFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_updates, container, false);
listView = (ListView) v.findViewById(R.id.listView);
// define your xml resources here
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
loadUpdates();
}
private void loadUpdates() {
// api call
}
}
Try to embed your code into this fragment lifecycle. it will surely work.
There is no need to add onResume()
just do your stuff in loadUpdates(); method.
I have modified your code wrt SharedPreference.
You can try that.
pref = getActivity().getSharedPreferences("GIVE SOME name TO FILE", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("name", object.getString("name"));
editor.putString("email", object.getString("email"));
editor.putString("gender", object.getString("gender"));
editor.putString("birthday", object.getString("birthday"));
editor.apply();
Replace above code with your existing code, once you successfully get user profile information from FB
I think your problem is your SharedPreferences was initialized with an Activity. To avoid your data is lost when the Activity destroyed, you should use ApplicationContext().
I made a separated class with SharedPreference like this:
public class SessionManager {
// Shared Preferences reference
public SharedPreferences pref;
// Editor reference for Shared preferences
private Editor editor;
#SuppressWarnings("unused")
private Context context;
int PRIVATE_MODE = 0;
public static final String PREFER_NAME = "login";
public static final String KEY_USER_NAME = "username";
public SessionManager(Context context) {
this.context = context;
pref = context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public String getUserName() {
return pref.getString(KEY_USER_NAME, "");
}
public void setUserName(String userName) {
editor.putString(KEY_USER_NAME, userName);
editor.commit();
}
In your Fragment, initializing SharedPreferences with:
sessionManager = new SessionManager(getActivity.getApplicationContext());
saving your data:
session.setUserName(object.getString("name"));
Retrieving data at later times by called:
String userName = session.getUserName();
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);
}
}
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.