I have already created users, a name and password in my database. Then the user name is passed to the next activity. And with the next activity from the menu, you can click the logout button and it should display the registration window. But nothing works for me, the "exit" button does not flip to another screen, but just goes into the same one...
mSettings = getSharedPreferences("my_storage", Context.MODE_PRIVATE);
editor = mSettings.edit();
if(mSettings.getBoolean("is_logged", true)){
startActivity(new Intent(Authorisation.this, Menu.class));
finish();
}
editor.putBoolean("is_logged", false).apply();
and after that, I pass the name and password to the editor, set the value to true. Where did I go wrong?
Boolean checkuserpass = DB.checkusernamepassword(user, pass);
if(checkuserpass == true){
Intent intent = new Intent(getApplicationContext(), Menu.class);
intent.putExtra("name", user);
NAME = user;
editor.putString(NAME, user).apply();
editor.putString("PASSWORD", pass).apply();
editor.putBoolean("is_logged", true).apply();
startActivity(intent);
The code of another menu activity. Here I am trying to pass the values to the header (username - name during registration).
#Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
Intent intent = new Intent(Menu.this, Authorisation.class);
Authorisation authorisation = new Authorisation();
authorisation.log_out();
startActivity(intent);
finish();
return true;
}
Related
I am working on a login app using FirebaseAuth, I am implementing two separate Activities, one to work online and other for offline. There is third starter activity that tries to automatically login a user if his data is present on the SharedPreferences. When finish() is called on an activity signInWithEmailAndPassword won't stop.
when internet is not working and "Work Offline" button is clicked , it will lead the user to ActivityOffline. But when internet is restored while the user is on ActivityOffline , out of nowhere ActivityOnline will pop up because of signInWithEmailAndPassword on the starter activity which is already finished.
How can i stop signInWithEmailAndPassword when my Work Offline button is clicked?
public class Starter extends AppCompatActivity {
Button useOffline;
String email;
String password;
FirebaseAuth mAuth = FirebaseAuth.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starter);
Prefs prefs = new Prefs(this);
email = prefs.getStringEntry("email");
password = prefs.getStringEntry("password");
useOffline = findViewById(R.id.use_offline);
useOffline.setOnClickListener(v -> {
Intent intent = new Intent(Starter.this, OfflineActivity.class);
startActivity(intent);
finish();
});
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(() -> useOffline.setVisibility(View.VISIBLE), 5000);
if (email.equals("") || password.equals("")) {
Intent intent = new Intent(Starter.this, LoginActivity.class);
startActivity(intent);
finish();
} else {
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
prefs.setStringEntry("UID", Objects.requireNonNull(FirebaseAuth.getInstance().getCurrentUser()).getUid());
Intent intent = new Intent(Starter.this, OnlineActivity.class);
startActivity(intent);
} else {
prefs.removeEntry("email");
prefs.removeEntry("password");
Intent intent = new Intent(Starter.this, LoginActivity.class);
startActivity(intent);
}
finish();
});
}
}
}
You can set a boolean flag to true when offline button press and check this flag before start online activity.
I have an android app in which I am using shared preferences for login.Until now I have a flow like user logs in..when login is successful the credentials are stored.And when the user opens the app again the username password appears in the edit text.I have a login button and have setonclicklistner to login and jump to the inner activities.
I am trying a flow like when the user logs in successfully..and the app is restarted the credentials are stored..it should automatically go the next activity(inner activity).
What I have tried until now..
In oncreate the onclicklistner that opens next activity if credentials are good
buttonlogin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(etemail.getText().toString().equals("") && etpass.getText().toString().equals(""))
{
Toast.makeText(getApplicationContext(),"Enter your username and Password",Toast.LENGTH_LONG).show();
}
else
{
load_data();
}
}
});
Code of shared pref
private void savePreferences() {
SharedPreferences settings = getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
// Edit and commit
UnameValue = etemail.getText().toString();
PasswordValue = etpass.getText().toString();
editor.putString(PREF_UNAME, UnameValue);
editor.putString(PREF_PASSWORD, PasswordValue);
editor.commit();
}
private void loadPreferences()
{
SharedPreferences settings = getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
// Get value
UnameValue = settings.getString(PREF_UNAME, DefaultUnameValue);
PasswordValue = settings.getString(PREF_PASSWORD, DefaultPasswordValue);
etemail.setText(UnameValue);
etpass.setText(PasswordValue);
}
What should I do in order to achieve this??if username password is stored automatically open next activity instead of clicking login button??
Thanks
you can use contains(String key) in SharedPreferences class
could be done in loadPreferences()
if login is only used to allow access to the next activity, then you don't need to simulate the button click, but if the click loads other data based on the provided username/password then you have to do it using performClick() in Button class.
so your code may look like this:
private void loadPreferences()
{
SharedPreferences settings = getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if(settings.contains(PREF_UNAME) && settings.contains(PREF_PASSWORD)){
//you can start the 2nd activity directly here
//Intent intent = new Intent (...)
//startActivity(intent);
//finish();
//OR
//load data into edittexts and programatically click the login button
UnameValue = settings.getString(PREF_UNAME, DefaultUnameValue);
PasswordValue = settings.getString(PREF_PASSWORD, DefaultPasswordValue);
etemail.setText(UnameValue);
etpass.setText(PasswordValue);
//here it will click the button as if the user did it.
btnLogin.performClick();
}//contains
}
Side note: it's not good practice (not secure) to store passwords in SharedPreferences specially plain-text, not encrypted
Open the next activity first, and then in onCreate method check if the user is logged in. If not close the first, and open the loggin activity.
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
session = new SessionManager(getApplicationContext());
CheckLogin();
...
}
private void CheckLogin(){
if(session.checkLogin()){finish();}
}
SessionManager.java
public boolean checkLogin(){
// Check login status
if(!this.isUserLoggedIn()){
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities from stack
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
return true;
}
return false;
}
After storing username and password in sharedpreference editor.putBoolean("hasLoggedin", true);
So it should be like
UnameValue = etemail.getText().toString();
PasswordValue = etpass.getText().toString();
editor.putString(PREF_UNAME, UnameValue);
editor.putString(PREF_PASSWORD, PasswordValue);
editor.putBoolean("hasLoggedin", true);
editor.commit();
then check in Oncreate method like
boolean hasLoggedin = sp.getBoolean("hasLoggedin", false);
if (hasLoggedin) {
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
startActivity(intent);
finish();
}
I wrote this code following the skeleton of Reto Meier's "Professional Android 4 Application Development" and some slide of my professor, but i can't understand why the new activity (PreferencesActivity, fully coded) is not starting and is not raising any kind of errors: in the VM it just won't do anything when i press "Preferences" in the standard android menu I created.
I added the new activity in app's manifest correctly (just name, label, theme and screen orientation).
Here's the code
public class MainActivity extends Activity implements OnClickListener, OnValueChangeListener {
static final private int MENU_PREFERENCES = Menu.FIRST+1;
...
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_PREFERENCES, Menu.NONE, "Preferences");
return true;
}
public boolean onOptionsitemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()) {
case (MENU_PREFERENCES): {
Intent i = new Intent(this, PreferencesActivity.class);
startActivity(i);
return true;
}
}
return false;
}
...
}
The only strange thing I get is this warning in Logcat
06-20 14:50:49.760: W InputManagerService(699): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#41219950
You can use both of them
Intent i = new Intent(getApplicationContext(), PreferencesActivity.class);
Intent i = new Intent(MainActivity.this, PreferencesActivity.class);
But it's better to use 1st one because in 2nd one memory leakage problem may occour and also just add this line in your manifest file.
<activity android:name=".PreferencesActivity" />
Your Code :
Intent i = new Intent(this, PreferencesActivity.class);
startActivity(i);
return true;
Instead of this you need to pass MainActivity.this
Intent i = new Intent(MainActivity.this, PreferencesActivity.class);
startActivity(i);
return true;
Issue is Proper context is not passing so its not starting Activity.
Instead of using this you could use getApplicationContext(), it gets you the context of the application object for the currents process.
Try this....
Intent i = new Intent(getApplicationContext(), PreferencesActivity.class);
startActivity(i);
This May Help You..
You need to pass MainActivity
Intent i = new Intent(MainActivity.this, PreferencesActivity.class);
startActivity(i);
return true;
Better to use menu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "onOptionsItemSelected()");
switch (item.getItemId()) {
case android.R.id.yourId:
finish();
return true;
case R.id.Yourid:
return true;
default:
return super.onOptionsItemSelected(item);
You can also write
startActivity(new Intent(getApplicationContext(),NextActivity.class));
write your activity name in NextActivity.class
I have an issue whereby, the back button works fine. Unless you push the home button, then re-enter the application, then push the back button again. It then quits the App, because their is no task trail (of activities)
Here is my colleagues code, of which I am trying to fix. Android.R.id.home is the problematic soft back button, although same thing is happening with OS back button.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case android.R.id.home:
activity.finish();
return true;
case R.id.menu_paymentLocs:
intent = new Intent(activity, PaymentLocationsPage.class);
intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
activity.startActivity(intent);
return true;
case R.id.menu_feedback:
intent = new Intent(activity, FeedbackPage.class);
intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
activity.startActivity(intent);
return true;
case R.id.menu_about:
intent = new Intent(activity, AboutPage.class);
intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
activity.startActivity(intent);
return true;
case R.id.menu_changeconsumer:
new SelectConsumerDialogFragment().show(getFragmentManager(), "select_consumer");
return true;
case R.id.menu_logout:
intent = new Intent(activity, SplashPage.class);
myMeter.logout();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
activity.startActivity(intent);
return true;
}
return true;
}
To prevent the back button from doing anything predefined you need to override the onbackpressed() method
try this if you are using api level 2.0 or higher
#Override
public void onBackPressed() {
// Do Here what ever you want do on back press;
}
Remove all intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
How can I make ringtone activity (that always appear in setting) so the user can choose her ringtone from system ringTones I googled it but I didn't find complete tutorial, I am really confused, please give me tutorial or some codes.
Also, if I want the user to choose the special ringtone to Notification in my application should i use Shared preference or preference?
I already did the Menu:
// Menu Code Part#2
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about:
startActivity(new Intent(this, About.class));
return true;
case R.id.help:
startActivity(new Intent(this, Help.class));
return true;
case R.id.setting:
startActivity(new Intent(this, Setting.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
Full code:
res/xml/preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="Second Category">
<RingtonePreference
android:name="Ringtone Preference"
android:summary="Select a ringtone"
android:title="Ringtones"
android:key="ringtonePref" />
</PreferenceCategory>
</PreferenceScreen>
Preferences.class
public class Preferences extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
Your code go here:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about:
// startActivity(new Intent(this, About.class));
return true;
case R.id.help:
startActivity(new Intent(this, Help.class));
return true;
case R.id.setting:
Intent settingsActivity = new Intent(getBaseContext(),
Preferences.class);
startActivity(settingsActivity);
return true;
default:
return super.onOptionsItemSelected(item);
}
To read these preferences from code, we should create a getPrefs() method, which we can call in the onStart() method. When we call it in the onStart() method instead of onCreate(), we can be sure that the preferences load when we have set them and returned to our main activity,
The getPrefs() method could look like this:
String ringtonePreference;
// Get the xml/preferences.xml preferences
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
ringtonePreference = prefs.getString("ringtonePref",
"DEFAULT_RINGTONE_URI");
androidmanifest.xml
<activity
android:name=".Preferences"
android:label="#string/set_preferences">
</activity>
Yes, you can use SharedPreferences to store the URI of the ringtone the user selected. You can let the user select a ringtone using this:
Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "Select Ringtone");
if (mRingtoneUri != null) {
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, Uri.parse(mRingtoneUri));
} else {
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, (Uri) null);
}
startActivityForResult(intent, RINGTONE_REQUEST);
The above code will prompt the user to select a ringtone from the system. When they select one, you will need to handle the Activity result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RINGTONE_REQUEST && resultCode == RESULT_OK) {
Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
SharedPreferences preferences = getSharedPreferences(PREF, MODE_PRIVATE);
Editor editor = preferences.edit();
if (uri == null)
editor.putString(RINGTONE, null);
else
editor.putString(RINGTONE, uri.toString());
editor.commit();
if (uri == null)
mRingtoneUri = null;
else
mRingtoneUri = uri.toString();
}
}
}
This code will save the URI of the ringtone to SharedPreferences.