I am Creating an app where i login into app,it matches the data with database and then permits the user to login. But every time i press on login and go to another activity , the application terminates
public void userlogin(View view){
logname = et1.getText().toString();//retrieving details from Username field
logpass = et2.getText().toString();//retrieving details from Password field
String method = "Login";
BackTask bt = new BackTask(this);
bt.execute(method,logname,logpass);//checking from database
SharedPreferences.Editor editor = sharedpreferences.edit();//session management
editor.putString(Name, logname);
editor.putString(Pass, logpass);
if(editor.commit())
{
Intent in = new Intent(MainActivity.this,Create.class);
startActivity(in);
}
//starting another activty
}
Related
I'm developing an app where user must be able to switch between his accounts. As of now I'm able to allow the app with one account log in. How can I allow the user to create an another account and then switch between them in my android app?
update:-
I'm able to auth by Google button (firebase)
I want to do something like this in my app!
In my login.class I stored the value of UID which i got from firebase. Now i want to send this data to my splashscreen where it will check if uid==null then it will redirect to login and if uid !=null then it will redirect to MainActivity.
login.class
String MyPREFERENCES = "MyPrefs" ;
String uid = "uidKey";
SharedPreferences sharedpreferences = login.this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("uid", UID);
editor.putBoolean("is_logged_before",true); //this line will do trick
editor.commit();
Toast.makeText(login.this,"uid:"+UID,Toast.LENGTH_LONG).show();
String uid1 = sharedpreferences.getString("uid", "");
Log.i("shareduser",uid1);
Intent i = new Intent(login.this,splashScreen.class);
i.putExtra("message",uid1);
startActivity(i);
splashscreen
public class splashScreen extends Activity {
private static int SPLASH_TIME_OUT = 2000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashscreen);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
/*Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");
Log.i("received uid",message);*/
Intent homeIntent = new Intent(splashScreen.this, login.class);
startActivity(homeIntent);
finish();
}
},SPLASH_TIME_OUT);
}
}
The scope of your answer is very wide. Please ask only genuine doubts related to programming only.
Looks like you need to implement Auto-Login of the User. For this you need to use Shared Preferences.
After successful login of the user, store the username and password in the shared preferences.
Then when the user again tries to login you need to check the sharedPref to check for the username and password.
Moreover it again depends on the type of authentication you are implementing as you can also get the Session Id for the user.
Check this answer for that
Also for Account Picker check this answer
I'm stuck with one issue... So I build app, which, after login shows user information in MainActivity (I did that with Intent). Then I starts the app, I have to login with PIN Code. First time everything is fine. But if I click Logout button in mainActivity, I come back to LoginActivity and if I try to Login again, I don't get user information anymore. Only null values from sessionManager. I hope you understand my problem. I think the problem is here:
/** **SessionManager.java**
* Get stored session data
* */
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
// user userName
user.put(KEY_USER_NAME, pref.getString(KEY_USER_NAME, null));
// user workerGid
user.put(KEY_WORKER_GID, pref.getString(KEY_WORKER_GID, null));
// user firstName
user.put(KEY_FIRST_NAME, pref.getString(KEY_FIRST_NAME, null));
// user lastName
user.put(KEY_LAST_NAME, pref.getString(KEY_LAST_NAME, null));
// user mechGid
user.put(KEY_MECH_GID, pref.getString(KEY_MECH_GID, null));
// user transportName
user.put(KEY_TRANSPORT_NAME, pref.getString(KEY_TRANSPORT_NAME, null));
// return user
return user;
}
//Clear session details
public void logoutUser(){
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
}
//MapActivity: // get user data from session
HashMap<String, String> user = session.getUserDetails();
// First Name
String firsName = user.get(SessionManager.KEY_FIRST_NAME);
// Last Name
String lastName = user.get(SessionManager.KEY_LAST_NAME);
// Transport Name
String transportName = user.get(SessionManager.KEY_TRANSPORT_NAME);
TextView transport_name = (TextView) findViewById(R.id.transport);
transport_name.setText(transportName);
TextView nameLastname = (TextView) findViewById(R.id.user);
nameLastname.setText(firsName + lastName);
View logoutButton = findViewById(R.id.btnLogout);
View.OnClickListener button_logout = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(session.isLoggedIn())
session.logoutUser();
Intent in = new Intent(MapActivity.this,LoginActivity.class);
startActivity(in);
finish();
}
};
logoutButton.setOnClickListener(button_logout)
As stated in the comment above by #Suranhi Singh you are clearing your preferences, in this case is your user session. When you open your app again, it creates a new ,and empty, instance of SessionManager which overwrites the previous.
I suggest using a different tag to save the info you want to persist separate from the SessionManager. Dont use SessionManager for the data you want to be saved.
I have 4 activities in my android app.
1) Splash Activity - To decide if the app is being launched for the first time and to decide which activity to open
2)Main Activity - Button to open camera and start scanning i.e go to QR activity
2) QR Activity - Scan a QR code
3) Web Activity - On successful scanning, open a web page in the app. Use the data from the QR code to make a URL for the web page
In my splash activity, I check if it is the first run. If it is, I got to the main activity and if not, I want to go to the web activity. In my QR activity, I scan QR code and get a number from it. I use this number in the next activity, i.e, web activity to make a url using the scanned number and open the web page, But now, since I want to start different activity depending on the app run number, I want to save the scanned number from the first activity for all future runs of the app. Much like Facebook, which stores our login credentials for all future runs.
I am trying to do something like this, but the scanned value is not passed to my web activity
ScannerActivity.java
public static final String PREFS_NAME = "myPrefs";
if (barcodes.size() != 0) {
Intent intent = new Intent(getApplication(), WebActivity.class);
//intent.putExtra("result",barcodes.valueAt(0));
SharedPreferences.Editor editor=settings.edit();
editor.putString("result", barcodes.valueAt(0).displayValue);
editor.commit();
startActivity(intent);
finish();
}
WebActivity.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
String result = settings.getString("result", "");
/*Barcode barcode = (Barcode) getIntent().getParcelableExtra("result");
Toast.makeText(WebActivity.this, barcode.displayValue, Toast.LENGTH_LONG).show();*/
Toast.makeText(WebActivity.this, result, Toast.LENGTH_SHORT).show();
webView = (WebView) findViewById(R.id.webview);
webView.setWebViewClient(new myWebClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(" http://url?u="+result);
}
You're recommended to visit Android Studio Storage Option to have an enlarged perception of the mechanism and functionality
that being said, allow me to provide you with a snippet of how I store values in my application
Note you need to make minor adjustments, since I am applying Sharedpreferences inside a fragment
first
addusername = (EditText) oView.findViewById(R.id.addnewUsername);
second
//adjustment and reattachment
String bonsiour = addusername.getText().toString().trim();
SharedPreferences sPref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = sPref.edit();
edt.putString("key1", bonsiour);
edt.commit();
//toast to confirm value has been saved
String buzo = sPref.getString("key1", "empty");
Toast.makeText(getActivity(), "You're " + buzo + "!!", Toast.LENGTH_LONG).show();
This is how to extract/read from it
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String name = prefs.getString("key1", "No name defined");
if(name.equals("PDF_FOUND")){
Toast.makeText(Controller.this,"IT WORKED !", Toast.LENGTH_SHORT).show();
//skip the splash screen and move to another activity asap
} else{
Toast.makeText(Controller.this,"BAD NEWS !", Toast.LENGTH_SHORT).show();
//display Splash screen
}
}
You can use SharedPreferences to store your String and re-use it later
If you want to store a String for example, first create keys to get your values
public static final String sharedPreferencesKey = "shareKey";
public static final String stringKey = "stringKey";
To store your value
SharedPreferences sharedpreferences =
context.getSharedPreferences(sharedPreferencesKey, Context.MODE_PRIVATE);
SharedPreferences.Editor ed = sharedpreferences.edit();
ed.putString(stringKey, "");
ed.apply();
To get your value
if (sharedpreferences.contains(stringKey))
sharedPreferences.getString(stringKey, "")
To store your String in shared preferences, you can do the following in a one liner:
String QRCode = "code";
PreferenceManager.getDefaultSharedPreferences(this).edit().putString("QRCode", QRCode).commit();
To retrieve the value of your stored String, use this:
//The second parameter for getString() is the default value to return if QRCode is not set
String QRCode = PreferenceManager.getDefaultSharedPreferences(this).getString("QRCode", "NOT_FOUND");
if(QRCode.equals("NOT_FOUND")){
//open MainActivity
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
} else {
//open WebActivity
Intent intent = new Intent(this, WebActivity.class);
//you can pass code to webactivity or retrieve it from shared prefs
intent.putExtra("QRCode", QRCode);
startActivity(intent);
}
I am new to android development and i am working with a login activity. So for that i need to create a central database so that all the users can be authenticated and hence logged in. So please tell me how can I do this.
Can I use sqlite to create this type of data or it is just used to create a local database per client?
Thank you
For allowing multiple user loggin in the app you need to use central database .
Below is the link which will help you a lot.
http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/
You'd need an API to do this if you want it to span across several users. I'd recommend using Parse as a beginner as it's easy to set up and use.
https://www.parse.com/
tutorial:
http://www.androidbegin.com/tutorial/android-parse-com-simple-login-and-signup-tutorial/
used a SQL database instead of sqlite and used sheared preference for local storage. that is the best for create a login activity in any application.
Case 1:
If you have the Central Database in the Server then simply use the
SharedPreferences to save login credentials which you getting from Server for individual client device. No need to make the database for it.
Case2:
If you want to make Central Database in the mobile then use the Sqlite to save login credentials.
for sheared prefrence create a class name Session?Manager
public class SessionManager {
// Email address (make variable public to access from outside)
public static final String KEY_api = "apikey";
private static final String KEY_NAME = "name";
// Sharedpref file name
private static final String PREF_NAME = "AndroidHivePref";
private static final String push_ = "AndroidHivePref";
// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
SharedPreferences.Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Constructor
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void createLoginSession(String name, String apikey) {
// Storing login value as TRUE
editor.putBoolean(IS_LOGIN, true);
// Storing name in pref
editor.putString(KEY_NAME, name);
// Storing email in pref
editor.putString(KEY_api, apikey);
// commit changes
editor.commit();
}
public int getMerchentPushCount() {
return pref.getInt("MerchentPushCount", 0);
}
public void setMerchentPushCount(Integer count) {
editor.putInt("MerchentPushCount", count);
editor.commit();
}
/**
* Check login method wil check user login status
* If false it will redirect user to login page
* Else won't do anything
*/
public void checkLogin() {
// Check login status
if (!this.isLoggedIn()) {
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities
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);
}
}
/**
* Get stored session data
*/
public HashMap<String, String> getUserDetails() {
HashMap<String, String> user = new HashMap<String, String>();
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
// user api key
user.put(KEY_api, pref.getString(KEY_api, null));
// return user
return user;
}
/**
* Clear session details
*/
public void logoutUser() {
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to Loing Activity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_CLEAR_TASK |
Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
// Staring Login Activity
_context.startActivity(i);
}
/**
* Quick check for login
* *
*/
// Get Login State
public boolean isLoggedIn() {
return pref.getBoolean(IS_LOGIN, false);
}
}
and called it in LoginActivity class ...
session = new SessionManager(getApplicationContext());
SharedPreferences pref = session.pref;
Please have a look at using PHP with MySQL.
for auto login, I recommend you to keep session in preference other than keeping user id and password.
My database have two table, which is login and details.
login is used to store username (PK), and password and details is to store the username (FK), user's photo, details..
I want to keep the username shown in header so I can get the username and store it in details table.
How try to use bundles get extras() method to get the username and shown in header, but can't work if I intent back to those page.
Any idea how can I fix the username in header?
Or what should I do to ensure the user's details can store in the correct user database when user click "store button".
If you are calling Activity1 --- > Activity2
You can send the UserName by this method
Intent intent = new Intent(getBaseContext(), Activity2.class);
intent.putExtra("UserName ", UserName );
startActivity(intent);
To retrive the Extra() in Activity2, you need this code
String UserName = (String) getIntent().getSerializableExtra("UserName ");
Hope this helps
Below Edit for Better Understanding
public class Activity2 extends Activity {
private String UserName;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_2);
UserName= (String) getIntent().getSerializableExtra("UserName");
Log.i(Tag, "UserName: "+ UserName);
}
// you can call this method from click or where ever you want
private void AnyMethod()
{
Intent intent = new Intent(getBaseContext(), Activity3.class);
intent.putExtra("UserName ", UserName );
startActivity(intent);
}
}
You can have static object in the activity that object contains username and details of the user. When you intent back then you can assign current object to that static object. In this way you will be able to get the same user on previous activity.
Let's say you have an activity A from which you intent to the details activity. Create a public static user object that contains all the details of that user in A. When you intent back from details activity then assign A.user = current user object. In this way you can have the same user after you intent back and you can show username on the header on.