I am trying to build an android application. After logged in to the application I want to use User_Id for all activities for getting unique data based on that user_id. How it is possible? And what changes i want to make in this code to get user_id in all activities?
LoginActivity.java
public class LoginActivityMerchant extends AppCompatActivity implements View.OnClickListener {
//Defining views
private AutoCompleteTextView ACTUser;
private EditText etPassword;
private Button buttonLogin;
private TextView linkToRegister;
private ProgressDialog loading;
public static final String KEY_firstName = "First_Name";
public static final String KEY_LastName = "Last_Name";
public static final String KEY_Mob = "Mobile";
public static final String KEY_ShopName = "Shop_Name";
public static final String KEY_Location = "Location";
public static final String KEY_Radius = "UserId";
public static final String JSON_ARRAY = "result";
public static final String KEY_UserName = "User_Name";
public static final String KEY_Password = "Password";
public TextView test;
//boolean variable to check user is logged in or not
//initially it is false
private boolean loggedIn = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_activity_merchant);
//Initializing views
ACTUser = (AutoCompleteTextView) findViewById(R.id.email);
etPassword = (EditText) findViewById(R.id.password);
buttonLogin = (Button) findViewById(R.id.email_sign_in_button);
linkToRegister = (TextView) findViewById(R.id.Reg_TextView);
test=(TextView)findViewById(R.id.test);
//Adding click listener
buttonLogin.setOnClickListener(this);
linkToRegister.setOnClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
//In onresume fetching value from sharedpreference
SharedPreferences sharedPreferences = getSharedPreferences(config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Fetching the boolean value form sharedpreferences
loggedIn = sharedPreferences.getBoolean(config.LOGGEDIN_SHARED_PREF, false);
//If we will get true
if(loggedIn){
//We will start the Profile Activity
//Config.KEY_USERNAME=Config.USERNAME_SHARED_PREF;
SharedPreferences sharedPreferences1 = getSharedPreferences(config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
String username = sharedPreferences1.getString(config.SHARED_PREF_NAME,"Not Available");
setInfos(username);
Intent intent = new Intent(LoginActivityMerchant.this, MainActivity.class);
startActivity(intent);
}
}
private void login(){
//Getting values from edit texts
final String user = ACTUser.getText().toString().trim();
final String password = etPassword.getText().toString().trim();
if(user.isEmpty()||password.isEmpty())
{
Toast.makeText(LoginActivityMerchant.this, "Please fill all the fields", Toast.LENGTH_LONG).show();
}
//Creating a string request
else{
StringRequest stringRequest = new StringRequest(Request.Method.POST, config.LOGIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//test.setText(response);
//If we are getting success from server
if(response.contains("success")){
//Creating a shared preference
// Toast.makeText(LoginActivityMerchant.this, "Success", Toast.LENGTH_LONG).show();
SharedPreferences sharedPreferences = LoginActivityMerchant.this.getSharedPreferences(config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Creating editor to store values to shared preferences
SharedPreferences.Editor editor = sharedPreferences.edit();
//Adding values to editor
editor.putBoolean(config.LOGGEDIN_SHARED_PREF, true);
editor.putString(config.SHARED_PREF_NAME, user);
config.KEY_USERNAME = user;
//Saving values to editor
editor.commit();
//Starting profile activity
//Intent intent = new Intent(LoginActivity.this, ProfileActivity.class);
setInfos(user);
Intent intent = new Intent(LoginActivityMerchant.this, MainActivity.class);
startActivity(intent);
}else{
//If the server response is not success
//Displaying an error message on toast
Toast.makeText(LoginActivityMerchant.this, "Invalid username or password", Toast.LENGTH_LONG).show();
ACTUser.setText(user);
etPassword.setText(password);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//You can handle error here if you want
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
//Adding parameters to request
params.put(KEY_UserName, user);
params.put(KEY_Password, password);
//test.setText(password);
//returning parameter
return params;
}
};
//Adding the string request to the queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}}
#Override
public void onClick(View v) {
//Calling the login function
if(v==buttonLogin){
login();
}
if(v==linkToRegister){
Intent intent = new Intent(LoginActivityMerchant.this, Registration.class);
startActivity(intent);
}
}
public void setInfos(String username){
String url = config.LOGIN_URL+username;
loading = ProgressDialog.show(this, " Please wait...", "Fetching...", false, false);
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivityMerchant.this, error.getMessage().toString(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response) {
String FirstName="";
String LastName="";
String UserName="";
String Mobile="";
String Location="";
String Radius="";
// String stringid="";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(JSON_ARRAY);
JSONObject userData = result.getJSONObject(0);
FirstName = userData.getString(KEY_firstName);
UserName = userData.getString(KEY_UserName);
LastName = userData.getString(KEY_LastName);
Mobile = userData.getString(KEY_Mob);
Location = userData.getString(KEY_Location);
//stringid=userData.getString(KEY_USERID);
} catch (JSONException e) {
e.printStackTrace();
}
config.KEY_NAME=FirstName + " "+LastName;
config.KEY_USERNAME=UserName;
}
}
loginold.php
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$username = $_POST['User_Name'];
$password = $_POST['Password'];
//Creating sql query
$sql = "SELECT * FROM User_Profile WHERE User_Name='$username' AND Password='$password'";
//importing dbConnect.php script
require_once('include/dbConnect.php');
//executing query
$result = mysqli_query($con,$sql);
//fetching result
$check = mysqli_fetch_array($result);
//if we got some result
if(isset($check)){
//displaying success
echo "success";
}else{
//displaying failure
echo "failure";
}
mysqli_close($con);
}
else
{echo "error";}
You can use SharedPreference :
public class SaveId {
static final String ID = "ID";
static SharedPreferences getSharedPreferences(Context ctx) {
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public static void setId(Context ctx, int value) {
SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
editor.putInt(ID, value);
editor.commit();
}
public static String getId(Context ctx) {
return getSharedPreferences(ctx).getString(ID, "");
}
}
When you want to set the id call SaveId.setId(yourID); and when you want to get the id call SaveId.getId();
Instead of read and write to SharedPreferences I would prefer a more efficient way to store a simple data like an ID.
There are two ways:
If you are using an MVP approach, you could delegate the setter and getter of the ID to your central manager, instead go for option 2
Set the id in your custom application and get it through it.
You have to override default application and set it in the manifest.
public class MyApplication extends Application {
private Integer id;
public void setId(int id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
In your activities you can get it through:
((MyApplication) getApplication()).getId();
Related
I am making a Register User activity and login user activity in android studio however there seems to be a problem with either my PHP scripts or the java for the login system.
It was working for me for a while but then something broke, i got my backup running however, my scripts only return "invalid username or password" when it is entered correctly.
Also, while i'm asking for help with this. This application is going to be a messaging/forum like application. Users will be anonymous for other viewers but visible to admins.
The users will enter rooms like on whatsapp where they can write a message to a group but with a reply functionality to each message.
And i began wondering whether i should use firebase for this sort of application where user register and login would be handled by firebase and also the messaging. Would it be possible to achieve this with firebase? Or is it a better approach using my own server and sql and so on....
Could you give me any guidance towards what i should bare in mind and what i should think about using.
The register user works fine, for now at least.
The full project and scripts can be found here:
https://github.com/Kraziion2/DatabaseApp2
scripts are called Android.
userLogin.php:
require_once '../includes/DbOperations.php';
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
if(isset($_POST['username']) and isset($_POST['password'])){
$db = new DbOperations();
if($db->userLogin($_POST['username'], $_POST['password'])){
$user = $db->getUserByUsername($_POST['username']);
$response['error'] = false;
$response['id'] = $user['id'];
$response['email'] = $user['email'];
$response['username'] = $user['username'];
}else{
$response['error'] = true;
$response['message'] = "Invalid username or password";
}
}else{
$response['error'] = true;
$response['message'] = "Required fields are missing";
}
}
echo json_encode($response);
DbOperations.php:
class DbOperations{
private $con;
function __construct(){
require_once dirname(__FILE__).'/DbConnect.php';
$db = new DbConnect();
$this->con = $db->connect();
}
/*CRUD -> C -> CREATE */
public function createUser($username, $pass, $email){
if($this->isUserExist($username,$email)){
return 0;
}else{
$password = md5($pass);
$stmt = $this->con->prepare("INSERT INTO `users` (`id`, `username`, `password`, `email`) VALUES (NULL, ?, ?, ?);");
$stmt->bind_param("sss",$username,$password,$email);
if($stmt->execute()){
return 1;
}else{
return 2;
}
}
}
public function userLogin($username, $pass){
$password = md5($pass);
$stmt = $this->con->prepare("SELECT id FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss",$username,$password);
$stmt->execute();
$stmt->store_result();
return $stmt->num_rows > 0;
}
public function getUserByUsername($username){
$stmt = $this->con->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s",$username);
$stmt->execute();
return $stmt->get_result()->fetch_assoc();
}
private function isUserExist($username, $email){
$stmt = $this->con->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
$stmt->bind_param("ss", $username, $email);
$stmt->execute();
$stmt->store_result();
return $stmt->num_rows > 0;
}
}
java:
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
private EditText editTextUsername, editTextPassword;
private Button buttonLogin;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
if(SharedPreferencesManager.getInstance(this).isLoggedIn()){
finish();
startActivity(new Intent(this, ProfileActivity.class));
return;
}
editTextUsername = (EditText) findViewById(R.id.editTextUsername);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
buttonLogin = (Button) findViewById(R.id.logInBtn);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Please wait...");
buttonLogin.setOnClickListener(this);
}
private void userLogin(){
final String username = editTextUsername.getText().toString().trim();
final String password = editTextPassword.getText().toString().trim();
progressDialog.show();
StringRequest stringRequest = new StringRequest(
Request.Method.POST,
Constants.URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject obj = new JSONObject(response);
if(!obj.getBoolean("error")){
SharedPreferencesManager.getInstance(getApplicationContext())
.userLogin(
obj.getInt("id"),
obj.getString("username"),
obj.getString("email")
);
startActivity(new Intent(getApplicationContext(), ProfileActivity.class));
finish();
}else{
Toast.makeText(
getApplicationContext(),
obj.getString("message"),
Toast.LENGTH_LONG
).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(
getApplicationContext(),
error.getMessage(),
Toast.LENGTH_LONG
).show();
}
}
){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("password", password);
return params;
}
};
NetworkRequestHandler.getInstance(this).addToRequestQueue(stringRequest);
}
#Override
public void onClick(View view) {
if(view == buttonLogin){
userLogin();
}
}
}
SharedPref java:
public class SharedPreferencesManager {
private static SharedPreferencesManager mInstance;
private static Context mCtx;
private static final String SHARED_PREFERENCE_NAME = "mysharedpref12";
private static final String KEY_USER_NAME = "username";
private static final String KEY_USER_EMAIL = "useremail";
private static final String KEY_USER_ID = "userid";
private SharedPreferencesManager(Context context) {
mCtx = context;
}
public static synchronized SharedPreferencesManager getInstance(Context context) {
if (mInstance == null) {
mInstance = new SharedPreferencesManager(context);
}
return mInstance;
}
public boolean userLogin(int id, String username, String email){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREFERENCE_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(KEY_USER_ID,id);
editor.putString(KEY_USER_EMAIL,email);
editor.putString(KEY_USER_NAME,username);
editor.apply();
return true;
}
public boolean isLoggedIn(){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREFERENCE_NAME,Context.MODE_PRIVATE);
if(sharedPreferences.getString(KEY_USER_NAME, null) !=null){
return true;
}
return false;
}
public boolean logOut(){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREFERENCE_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
return true;
}
public String getUsername()
{
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREFERENCE_NAME,Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_USER_NAME, null);
}
public String getUserEmail()
{
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREFERENCE_NAME,Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_USER_EMAIL,null);
}
}//end of class
i use volley library on android code
i want to know check if my table has been updated or inserted then wanted to do it(A), otherwise it(B)
for example if my table updated or inserted then send (A)sms otherwise (B)toast
its my activity code:
public class DeviceAddActivity extends AppCompatActivity implements View.OnClickListener {
private static final String REGISTER_URL = "http://192.168.43.190/entezam/addphone.php";
public static final String KEY_CUSTNAME = "Customer_non";
public static final String KEY_PHONENAME = "Phone_Name";
public static final String KEY_IMEI = "IMEI";
private EditText editTextName;
private EditText editTextPhoneName;
private EditText editTextIMEI;
private Button buttonRegister;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_add);
editTextName = (EditText) findViewById(R.id.editTextcustname);
editTextPhoneName = (EditText) findViewById(R.id.editTextphonename);
editTextIMEI= (EditText) findViewById(R.id.editTextimei);
buttonRegister = (Button) findViewById(R.id.buttonRegister);
buttonRegister.setOnClickListener(this);
}
private void registerUser(){
final String Customer_non = editTextName.getText().toString().trim();
final String Phone_Name = editTextPhoneName.getText().toString().trim();
final String IMEI = editTextIMEI.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(DeviceAddActivity.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(DeviceAddActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_CUSTNAME,Customer_non);
params.put(KEY_PHONENAME,Phone_Name);
params.put(KEY_IMEI,IMEI);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
#Override
public void onClick(View v) {
if(v == buttonRegister){
registerUser();
}
}
and its my php code:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$Phone_Name = $_POST['Phone_Name'];
$Customer = $_POST['Customer_non'];
$IMEI = $_POST['IMEI'];
require_once('dbConnect.php');
$sql = "INSERT INTO phone_in (Phone_Name,Customer_non,IMEI) VALUES ('$Phone_Name','$Customer','$IMEI')";
if(mysqli_query($con,$sql)){
echo "Successfully Registered";
}else{
echo "Could not register";
}
}else{echo 'error';}
why when i click on button "login" i have this error:"E/Volley: [126] BasicNetwork.performRequest: Unexpected response code 500"?
PS:it is works in local, so with local db.
this is my code::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
config.java:
public class Config {
//URL to our login.php file
//public static final String LOGIN_URL = "http://192.168.94.1/Android/LoginLogout/login.php";
// public static final String LOGIN_URL = "http://10.0.2.2:8888/phpmyadmin/import.php#PMAURL-5:sql.php?db=androiddb&table=androiddb&server=1&target=&token=809562ca509cc18a182d0f6b0bef5485/login.php";
//public static final String LOGIN_URL = "http://192.168.1.140/Android/LoginLogout/login.php";
public static final String LOGIN_URL ="http://10.0.2.2:8888/androiddb/login.php";
//Keys for email and password as defined in our $_POST['key'] in login.php
public static final String KEY_EMAIL = "email";
public static final String KEY_PASSWORD = "password";
//If server response is equal to this that means login is successful
public static final String LOGIN_SUCCESS = "success";
//Keys for Sharedpreferences
//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";
}
LOGIN ACTIVITY.java:
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
//Defining views
private EditText editTextEmail;
private EditText editTextPassword;
private AppCompatButton buttonLogin;
//boolean variable to check user is logged in or not
//initially it is false
private boolean loggedIn = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//Initializing views
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
buttonLogin = (AppCompatButton) findViewById(R.id.buttonLogin);
//Adding click listener
buttonLogin.setOnClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
//In onresume fetching value from sharedpreference
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME,Context.MODE_PRIVATE);
//Fetching the boolean value form sharedpreferences
loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);
//If we will get true
if(loggedIn){
//We will start the Profile Activity
Intent intent = new Intent(LoginActivity.this, ProfileActivity.class);
startActivity(intent);
}
}
private void login(){
//Getting values from edit texts
final String email = editTextEmail.getText().toString().trim();
final String password = editTextPassword.getText().toString().trim();
//Creating a string request
StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.LOGIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//If we are getting success from server
if(response.equalsIgnoreCase(Config.LOGIN_SUCCESS)){
//Creating a shared preference
SharedPreferences sharedPreferences = LoginActivity.this.getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Creating editor to store values to shared preferences
SharedPreferences.Editor editor = sharedPreferences.edit();
//Adding values to editor
editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, true);
editor.putString(Config.EMAIL_SHARED_PREF, email);
//Saving values to editor
editor.commit();
//Starting profile activity
Intent intent = new Intent(LoginActivity.this, ProfileActivity.class);
startActivity(intent);
}else{
//If the server response is not success
//Displaying an error message on toast
Toast.makeText(LoginActivity.this, "Invalid username or password", Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//You can handle error here if you want
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
//Adding parameters to request
params.put(Config.KEY_EMAIL, email);
params.put(Config.KEY_PASSWORD, password);
// params.put("Content-Type", "application/json; charset=utf-8");
//returning parameter
return params;
}
};
//Adding the string request to the queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
#Override
public void onClick(View v) {
//Calling the login function
login();
}
}
DBConnect.php:
<?php
define('HOST','localhost');
define('USER',);
define('PASS','');
define('DB','androiddb');
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
LOGIN.php:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$username = $_POST['email'];
$password = $_POST['password'];
//Creating sql query
$sql = "SELECT * FROM users WHERE email='$username' AND password='$password'";
//importing dbConnect.php script
require_once('dbConnect.php');
//executing query
$result = mysqli_query($con,$sql);
//fetching result
$check = mysqli_fetch_array($result);
//if we got some result
if(isset($check)){
//displaying success
echo "success";
}else{
//displaying failure
echo "failure";
}
mysqli_close($con);
}
The problem is not your code but the server. 500 means Internal server error
This is my first attempt to create a login system in Android Studio and already got myself into trouble with my code.
My PHP script always returns something as JSON and I'm trying to parse that JSON in my LoginActivity, inside the login -method, but I'm getting
the following error after creditentials were forwarded to the server and the login button was clicked:
I/qtaguid﹕ Failed write_ctrl(u 43) res=-1 errno=22
I/qtaguid﹕ Untagging socket 43 failed errno=-22
W/NetworkManagementSocketTagger﹕ untagSocket(43) failed with errno -22
It did work earlier, when I was doing a stringRequest instead of jsonRequest, so everything should be fine on the server side. Since I'm very new to Android development, I'm unable to figure this one out by myself and need desperately your help.
Here's my LoginActivity without the imports:
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
// Define Views
private EditText editTextEmail, editTextPassword;
private Button buttonLogin;
private ProgressBar progress;
private UserLocalStore userLocalStore;
private boolean loggedIn = false;
private final String TAG = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide(); // Hides the Action Bar for Login Activity
setContentView(R.layout.activity_login); // Sets the Content View
// Initializing Views
// EditText fields
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
// Buttons
buttonLogin = (Button) findViewById(R.id.buttonLogin);
// Other
progress = (ProgressBar) findViewById(R.id.progressBar);
// This method will set watcher for the EditTextFields
// The method will watch the value set to the EditTextFields.
// If there is nothing inputted in the EditTextField, "Login" button is disabled.
// Correspondingly, if there are text in the field, "Login" button is enabled.
watcher(editTextEmail, editTextPassword, buttonLogin);
// On-Click listeners
buttonLogin.setOnClickListener(this);
}
// Watcher method to check the value of EditText field
public void watcher(final EditText editText, final EditText editPassword, final Button button)
{
editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if (editText.length() == 0 && editPassword.length() == 0) // If length of the text field is equal to 0
button.setEnabled(false); // Disable the "Send" button
else
button.setEnabled(true); // Otherwise enable
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
if(editText.length() == 0 && editPassword.length() == 0)
button.setEnabled(false); //disable at app start
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);
// If the value of loggedIn variable is true
if(!loggedIn) {
// We will start the Courses activity
Intent intent = new Intent(LoginActivity.this, CourseActivity.class);
startActivity(intent);
}
}
private void login() {
// Get the values from the edit texts
final String email = editTextEmail.getText().toString().trim();
final String password = editTextPassword.getText().toString().trim();
// Creating a JSON Object request
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Config.LOGIN_URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
// This line will not print out
System.out.println(response);
try {
String json_status = response.getString("status");
String message = response.getString("message");
if(json_status.equalsIgnoreCase(Config.LOGIN_SUCCESS)) {
System.out.println(message);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// You can handle the error here if you want
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
// Adding parameters to request
params.put(Config.KEY_EMAIL, email);
params.put(Config.KEY_PASSWORD, password);
// Return parameters
return params;
}
};
// Adding the string request to the queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonObjectRequest);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
// If button Login was clicked
case R.id.buttonLogin:
login(); // Start login method after "Login" button is clicked
// startActivity(new Intent(this, MainActivity.class));
break;
}
}
}
And here's my PHP:
<?php
require_once("dbconnect.php");
// POST Variables
$post_email = $_POST['email'];
$post_password = $_POST['password'];
// Prepare the SQL query
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute(array(
':email' => $post_email,
));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0 && password_verify($post_password, $row['password']) && $row['role'] != 'staff') {
$user = array(); // Create an array for the user information
$user['id'] = $row['id'];
$user['name'] = $row['name'];
$user['email'] = $row['email'];
$user['password'] = $row['password'];
$user['role'] = $row['role'];
// echo json_encode(["message" => "success"]);
echo json_encode(["status" => "success", "message" => "Successfully logged in"]); // Format the array to JSON
} else {
echo json_encode(["status" => "error", "message" => "Incorrect creditentials"]);
}
You might not be passing the params, I usually use this syntax:
// Get the values from the edit texts
final String email = editTextEmail.getText().toString().trim();
final String password = editTextPassword.getText().toString().trim();
Map<String, Object> params = new ArrayMap<>(2);
// Adding parameters to request
params.put(Config.KEY_EMAIL, email);
params.put(Config.KEY_PASSWORD, password);
// Creating a JSON Object request
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(params),
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
Log.d(TAG, response.toString());
// other stuff ...
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
// You can handle the error here if you want
}
});
// Adding the string request to the queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonObjectRequest);
Also, you might want to handle all the volley requests in a Singleton class, have a look at this SO question.
Hope this helps in any way :)
After Login, I get back a JSON response from the server with the real name of the user. But it won't be displayed in TextView txtName. What is wrong with the code?
MainActivity.java:
public class MainActivity extends Activity {
private TextView txtName;
private TextView txtEmail;
private Button btnLogout;
private Button btnNeu;
private Button btnAlle;
private SQLiteHandler db;
private SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
txtName = (TextView) findViewById(R.id.name);
txtEmail = (TextView) findViewById(R.id.email);
btnLogout = (Button) findViewById(R.id.btnLogout);
btnNeu = (Button) findViewById(R.id.neu);
btnAlle = (Button) findViewById(R.id.alle);
// SqLite database handler
db = new SQLiteHandler(getApplicationContext());
// session manager
session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
String name = user.get("name");
String email = user.get("email");
// Displaying the user details on the screen
txtName.setText(name);
txtEmail.setText(email);
...
}
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
}
SQLiteHandler.java:
public class SQLiteHandler extends SQLiteOpenHelper {
private static final String TAG = SQLiteHandler.class.getSimpleName();
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "android_api";
// Login table name
private static final String TABLE_LOGIN = "login";
// Login Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
private static final String KEY_UID = "uid";
private static final String KEY_CREATED_AT = "created_at";
public SQLiteHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_EMAIL + " TEXT UNIQUE," + KEY_UID + " TEXT,"
+ KEY_CREATED_AT + " TEXT" + ")";
db.execSQL(CREATE_LOGIN_TABLE);
Log.d(TAG, "Database tables created");
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN);
// Create tables again
onCreate(db);
}
/**
* Storing user details in database
* */
public void addUser(String name, String email, String uid, String created_at) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, name); // Name
values.put(KEY_EMAIL, email); // Email
values.put(KEY_UID, uid); // Email
values.put(KEY_CREATED_AT, created_at); // Created At
// Inserting Row
long id = db.insert(TABLE_LOGIN, null, values);
db.close(); // Closing database connection
Log.d(TAG, "New user inserted into sqlite: " + id);
}
/**
* Getting user data from database
* */
public HashMap<String, String> getUserDetails() {
HashMap<String, String> user = new HashMap<String, String>();
String selectQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
user.put("name", cursor.getString(1));
user.put("email", cursor.getString(2));
user.put("uid", cursor.getString(3));
user.put("created_at", cursor.getString(4));
}
cursor.close();
db.close();
// return user
Log.d(TAG, "Fetching user from Sqlite: " + user.toString());
return user;
}
/**
* Getting user login status return true if rows are there in table
* */
public int getRowCount() {
String countQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int rowCount = cursor.getCount();
db.close();
cursor.close();
// return row count
return rowCount;
}
/**
* Re crate database Delete all tables and create them again
* */
public void deleteUsers() {
SQLiteDatabase db = this.getWritableDatabase();
// Delete All Rows
db.delete(TABLE_LOGIN, null, null);
db.close();
Log.d(TAG, "Deleted all user info from sqlite");
}
}
LoginActivity.java:
public class LoginActivity extends Activity {
// LogCat tag
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
// Check for empty data in the form
if (email.trim().length() > 0 && password.trim().length() > 0) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Bitte Benutzername und Passwort eintragen!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
/**
* function to verify login details in mysql db
* */
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Login ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Launch main activity
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "login");
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
Finally I found the code i have forgotten to insert in LoginActivity.java:
Now it is working
public class LoginActivity extends Activity {
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
db = new SQLiteHandler(getApplicationContext());
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
// Check for empty data in the form
if (email.trim().length() > 0 && password.trim().length() > 0) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Bitte Benutzername und Passwort eintragen!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
/**
* function to verify login details in mysql db
* */
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Login ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
// Launch main activity
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "login");
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}