Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Registration and login through php and mysql only with volley, fastintent and butterknife.
package com.emagic.newproject;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.nsd.NsdManager.RegistrationListener;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import butterknife.ButterKnife;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.emagic.libraries.intents.FastIntent;
import com.emagic.libraries.managers.SystemBarTintManager;
import com.emagic.newproject.managers.SessionManager;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
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;
@SuppressWarnings("rawtypes")
public FastIntent fi;
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
@SuppressWarnings("rawtypes")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
ButterKnife.inject(this);
fi = new FastIntent(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
setTranslucentStatus(true);
}
SystemBarTintManager tintManager = new SystemBarTintManager(this);
tintManager.setStatusBarTintEnabled(true);
tintManager.setStatusBarTintResource(R.color.ColorPrimary);
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()) {
fi.startActivity(MainActivity.class);
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
// Check for empty data in the form
if (!email.isEmpty() && !password.isEmpty()) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
fi.snakebar("Please enter the credentials!");
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
fi.startActivity(RegisterActivity.class);
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("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
String message = jObj.optString(TAG_MESSAGE);
int success1 = jObj.getInt(TAG_SUCCESS);
if (success1 == 1) {
session.setLogin(true);
fi.startActivity(MainActivity.class);
fi.snakebar(message);
} else if (success1 == 0) {
// Error in login. Get the error message
fi.snakebar(message);
}
} catch (JSONException e) {
//here it will give a json value error but thats not a big problem because
// The needed task is done.
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
fi.snakebar("An Internal error occured, This may be because either the server is down or your Connecttion is not working properly");
hideDialog();
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("Email_Id", email);
params.put("Password", password);
return params;
}
};
// Adding request to request queue
NewProject.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
@TargetApi(19)
private void setTranslucentStatus(boolean on) {
Window win = getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
if (on) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
win.setAttributes(winParams);
}
}
package com.emagic.newproject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import com.emagic.libraries.intents.FastIntent;
import com.emagic.newproject.R;
import com.emagic.newproject.managers.SessionManager;
public class RegisterActivity extends Activity {
private static final String TAG = RegisterActivity.class.getSimpleName();
@InjectView(R.id.btnRegister)
Button btnRegister;
@OnClick(R.id.btnRegister)
public void onClick(Button btnRegister) {
String name = inputFullName.getText().toString().trim();
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
String confirmPassword = iputConfirmPassword.getText().toString()
.trim();
String mobileNumber = inputMobileNumber.getText().toString().trim();
String address = inputAddress.getText().toString().trim();
String emailPattern = "^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@"
+ "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
+ "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+ "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$";
if (name.isEmpty() && email.isEmpty() && confirmPassword.isEmpty()
&& mobileNumber.isEmpty() && address.isEmpty()) {
fi.snakebar("Please enter your details");
} else if (name.isEmpty()) {
fi.snakebar("Please enter your name");
} else if (address.isEmpty()) {
fi.snakebar("Please enter your address");
} else if (mobileNumber.isEmpty()) {
fi.snakebar("Please enter your Mobile number");
} else if (!password.isEmpty() && confirmPassword.isEmpty()) {
fi.snakebar("Please confirm your password");
} else if (password.isEmpty() && !confirmPassword.isEmpty()) {
fi.snakebar("You Cannot Confirm a password without entering the actual password");
} else if (email.isEmpty()) {
fi.snakebar("Email address is required");
} else if (mobileNumber.length() < 10) {
fi.snakebar("Not a valid Mobile Numaber");
} else if (!password.equals(confirmPassword)) {
fi.snakebar("Password does not match");
} else if (!email.matches(emailPattern)) {
fi.snakebar("Not a valid email address");
} else if (!name.isEmpty() && email.matches(emailPattern)
&& confirmPassword.equals(password)
&& mobileNumber.length() == 10 && !address.isEmpty()) {
registerUser(name, email, confirmPassword, mobileNumber, address);
}
}
@InjectView(R.id.name)
EditText inputFullName;
@InjectView(R.id.email)
EditText inputEmail;
@InjectView(R.id.password)
EditText inputPassword;
@InjectView(R.id.confirmPassword)
EditText iputConfirmPassword;
@InjectView(R.id.mobileNumber)
EditText inputMobileNumber;
@InjectView(R.id.address)
EditText inputAddress;
ProgressDialog pDialog;
SessionManager session;
@SuppressWarnings("rawtypes")
public FastIntent fi;
String emailString;
@SuppressWarnings("rawtypes")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
ButterKnife.inject(this);
fi = new FastIntent(this);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
}
/*
* // Link to Login Screen btnLinkToLogin.setOnClickListener(new
* View.OnClickListener() {
*
* public void onClick(View view) { Intent i = new
* Intent(getApplicationContext(), LoginActivity.class); startActivity(i);
* finish(); } });
*
* }
*/
/**
* Function to store user in MySQL database will post params(tag, name,
* email, password) to register url
* */
private void registerUser(final String name, final String email,
final String confirmPassword, final String mobileNumber,
final String address) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
emailString = jObj.getString(email);
Toast.makeText(
getApplicationContext(),
"User successfully registered. Try login now!",
Toast.LENGTH_LONG).show();
// Launch login activity
Intent intent = new Intent(
RegisterActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
fi.snakebar("An Internal error occured, This may be because either the server is down or your Connecttion is not working properly");
hideDialog();
}
}) {
@Override
public Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
if (params.put("Email_Id", email) == emailString) {
fi.snakebar("User with same email address already exists");
} else {
params.put("Login_Name", name);
params.put("Email_Id", email);
params.put("Password", confirmPassword);
params.put("Mobile_No", mobileNumber);
params.put("Address", address);
}
return params;
}
};
// Adding request to request queue
NewProject.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
public final static boolean isValidEmail(CharSequence target) {
if (target == null)
return false;
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
@Acrunam

This comment has been minimized.

Copy link

commented Aug 30, 2018

This works great. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.