Advertisement
Guest User

Untitled

a guest
Jan 18th, 2017
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.19 KB | None | 0 0
  1. package com.custofeed.app.feedback.activity;
  2.  
  3. import android.animation.Animator;
  4. import android.animation.AnimatorListenerAdapter;
  5. import android.annotation.TargetApi;
  6. import android.content.Context;
  7. import android.content.Intent;
  8. import android.content.SharedPreferences;
  9. import android.net.ConnectivityManager;
  10. import android.net.NetworkInfo;
  11. import android.os.AsyncTask;
  12. import android.os.Build;
  13. import android.os.Bundle;
  14. import android.support.v7.app.AppCompatActivity;
  15. import android.text.TextUtils;
  16. import android.view.KeyEvent;
  17. import android.view.View;
  18. import android.view.View.OnClickListener;
  19. import android.view.inputmethod.EditorInfo;
  20. import android.widget.AutoCompleteTextView;
  21. import android.widget.Button;
  22. import android.widget.CheckBox;
  23. import android.widget.EditText;
  24. import android.widget.TextView;
  25. import android.widget.Toast;
  26.  
  27. import com.android.volley.Request;
  28. import com.android.volley.RequestQueue;
  29. import com.android.volley.Response;
  30. import com.android.volley.VolleyError;
  31. import com.android.volley.toolbox.StringRequest;
  32. import com.android.volley.toolbox.Volley;
  33. import com.custofeed.app.feedback.R;
  34. import com.custofeed.app.feedback.model.DatabaseHandler;
  35. import com.custofeed.app.feedback.network.URLS;
  36. import com.custofeed.app.feedback.utils.SharedPreference;
  37.  
  38. import org.json.JSONException;
  39. import org.json.JSONObject;
  40.  
  41. import java.util.HashMap;
  42. import java.util.Map;
  43.  
  44. /**
  45. * A login screen that offers login via username/password.
  46. */
  47. public class LoginActivity extends AppCompatActivity{
  48.  
  49. /**
  50. * Keep track of the login task to ensure we can cancel it if requested.
  51. */
  52. private UserLoginTask mAuthTask = null;
  53.  
  54. // UI references.
  55. private AutoCompleteTextView mUsernameView;
  56. private EditText mPasswordView;
  57. private View mProgressView;
  58. private View mLoginFormView;
  59.  
  60. private Boolean loginResult = false;
  61. private SharedPreferences sharedPref;
  62.  
  63. DatabaseHandler mydb;
  64.  
  65. @Override
  66. protected void onCreate(Bundle savedInstanceState) {
  67. super.onCreate(savedInstanceState);
  68. setContentView(R.layout.activity_login);
  69.  
  70. mydb = new DatabaseHandler(this);
  71.  
  72. sharedPref = getSharedPreferences("data", MODE_PRIVATE);
  73.  
  74. //Check if user is already logged in
  75. Boolean isLogged = sharedPref.getBoolean(SharedPreference.Account.IS_LOGGED, false);
  76. if(isLogged) {
  77. //Check if Login Expired
  78. long expires = sharedPref.getLong(SharedPreference.Account.SESSION_EXPIRE, 0);
  79. if(System.currentTimeMillis() < expires){
  80. nextActivity(true);
  81. }
  82. }
  83.  
  84. // Set up the login form.
  85. mUsernameView = (AutoCompleteTextView) findViewById(R.id.username);
  86. mPasswordView = (EditText) findViewById(R.id.password);
  87. mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
  88. @Override
  89. public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
  90. ConnectivityManager connMgr = (ConnectivityManager)
  91. getSystemService(Context.CONNECTIVITY_SERVICE);
  92. NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
  93. if (networkInfo != null && networkInfo.isConnected()) {
  94. if (id == R.id.login || id == EditorInfo.IME_NULL) {
  95. attemptLogin();
  96. return true;
  97. }
  98. } else {
  99. Toast.makeText(LoginActivity.this,
  100. "No network connection available", Toast.LENGTH_SHORT).show();
  101. }
  102. return false;
  103. }
  104. });
  105.  
  106. //Autofill form if Details Exist
  107. String remUsername = sharedPref.getString(SharedPreference.Account.USERNAME, null);
  108. String remPassword = sharedPref.getString(SharedPreference.Account.PASSWORD, null);
  109. if(remUsername != null && remPassword != null){
  110. mUsernameView.setText(remUsername);
  111. mPasswordView.setText(remPassword);
  112. }
  113.  
  114. Button mSignInButton = (Button) findViewById(R.id.sign_in_button);
  115. mSignInButton.setOnClickListener(new OnClickListener() {
  116. @Override
  117. public void onClick(View view) {
  118. ConnectivityManager connMgr = (ConnectivityManager)
  119. getSystemService(Context.CONNECTIVITY_SERVICE);
  120. NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
  121. if (networkInfo != null && networkInfo.isConnected()) {
  122. attemptLogin();
  123. } else {
  124. Toast.makeText(LoginActivity.this,
  125. "No network connection available", Toast.LENGTH_SHORT).show();
  126. }
  127. }
  128. });
  129.  
  130. mLoginFormView = findViewById(R.id.login_form);
  131. mProgressView = findViewById(R.id.login_progress);
  132.  
  133. }
  134.  
  135. protected void setReturn(Boolean result){
  136. loginResult = result;
  137. }
  138.  
  139. private void loginUser(){
  140. final String username = mUsernameView.getText().toString().trim();
  141. final String password = mPasswordView.getText().toString().trim();
  142.  
  143. StringRequest stringRequest = new StringRequest(Request.Method.POST, URLS.POST_LOGIN,
  144. new Response.Listener<String>() {
  145. @Override
  146. public void onResponse(String response) {
  147. try {
  148. JSONObject jsonObject = new JSONObject(response);
  149. if(jsonObject.has("key")){
  150. SharedPreferences.Editor prefEditor = sharedPref.edit();
  151. prefEditor.putString(SharedPreference.Account.AUTH_TOKEN, jsonObject.optString("key"));
  152. prefEditor.apply();
  153. Toast.makeText(LoginActivity.this,
  154. "Logging In",Toast.LENGTH_SHORT).show();
  155. nextActivity(false);
  156. setReturn(true);
  157. }else{
  158. Toast.makeText(LoginActivity.this,
  159. "Invalid Credentials",Toast.LENGTH_SHORT).show();
  160. setReturn(false);
  161. }
  162. } catch (JSONException e) {
  163. Toast.makeText(LoginActivity.this,
  164. "Invalid Credentials",Toast.LENGTH_SHORT).show();
  165. setReturn(false);
  166. }
  167. }
  168. },
  169. new Response.ErrorListener() {
  170. @Override
  171. public void onErrorResponse(VolleyError error) {
  172. Toast.makeText(LoginActivity.this,
  173. "Invalid Credentials",Toast.LENGTH_SHORT).show();
  174. setReturn(false);
  175. }
  176. }){
  177. @Override
  178. protected Map<String,String> getParams(){
  179. Map<String,String> params = new HashMap<>();
  180. params.put(SharedPreference.Account.USERNAME, username);
  181. params.put(SharedPreference.Account.PASSWORD,password);
  182. return params;
  183. }
  184.  
  185. };
  186.  
  187. RequestQueue requestQueue = Volley.newRequestQueue(this);
  188. requestQueue.add(stringRequest);
  189. }
  190.  
  191.  
  192. /**
  193. * Attempts to sign in or register the account specified by the login form.
  194. * If there are form errors (invalid username, missing fields, etc.), the
  195. * errors are presented and no actual login attempt is made.
  196. */
  197. private void attemptLogin() {
  198. if (mAuthTask != null) {
  199. return;
  200. }
  201.  
  202. // Reset errors.
  203. mUsernameView.setError(null);
  204. mPasswordView.setError(null);
  205.  
  206. // Store values at the time of the login attempt.
  207. String username = mUsernameView.getText().toString();
  208. String password = mPasswordView.getText().toString();
  209.  
  210. boolean cancel = false;
  211. View focusView = null;
  212.  
  213. // Check for a valid password, if the user entered one.
  214. if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
  215. mPasswordView.setError(getString(R.string.error_invalid_password));
  216. focusView = mPasswordView;
  217. cancel = true;
  218. }
  219.  
  220. // Check for a valid username address.
  221. if (TextUtils.isEmpty(username)) {
  222. mUsernameView.setError(getString(R.string.error_field_required));
  223. focusView = mUsernameView;
  224. cancel = true;
  225. }
  226.  
  227. // Check for a valid password, if the user entered one.
  228. if (!isUsernameValid(username)) {
  229. mPasswordView.setError(getString(R.string.error_invalid_username));
  230. focusView = mPasswordView;
  231. cancel = true;
  232. }
  233.  
  234. if (cancel) {
  235. // There was an error; don't attempt login and focus the first
  236. // form field with an error.
  237. focusView.requestFocus();
  238. } else {
  239. // Show a progress spinner, and kick off a background task to
  240. // perform the user login attempt.
  241. showProgress(true);
  242. mAuthTask = new UserLoginTask();
  243. mAuthTask.execute((Void) null);
  244. }
  245. }
  246.  
  247. private boolean isUsernameValid(String username) {
  248. return username.length() > 0;
  249. }
  250.  
  251. private boolean isPasswordValid(String password) {
  252. return password.length() > 4;
  253. }
  254.  
  255. /**
  256. * Shows the progress UI and hides the login form.
  257. */
  258. @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
  259. private void showProgress(final boolean show) {
  260. // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
  261. // for very easy animations. If available, use these APIs to fade-in
  262. // the progress spinner.
  263. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
  264. int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
  265.  
  266. mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
  267. mLoginFormView.animate().setDuration(shortAnimTime).alpha(
  268. show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
  269. @Override
  270. public void onAnimationEnd(Animator animation) {
  271. mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
  272. }
  273. });
  274.  
  275. mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
  276. mProgressView.animate().setDuration(shortAnimTime).alpha(
  277. show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
  278. @Override
  279. public void onAnimationEnd(Animator animation) {
  280. mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
  281. }
  282. });
  283. } else {
  284. // The ViewPropertyAnimator APIs are not available, so simply show
  285. // and hide the relevant UI components.
  286. mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
  287. mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
  288. }
  289. }
  290.  
  291. /**
  292. * Represents an asynchronous login/registration task used to authenticate
  293. * the user.
  294. */
  295. public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
  296.  
  297. UserLoginTask() {}
  298.  
  299.  
  300.  
  301. @Override
  302. protected Boolean doInBackground(Void... params) {
  303. try {
  304. loginUser();
  305. if(!loginResult){
  306. Toast.makeText(LoginActivity.this,
  307. "Invalid Login Credentials",Toast.LENGTH_LONG).show();
  308. }
  309. return loginResult;
  310.  
  311. } catch(Exception e) {
  312. return false;
  313. }
  314. }
  315.  
  316. @Override
  317. protected void onPostExecute(final Boolean success) {
  318. mAuthTask = null;
  319. showProgress(true);
  320. }
  321.  
  322. @Override
  323. protected void onCancelled() {
  324. mAuthTask = null;
  325. showProgress(false);
  326. }
  327. }
  328.  
  329. protected void nextActivity(Boolean isLogged){
  330. if(!isLogged){
  331. //Set User Logged in state
  332. SharedPreferences.Editor prefEditor = sharedPref.edit();
  333. prefEditor.putLong(SharedPreference.Account.SESSION_EXPIRE, System.currentTimeMillis() + URLS.SESSION_EXPIRE_TIME);
  334. prefEditor.putBoolean(SharedPreference.Account.IS_LOGGED,true);
  335.  
  336. CheckBox rememberMe = (CheckBox) findViewById(R.id.rememberCheckBox);
  337. if(rememberMe.isChecked()){
  338. prefEditor.putString(SharedPreference.Account.USERNAME, mUsernameView.getText().toString().trim());
  339. prefEditor.putString(SharedPreference.Account.PASSWORD, mPasswordView.getText().toString().trim());
  340. }else{
  341. prefEditor.putString(SharedPreference.Account.USERNAME,null);
  342. prefEditor.putString(SharedPreference.Account.PASSWORD, null);
  343. }
  344. prefEditor.apply();
  345. }
  346.  
  347. nextActivity();
  348. }
  349.  
  350. protected void nextActivity(){
  351. finish();
  352. Intent myIntent = new Intent(this,PinActivity.class);
  353. this.startActivity(myIntent);
  354. }
  355. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement