I am trying to develop an authentication android based webservice Rest,I am using the library Retrofit with async task as an inner class .
I have a variable called loginstatus returns true if the user exists otherwise false .
the problem is when the compiler out of the success method isloginstatus initializes to false.
Here is my activity code :
public class CheckLoginActivity extends Activity {
static AlertDialog dialog;
Button b;
UserModel userModel;
TextView statusTV;
EditText userNameET, passWordET;
String editTextUsername;
boolean loginStatus;
String editTextPassword;
String API_URL = "http://192.168.42.60/task_manager/v1/index.php";
SharedPreferences sharedpreferences;
public static final String USERPREFERENCE = "userPreference";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_login);
final TextInputLayout usernameWrapper = (TextInputLayout) findViewById(R.id.usernameWrapper);
final TextInputLayout passwordWrapper = (TextInputLayout) findViewById(R.id.passwordWrapper);
usernameWrapper.setHint("Username");
passwordWrapper.setHint("Password");
dialog = new SpotsDialog(this, "Chargement");
//NameText control
userNameET = (EditText) findViewById(R.id.editText1);
passWordET = (EditText) findViewById(R.id.editText2);
//Display Text control
statusTV = (TextView) findViewById(R.id.tv_result);
//Button to trigger web service invocation
b = (Button) findViewById(R.id.button1);
//Display progress bar until web service invocation completes
//Button Click Listener
sharedpreferences = getSharedPreferences(USERPREFERENCE, Context.MODE_PRIVATE);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Check if text controls are not empty
if (userNameET.getText().length() != 0 && userNameET.getText().toString() != "") {
if (passWordET.getText().length() != 0 && passWordET.getText().toString() != "") {
editTextUsername = userNameET.getText().toString();
editTextPassword = passWordET.getText().toString();
// statusTV.setText("");
//Create instance for AsyncCallWS
AsyncCallWS task = new AsyncCallWS();
//Call execute
task.execute(editTextUsername, editTextPassword);
}
//If Password text control is empty
else {
statusTV.setText("Please enter Password");
}
//If Username text control is empty
} else {
statusTV.setText("Please enter Username");
}
}
});
}
and my async task
private class AsyncCallWS extends AsyncTask<String, String, Void> {
//Make Progress Bar visible
protected void onPreExecute() {
dialog.show();
}
#Override
protected Void doInBackground(String... params) {
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API_URL)
.build();
geolocateApi post = restAdapter.create(geolocateApi.class);
post.login(editTextUsername, editTextPassword, new Callback<UserModel>() {
#Override
public void success(UserModel userModelRecv, Response response) {
if (userModelRecv != null) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("username", userModelRecv.getUsername());
editor.putString("id", userModelRecv.getUser_id());
editor.putString("firstName", userModelRecv.getFirstName());
editor.putString("lastName", userModelRecv.getLastName());
editor.putString("Role", userModelRecv.getRole());
userModel=userModelRecv;
editor.commit();
loginStatus=true;
}else loginStatus=false;
}
#Override
public void failure(RetrofitError error) {
}
});
return null;
}
#Override
//Once WebService returns response
protected void onPostExecute(Void result) {
//Make Progress Bar invisible
Intent intSucces = new Intent(CheckLoginActivity.this, HomeActivity.class);
try {
Thread.sleep(200);
} catch (Exception e) {
e.printStackTrace();
}
dialog.hide();
//Error status is false
if (loginStatus) {
//Based on Boolean value returned from WebService
//Navigate to Home Screen
startActivity(intSucces);
} else {
//Set Error message
statusTV.setText("Login Failed, try again");
}
}
}
my interface Retrofit
public interface geolocateApi {
#FormUrlEncoded
#POST("/login")
public boolean login(#Field("username") String username,#Field("password") String password, Callback<UserModel> response);
}
Thanks for your help
You are using Retrofit for your login with a callback which basically sends request asynchronously. So by the time your onPostExecute is executed retrofit request might still be processing leaving your loginStatus to default false value. You don't need AsyncTask here as login already is running in background. It should be something like this
public class CheckLoginActivity extends Activity {
static AlertDialog dialog;
Button b;
UserModel userModel;
TextView statusTV;
EditText userNameET, passWordET;
String editTextUsername;
boolean loginStatus;
String editTextPassword;
String API_URL = "http://192.168.42.60/task_manager/v1/index.php";
SharedPreferences sharedpreferences;
public static final String USERPREFERENCE = "userPreference";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_login);
final TextInputLayout usernameWrapper = (TextInputLayout) findViewById(R.id.usernameWrapper);
final TextInputLayout passwordWrapper = (TextInputLayout) findViewById(R.id.passwordWrapper);
usernameWrapper.setHint("Username");
passwordWrapper.setHint("Password");
dialog = new SpotsDialog(this, "Chargement");
//NameText control
userNameET = (EditText) findViewById(R.id.editText1);
passWordET = (EditText) findViewById(R.id.editText2);
//Display Text control
statusTV = (TextView) findViewById(R.id.tv_result);
//Button to trigger web service invocation
b = (Button) findViewById(R.id.button1);
//Display progress bar until web service invocation completes
//Button Click Listener
sharedpreferences = getSharedPreferences(USERPREFERENCE, Context.MODE_PRIVATE);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Check if text controls are not empty
if (userNameET.getText().length() != 0 && userNameET.getText().toString() != "") {
if (passWordET.getText().length() != 0 && passWordET.getText().toString() != "") {
editTextUsername = userNameET.getText().toString();
editTextPassword = passWordET.getText().toString();
// statusTV.setText("");
//Create instance for AsyncCallWS
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API_URL)
.build();
geolocateApi post = restAdapter.create(geolocateApi.class);
post.login(editTextUsername, editTextPassword, new Callback<UserModel>() {
#Override
public void success(UserModel userModelRecv, Response response) {
dialog.hide();
if (userModelRecv != null) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("username", userModelRecv.getUsername());
editor.putString("id", userModelRecv.getUser_id());
editor.putString("firstName", userModelRecv.getFirstName());
editor.putString("lastName", userModelRecv.getLastName());
editor.putString("Role", userModelRecv.getRole());
userModel = userModelRecv;
editor.commit();
loginStatus = true;
Intent intSucces = new Intent(CheckLoginActivity.this, HomeActivity.class);
startActivity(intSucces);
} else {
loginStatus = false;
statusTV.setText("Login Failed, try again");
}
}
#Override
public void failure(RetrofitError error) {
}
});
}
//If Password text control is empty
else {
statusTV.setText("Please enter Password");
}
//If Username text control is empty
} else {
statusTV.setText("Please enter Username");
}
}
});
}
}
Related
I am developing an android app, my app have a login activity. What i want to do is once a user is logged in for the first time it will remain logged in even if the app is closed.
I tried a way out but it didn't worked well.
Any help will b appreciated.
Thanks!
1) Login.java
private Snackbar snackbar;
private ProgressDialog pd;
private TextInputLayout mTiEmail;
private TextInputLayout mTiPassword;
private CompositeSubscription mSubscriptions;
private SharedPreferences mSharedPreferences;
private Boolean loggedIn = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mSubscriptions = new CompositeSubscription();
mSubscriptions = new CompositeSubscription();
loginUserName = (EditText) findViewById(R.id.email_edit);
loginPassword = (EditText) findViewById(R.id.pass_edit);
pd = new ProgressDialog(Login.this);
mTiEmail = (TextInputLayout) findViewById(R.id.email1);
mTiPassword = (TextInputLayout) findViewById(R.id.password);
loginButton = (TextView)findViewById(R.id.btn_login);
initSharedPreferences();
loginButton.setOnClickListener(view -> login());
}
#Override
protected void onResume() {
super.onResume();
//In onresume fetching value from sharedpreference
SharedPreferences sharedPreferences = getSharedPreferences(Constants.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Fetching the boolean value form sharedpreferences
loggedIn = sharedPreferences.getBoolean(Constants.LOGGEDIN_SHARED_PREF, false);
//If we will get true
if (loggedIn) {
//We will start the Profile Activity
Intent intent = new Intent(Login.this, Dashboard.class);
startActivity(intent);
}
}
private void initSharedPreferences() {
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(Login.this);
}
private void login() {
setError();
String email = loginUserName.getText().toString();
String password = loginPassword.getText().toString();
int err = 0;
if (!validateEmail(email)) {
err++;
mTiEmail.setError("Email should be valid !");
}
if (!validateFields(password)) {
err++;
mTiPassword.setError("Password should not be empty !");
}
if (err == 0) {
loginProcess(email,password);
} else {
Toast.makeText(this, "Enter valid details", Toast.LENGTH_SHORT).show();
}
}
private void setError() {
loginUserName.setError(null);
loginPassword.setError(null);
}
private void loginProcess(String email, String password) {
mSubscriptions.add(NetworkUtil.getRetrofit(email,password).login()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(this::handleResponse,this::handleError));
}
private void handleResponse(Response response) {
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString(Constants.TOKEN,response.getToken());
editor.putString(Constants.EMAIL,response.getMessage());
editor.apply();
loginUserName.setText(null);
loginPassword.setText(null);
Intent in = new Intent(Login.this,Dashboard.class);
startActivity(in);
Toast.makeText(this, "REGISTERED-->>", Toast.LENGTH_LONG).show();
}
private void handleError(Throwable error) {
if (error instanceof HttpException) {
Gson gson = new GsonBuilder().create();
try {
String errorBody = ((HttpException) error).response().errorBody().string();
Response response = gson.fromJson(errorBody,Response.class);
Toast.makeText(this, response.getMessage(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
Here in my onResume() method i tried a way out but didn't work, Any Suggestions?
2) Constants.java
public class Constants {
public static final String BASE_URL = "http://192.168.2.145:8080/api/v1/";
public static final String TOKEN = "token";
public static final String EMAIL = "email";
//This would be the name of our shared preferences
public static final String SHARED_PREF_NAME = "myloginapp";
//This would be used to store the email of current logged in user
public static final String EMAIL_SHARED_PREF = "email";
//We will use this to store the boolean in sharedpreference to track user is loggedin or not
public static final String LOGGEDIN_SHARED_PREF = "loggedin";
}
UPDATE
Login.java
public class Login extends AppCompatActivity {
TextView loginButton;
EditText loginUserName, loginPassword;
private Snackbar snackbar;
private ProgressDialog pd;
private TextInputLayout mTiEmail;
private TextInputLayout mTiPassword;
private CompositeSubscription mSubscriptions;
private SharedPreferences mSharedPreferences;
private Boolean loggedIn = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mSubscriptions = new CompositeSubscription();
mSubscriptions = new CompositeSubscription();
loginUserName = (EditText) findViewById(R.id.email_edit);
loginPassword = (EditText) findViewById(R.id.pass_edit);
pd = new ProgressDialog(Login.this);
mTiEmail = (TextInputLayout) findViewById(R.id.email1);
mTiPassword = (TextInputLayout) findViewById(R.id.password);
loginButton = (TextView)findViewById(R.id.btn_login);
initSharedPreferences();
loginButton.setOnClickListener(view -> login());
}
#Override
protected void onResume() {
super.onResume();
//In onresume fetching value from sharedpreference
mSharedPreferences = getSharedPreferences("login", Context.MODE_PRIVATE);
if(mSharedPreferences.getBoolean("LoggedIn", false)){
Intent intent = new Intent(Login.this,Dashboard.class);
startActivity(intent);
} else {
loginButton.setOnClickListener(view -> login());
//Do other stuff
}
}
private void initSharedPreferences() {
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(Login.this);
}
private void login() {
String username = loginUserName.getText().toString();
String password = loginPassword.getText().toString();
loginProcess(username,password);
int err = 0;
if (!validateFields(username)&& !validateFields(password)) {
err++;
mTiEmail.setError("Username should not be empty !");
}
if (err == 0) {
loginProcess(username,password);
} else {
Toast.makeText(this, "Enter valid details", Toast.LENGTH_SHORT).show();
}
}
private void loginProcess(String username,String password){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitInterface requestInterface = retrofit.create(RetrofitInterface.class);
User user = new User();
user.setUsername(username);
user.setPassword(password);
ServerRequest request = new ServerRequest();
request.setOperation(Constants.LOGIN_OPERATION);
request.setUser(user);
Call<ServerResponse> response = requestInterface.operation(request);
response.enqueue(new Callback<ServerResponse>() {
#Override
public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {
if(response.isSuccessful()) {
ServerResponse serverResponse = response.body();
if(serverResponse.getMessage().equals(Constants.SUCCESS)) {
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putBoolean("LoggedIn",true);
//editor.putString(Constants.EMAIL,serverResponse.getUser().getEmail());
editor.putString(Constants.USERNAME,serverResponse.getUser().getUsername());
editor.putString(Constants.BUSINESSNAME,serverResponse.getUser().getBusinessname());
editor.apply();
Toast.makeText(Login.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
goToProfile();
} else {
Toast.makeText(Login.this, serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
Gson gson = new Gson();
ServerResponse errorResponse = null;
try {
errorResponse = gson.fromJson(response.errorBody().string(), ServerResponse.class);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(Login.this, errorResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ServerResponse> call, Throwable t) {
Log.d(Constants.TAG,"failed");
Toast.makeText(Login.this,t.getLocalizedMessage() , Toast.LENGTH_SHORT).show();
}
});
}
private void goToProfile(){
Intent intent = new Intent(this,Dashboard.class);
startActivity(intent);
}
}
Put this code in your onCreate()
SharedPreferences pref = getSharedPrefrences("login", Context.MODE_PRIVATE); //Opening 'login' sharedPreference
if(pref.getBoolean("LoggedIn", false)){ //checking if 'LoggedIn' exist in SharedPreference if no exist it returns false. if it exist fetches its value
//Move to Next Screen
} else {
loginButton.setOnClickListener(view -> login());
//Do other stuff
}
Then in your handleResponse().. Add these lines
//Lets suppose if User is logging in for the First time.. Below lines will add 'LoggedIn' to shared preference so user logged in directly next time
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("LoggedIn", true);
editor.apply();
Set LOGGEDIN_SHARED_PREF in your void handleResponse() as below :
editor.putBoolean(Constants.LOGGEDIN_SHARED_PREF,true);
Set your sharedPreferences globally
SharedPreferences sharedPreferences = getSharedPreferences(Constants.SHARED_PREF_NAME, Context.MODE_PRIVATE);
And edit on the same in your handleReponse()
SharedPreferences.Editor editor = sharedPreferences.edit();
I updated your code:
private Snackbar snackbar;
private ProgressDialog pd;
private TextInputLayout mTiEmail;
private TextInputLayout mTiPassword;
private CompositeSubscription mSubscriptions;
private SharedPreferences sharedPreferences;
private Boolean loggedIn = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mSubscriptions = new CompositeSubscription();
mSubscriptions = new CompositeSubscription();
loginUserName = (EditText) findViewById(R.id.email_edit);
loginPassword = (EditText) findViewById(R.id.pass_edit);
pd = new ProgressDialog(Login.this);
mTiEmail = (TextInputLayout) findViewById(R.id.email1);
mTiPassword = (TextInputLayout) findViewById(R.id.password);
loginButton = (TextView)findViewById(R.id.btn_login);
loginButton.setOnClickListener(view -> login());
}
#Override
protected void onResume() {
super.onResume();
//In onresume fetching value from sharedpreference
sharedPreferences = getSharedPreferences(Constants.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Fetching the boolean value form sharedpreferences
loggedIn = sharedPreferences.getBoolean(Constants.LOGGEDIN_SHARED_PREF, false);
//If we will get true
if (loggedIn) {
//We will start the Profile Activity
Intent intent = new Intent(Login.this, Dashboard.class);
startActivity(intent);
}
}
private void login() {
setError();
String email = loginUserName.getText().toString();
String password = loginPassword.getText().toString();
int err = 0;
if (!validateEmail(email)) {
err++;
mTiEmail.setError("Email should be valid !");
}
if (!validateFields(password)) {
err++;
mTiPassword.setError("Password should not be empty !");
}
if (err == 0) {
loginProcess(email,password);
} else {
Toast.makeText(this, "Enter valid details", Toast.LENGTH_SHORT).show();
}
}
private void setError() {
loginUserName.setError(null);
loginPassword.setError(null);
}
private void loginProcess(String email, String password) {
mSubscriptions.add(NetworkUtil.getRetrofit(email,password).login()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(this::handleResponse,this::handleError));
}
private void handleResponse(Response response) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Constants.TOKEN,response.getToken());
editor.putString(Constants.EMAIL,response.getMessage());
editor.putBoolean(Constants.LOGGEDIN_SHARED_PREF,true);
editor.apply();
loginUserName.setText(null);
loginPassword.setText(null);
Intent in = new Intent(Login.this,Dashboard.class);
startActivity(in);
Toast.makeText(this, "REGISTERED-->>", Toast.LENGTH_LONG).show();
}
private void handleError(Throwable error) {
if (error instanceof HttpException) {
Gson gson = new GsonBuilder().create();
try {
String errorBody = ((HttpException) error).response().errorBody().string();
Response response = gson.fromJson(errorBody,Response.class);
Toast.makeText(this, response.getMessage(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
I have an application android with login activity. my application work perfectly but after I login and I close my application and than I open it again I always must login first. I don't know how to make my program just login once time.
My code like this
public class MainActivity extends Activity {
TextView btnForgot;
Button btnLogin;
EditText inputEmail;
EditText inputPassword;
private TextView loginErrorMsg;
private TextView macmac, macmac1;
private ProgressDialog pDialog;
private static String KEY_SUCCESS = "success";
private static String KEY_UID = "uid";
private static String KEY_USERNAME = "uname";
private static String KEY_FIRSTNAME = "fname";
private static String KEY_LASTNAME = "lname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private static String MAC = "mac_0";
JSONParser jParser = new JSONParser();
JSONArray products = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnForgot = (TextView) findViewById(R.id.textView);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
loginErrorMsg = (TextView) findViewById(R.id.loginErrorMsg);
TypedValue typedValueColorPrimaryDark = new TypedValue();
MainActivity.this.getTheme().resolveAttribute(R.attr.colorPrimary, typedValueColorPrimaryDark, true);
final int colorPrimaryDark = typedValueColorPrimaryDark.data;
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(colorPrimaryDark);
}
/** Button Forgot Password **/
btnForgot.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), PasswordResetActivity.class);
startActivityForResult(myIntent, 0);
finish();
}});
/** Button Login **/
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if ( ( !inputEmail.getText().toString().equals("")) && ( !inputPassword.getText().toString().equals("")) )
{
NetAsync(view);
}
else if ( ( !inputEmail.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(), "Password field empty", Toast.LENGTH_SHORT).show();
}
else if ( ( !inputPassword.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(), "Email field empty", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "Email and Password field are empty", Toast.LENGTH_SHORT).show();
}
}
});
}
private class NetCheck extends AsyncTask<String,String,Boolean>
{
private ProgressDialog nDialog;
#Override
protected void onPreExecute(){
super.onPreExecute();
nDialog = new ProgressDialog(MainActivity.this);
nDialog.setTitle("Checking Network");
nDialog.setMessage("Loading..");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
/** Gets current device state and checks for working internet connection by trying Google **/
#Override
protected Boolean doInBackground(String... args){
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Boolean th){
if(th == true){
nDialog.dismiss();
new ProcessLogin().execute();
}
else{
nDialog.dismiss();
loginErrorMsg.setText("Error in Network Connection");
}
}
}
/** Async Task to get and send data to My Sql database through JSON respone **/
private class ProcessLogin extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
String email,password,mac1;
#Override
protected void onPreExecute() {
super.onPreExecute();
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
email = inputEmail.getText().toString();
password = inputPassword.getText().toString();
//mac1 = macmac.getText().toString();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Logging in ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email, password);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
pDialog.setMessage("Loading User Space");
pDialog.setTitle("Getting Data");
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
/** Clear all previous data in SQlite database **/
UserFunctions logout = new UserFunctions();
logout.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_LASTNAME),json_user.getString(KEY_EMAIL),json_user.getString(KEY_USERNAME),json_user.getString(KEY_UID),json_user.getString(KEY_CREATED_AT));
/** If JSON array details are stored in SQlite it launches the User Panel **/
Intent upanel = new Intent(getApplicationContext(), HomeActivity.class);
upanel.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pDialog.dismiss();
new status_login().execute();
startActivity(upanel);
/** Close Login Screen **/
finish();
}else{
pDialog.dismiss();
loginErrorMsg.setText("Incorrect username or password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public void NetAsync(View view){
new NetCheck().execute();
}
}
anyone can help me to make my application just one time login?
thanks before
You must store the values within shared preference so that, untill the app data is cleared or no session destroyed by the user, user will be logged in within application, and the login screen will appear only once.
in you post execute, you know that your user has logged in successfully or not. so it would not so bad to set a preference to set that login is true, so in another activity you can check the value of that shared preference value and if it true then he was logged in successfully otherwise not. so write something the following way
// in this method where you find your user either to be logged in or failed
#Override
protected void onPostExecute(JSONObject json) {
try {
if (json.getString(KEY_SUCCESS) != null) {
if (login == true) {
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(getString(R.string.login), true);
editor.commit();
}
}
}
and your main activity check for it as shown below
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
boolean login = getResources().getBoolean(R.string.login);
if (login) {
// do what you want to do
} else {
// prompt for login again
}
know more about SharedPreference
This is Your Answer
public class MainActivity extends Activity {
TextView btnForgot;
Button btnLogin;
EditText inputEmail;
EditText inputPassword;
private TextView loginErrorMsg;
private TextView macmac, macmac1;
private ProgressDialog pDialog;
private static String KEY_SUCCESS = "success";
private static String KEY_UID = "uid";
private static String KEY_USERNAME = "uname";
private static String KEY_FIRSTNAME = "fname";
private static String KEY_LASTNAME = "lname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private static String MAC = "mac_0";
JSONParser jParser = new JSONParser();
JSONArray products = null;
SharedPreferences sharedPref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPref = getSharedPreferences("MysharePrefrence", MODE_PRIVATE);
editor = sharedPref.edit();
boolean login = sharedPref.getBoolean("isLogin",false);
if (login)
{
Intent upanel = new Intent(getApplicationContext(), HomeActivity.class);
upanel.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(upanel);
finish();
}
btnForgot = (TextView) findViewById(R.id.textView);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
loginErrorMsg = (TextView) findViewById(R.id.loginErrorMsg);
TypedValue typedValueColorPrimaryDark = new TypedValue();
MainActivity.this.getTheme().resolveAttribute(R.attr.colorPrimary, typedValueColorPrimaryDark, true);
final int colorPrimaryDark = typedValueColorPrimaryDark.data;
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(colorPrimaryDark);
}
/** Button Forgot Password **/
btnForgot.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), PasswordResetActivity.class);
startActivityForResult(myIntent, 0);
finish();
}});
/** Button Login **/
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if ( ( !inputEmail.getText().toString().equals("")) && ( !inputPassword.getText().toString().equals("")) )
{
NetAsync(view);
}
else if ( ( !inputEmail.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(), "Password field empty", Toast.LENGTH_SHORT).show();
}
else if ( ( !inputPassword.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(), "Email field empty", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "Email and Password field are empty", Toast.LENGTH_SHORT).show();
}
}
});
}
private class NetCheck extends AsyncTask<String,String,Boolean>
{
private ProgressDialog nDialog;
#Override
protected void onPreExecute(){
super.onPreExecute();
nDialog = new ProgressDialog(MainActivity.this);
nDialog.setTitle("Checking Network");
nDialog.setMessage("Loading..");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
/** Gets current device state and checks for working internet connection by trying Google **/
#Override
protected Boolean doInBackground(String... args){
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Boolean th){
if(th == true){
nDialog.dismiss();
new ProcessLogin().execute();
}
else{
nDialog.dismiss();
loginErrorMsg.setText("Error in Network Connection");
}
}
}
/** Async Task to get and send data to My Sql database through JSON respone **/
private class ProcessLogin extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
String email,password,mac1;
#Override
protected void onPreExecute() {
super.onPreExecute();
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
email = inputEmail.getText().toString();
password = inputPassword.getText().toString();
//mac1 = macmac.getText().toString();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Logging in ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email, password);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
pDialog.setMessage("Loading User Space");
pDialog.setTitle("Getting Data");
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
/** Clear all previous data in SQlite database **/
UserFunctions logout = new UserFunctions();
logout.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_LASTNAME),json_user.getString(KEY_EMAIL),json_user.getString(KEY_USERNAME),json_user.getString(KEY_UID),json_user.getString(KEY_CREATED_AT));
/** If JSON array details are stored in SQlite it launches the User Panel **/
editor.putBoolean("isLogin",true);
editor.commit();
Intent upanel = new Intent(getApplicationContext(), HomeActivity.class);
upanel.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pDialog.dismiss();
new status_login().execute();
startActivity(upanel);
/** Close Login Screen **/
finish();
}else{
pDialog.dismiss();
loginErrorMsg.setText("Incorrect username or password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public void NetAsync(View view){
new NetCheck().execute();
}
}
You can use a SharedPreferences object to save the login status. Once a user is successfully login you store a boolean flag, for example:
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("signed_in", true);
editor.commit();
Next time you will just check this value.
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
if (sharedPref.getBoolean("signed_in", false) == true){
//user is login
}else{
//user not login
}
I finally got my login and registration to work. Once I get a success on login, how do I move to the next activity? I thought I put the Intent in the right place in the PostExecute, but it's not moving forward. Can you take a look and assist?
LoginActivity.java
public class LoginActivity extends AppCompatActivity implements View.OnClickListener{
public static final String EMAIL = "EMAIL";
public static final String PASSWORD = "PASSWORD";
private static final String LOGIN_URL = "http://www.contrariantradefx.info/android/btfxalerts/login.php";
private EditText editTextEmail;
private EditText editTextPassword;
private Button buttonLogin;
private Button buttonRegister;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
buttonLogin = (Button) findViewById(R.id.buttonLogin);
buttonRegister = (Button) findViewById(R.id.buttonRegister);
buttonLogin.setOnClickListener(this);
}
private void login(){
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
userLogin(email,password);
}
private void userLogin(final String email, final String password){
class UserLoginClass extends AsyncTask<String,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(LoginActivity.this,"Please Wait",null,true,true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
s = s.trim();
if(s.equalsIgnoreCase("success")){
**Intent intent = new Intent(LoginActivity.this,GoogleInAppBilling.class);
intent.putExtra(email,email);
startActivity(intent);**
}else{
Toast.makeText(LoginActivity.this,s,Toast.LENGTH_LONG).show();
}
}
#Override
protected String doInBackground(String... params) {
HashMap<String,String> data = new HashMap<>();
data.put("email",params[0]);
data.put("password",params[1]);
RegisterUserClass ruc = new RegisterUserClass();//todo leave class here but we are not using this to register
String result = ruc.sendPostRequest(LOGIN_URL,data);
return result;
}
}
UserLoginClass ulc = new UserLoginClass();
ulc.execute(email, password);
}
#Override
public void onClick(View v) {
if(v == buttonLogin){
login();
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v){
Intent intent = new Intent(LoginActivity.this, UserRegistration.class);
startActivity(intent);
}
});
};
}
}
RegisterUserClass
}else{
Toast.makeText(LoginActivity.this,s,Toast.LENGTH_LONG).show();
If your response from Back end is in Json Foramt parse response like this
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try{
JSONObject jObject = new JSONObject(s);
if (jObject.has("success")) {
**Intent intent = new Intent(LoginActivity.this,GoogleInAppBilling.class);
intent.putExtra(email,email);
startActivity(intent);**
}else{
Toast.makeText(LoginActivity.this,s,Toast.LENGTH_LONG).show();
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
loading.dismiss();
}
}else{
Toast.makeText(LoginActivity.this,s,Toast.LENGTH_LONG).show();
I have made an app in which first the user verifies its number with the help of sinch verification and then after succesfull verification it goes to the gameactivity but the problem is that every time the user opens the app he or she has to verify again which is a very bad out come.
i dont how o skip the verification process after again opening the app
Main Activity
public class MainActivity extends Activity {
public static final String SMS = "sms";
public static final String FLASHCALL = "flashcall";
public static final String INTENT_PHONENUMBER = "phonenumber";
public static final String INTENT_METHOD = "method";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TelephonyManager manager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
TextView phoneNumber = (TextView) findViewById(R.id.phoneNumber);
phoneNumber.setText(manager.getLine1Number());
}
private void openActivity(String phoneNumber, String method) {
Intent verification = new Intent(this, VerificationActivity.class);
verification.putExtra(INTENT_PHONENUMBER, phoneNumber);
verification.putExtra(INTENT_METHOD, method);
startActivity(verification);
}
private boolean checkInput() {
TextView phoneNumber = (TextView) findViewById(R.id.phoneNumber);
if (phoneNumber.getText().toString().isEmpty()) {
Toast.makeText(this, "Please input a phone number.", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
public void onButtonClicked(View view) {
if (checkInput()) {
TextView phoneNumber = (TextView) findViewById(R.id.phoneNumber);
if (view == findViewById(R.id.smsVerificationButton)) {
openActivity(phoneNumber.getText().toString(), SMS);
} else if (view == findViewById(R.id.callVerificationButton)) {
openActivity(phoneNumber.getText().toString(), FLASHCALL);
}
}
}
}
Verification Activity
public class VerificationActivity extends Activity {
private static final String TAG = Verification.class.getSimpleName();
private final String APPLICATION_KEY = "af23************************";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verification);
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressIndicator);
progressBar.setVisibility(View.VISIBLE);
Intent intent = getIntent();
if (intent != null) {
String phoneNumber = intent.getStringExtra(MainActivity.INTENT_PHONENUMBER);
String method = intent.getStringExtra(MainActivity.INTENT_METHOD);
TextView phoneText = (TextView) findViewById(R.id.numberText);
phoneText.setText(phoneNumber);
createVerification(phoneNumber, method);
}
}
void createVerification(String phoneNumber, String method) {
Config config = SinchVerification.config().applicationKey(APPLICATION_KEY).context(getApplicationContext())
.build();
VerificationListener listener = new MyVerificationListener();
Verification verification;
if (method.equalsIgnoreCase(MainActivity.SMS)) {
verification = SinchVerification.createSmsVerification(config, phoneNumber, listener);
} else {
TextView messageText = (TextView) findViewById(R.id.textView);
messageText.setText(R.string.flashcalling);
verification = SinchVerification.createFlashCallVerification(config, phoneNumber, listener);
}
verification.initiate();
}
class MyVerificationListener implements VerificationListener {
#Override
public void onInitiated() {
Log.d(TAG, "Initialized!");
}
#Override
public void onInitiationFailed(Exception exception) {
Log.e(TAG, "Verification initialization failed: " + exception.getMessage());
hideProgress(R.string.failed, false);
}
#Override
public void onVerified() {
Log.d(TAG, "Verified!");
hideProgress(R.string.verified, true);
}
#Override
public void onVerificationFailed(Exception exception) {
Log.e(TAG, "Verification failed: " + exception.getMessage());
hideProgress(R.string.failed, false);
}
}
void hideProgress(int message, boolean success) {
if (success) {
ImageView checkMark = (ImageView) findViewById(R.id.checkmarkImage);
checkMark.setVisibility(View.VISIBLE);
}
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressIndicator);
progressBar.setVisibility(View.INVISIBLE);
TextView progressText = (TextView) findViewById(R.id.progressText);
progressText.setVisibility(View.INVISIBLE);
TextView messageText = (TextView) findViewById(R.id.textView);
messageText.setText(message);
}
}
I just want that on re opening verification process should not be again called.
You can use SharedPreferences. add a key to your SharedPreferences object and initialize with value 0. You can do something like below
SharedPrefences prefences = PrefenceManager.getSharedPreferences("TAG",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
Now on successfull verification :
preferences.putInt("key",1);
so on next launch check for this key value, if its 1 skip the VerificationActivity and start GameActivtiy i.e
int value = preferences.getInt("key",0);
if(value == 0){
// Verify
}else{
// Skip Verification
}
How to create SharedPreferences with set visibility in login if the user is successfully login the button will be logout and the login will be gone
public class Login extends ActionBarActivity implements View.OnClickListener{
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static String url_check_login = "";
private static final String TAG_SUCCESS = "success";
Context cont=this;
EditText uname, pword;
Boolean nega = false;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_user);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
uname = (EditText) findViewById(R.id.uname);
pword = (EditText) findViewById(R.id.pword);
Button login = (Button)findViewById(R.id.btnLogin);
login.setOnClickListener(this);
Button register = (Button)findViewById(R.id.btnRegister);
register.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
final int id = v.getId();
switch (id) {
case R.id.btnLogin:
new SubmitLogin().execute();
break;
case R.id.btnRegister:
Intent i = new Intent (this, Registration.class);
startActivity(i);
finish();
break;
// even more buttons here
}
}
class SubmitLogin extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Logging In ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", uname.getText().toString()));
params.add(new BasicNameValuePair("pass", pword.getText().toString()));
JSONObject json = jsonParser.makeHttpRequest(url_check_login, "POST", params);
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
nega = false;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", uname.getText().toString());
editor.commit();
Intent gotoLogs = new Intent(cont, MainActivity.class);
startActivity(gotoLogs);
finish();
} else {
nega = true;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
if (nega) {
new AlertDialog.Builder(cont)
.setTitle("Login Failed")
.setMessage("Wrong Username or Password")
.setNegativeButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
//Close current activity
startActivity(new Intent(this,MainActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
To place info into SharedPreferences you should write following:
SharedPreferences sp = getSharedPreferences(PREFERNCES_FILE, MODE_PRIVATE);
sp.edit().putString(PREFERENCES_LOGIN, login).apply();
Variables PREFERNCES_FILE and PREFERENCES_LOGIN should be defined as String:
public static final String PREFERNCES_FILE = "my_preferences_file";
public static final String PREFERENCES_LOGIN = "login";
On logout there should be:
sp.edit().remove(PREFERENCES_LOGIN).apply();
Then to check if there is allready some info call:
boolean isLogged = sp.contains(PREFERENCES_LOGIN);
Then just set needed visibility:
login.setVisibility(isLogged ? View.GONE : View.VISIBLE);
UPDATE
Ok, here is example. This code should be in onCreate:
SharedPreferences sp = getSharedPreferences(PREFERNCES_FILE, MODE_PRIVATE);
boolean isLogged = sp.contains(PREFERENCES_LOGIN);
Button login = (Button)findViewById(R.id.btnLogin);
login.setVisibility(isLogged ? View.GONE : View.VISIBLE);
login.setOnClickListener(this);
Button logout = (Button)findViewById(R.id.btnLogout);
logout.setVisibility(isLogged ? View.VISIBLE : View.GONE);
logout.setOnClickListener(this);
And there should be button in your login_user xml with btnLogout id.
In onClick should be:
#Override
public void onClick(View v)
{
final int id = v.getId();
switch (id) {
case R.id.btnLogin:
SharedPreferences sp = getSharedPreferences(PREFERNCES_FILE, MODE_PRIVATE);
sp.edit().putString(PREFERENCES_LOGIN, login).apply();
findViewById(R.id.btnLogin).setVisibility(View.GONE);
findViewById(R.id.btnLogout).setVisibility(View.VISIBLE);
//another actions after login
break;
case R.id.btnLogout:
SharedPreferences sp = getSharedPreferences(PREFERNCES_FILE, MODE_PRIVATE);
sp.edit().remove(PREFERENCES_LOGIN).apply();
findViewById(R.id.btnLogin).setVisibility(View.VISIBLE);
findViewById(R.id.btnLogout).setVisibility(View.GONE);
//another actions after logout
break;
// even more buttons here
}
}
In login variable should be login data - I don't know where you should get it.