Advertisement
rezayoga

LoginActivity.java

Mar 2nd, 2016
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 13.67 KB | None | 0 0
  1. package co.fppc.ig;
  2.  
  3. import android.animation.Animator;
  4. import android.animation.AnimatorListenerAdapter;
  5. import android.annotation.TargetApi;
  6. import android.app.Activity;
  7. import android.app.AlertDialog;
  8. import android.app.LoaderManager.LoaderCallbacks;
  9. import android.content.CursorLoader;
  10. import android.content.DialogInterface;
  11. import android.content.Intent;
  12. import android.content.Loader;
  13. import android.database.Cursor;
  14. import android.net.Uri;
  15. import android.os.AsyncTask;
  16. import android.os.Build;
  17. import android.os.Bundle;
  18. import android.provider.ContactsContract;
  19. import android.text.TextUtils;
  20. import android.util.Log;
  21. import android.view.KeyEvent;
  22. import android.view.LayoutInflater;
  23. import android.view.View;
  24. import android.view.View.OnClickListener;
  25. import android.view.inputmethod.EditorInfo;
  26. import android.widget.ArrayAdapter;
  27. import android.widget.AutoCompleteTextView;
  28. import android.widget.Button;
  29. import android.widget.EditText;
  30. import android.widget.TextView;
  31.  
  32. import org.apache.http.NameValuePair;
  33. import org.apache.http.message.BasicNameValuePair;
  34. import org.json.JSONException;
  35. import org.json.JSONObject;
  36.  
  37. import java.util.ArrayList;
  38. import java.util.List;
  39.  
  40. import co.fppc.ig.database.model.User;
  41. import co.fppc.ig.library.Constants;
  42. import co.fppc.ig.library.GPSTracker;
  43. import co.fppc.ig.library.Helper;
  44. import co.fppc.ig.library.JSONParser;
  45.  
  46.  
  47. /**
  48.  * A login screen that offers login via email/password.
  49.  */
  50. public class LoginActivity extends Activity implements LoaderCallbacks<Cursor> {
  51.     private User user;
  52.     JSONParser jParser = new JSONParser();
  53.     JSONObject json;
  54.     /**
  55.      * Keep track of the login task to ensure we can cancel it if requested.
  56.      */
  57.  
  58.     // Mendeklarasikan instance/object dari UserLoginTask.
  59.     // UserLoginTask adalah class untuk melakukan pengambilan data verifikasi login antara android dengan server
  60.     // UserLoginTask didefinisikan didalam kelas ini sebagai inner class
  61.     private UserLoginTask mAuthTask = null;
  62.  
  63.     // UI references.
  64.     private AutoCompleteTextView mEmailView;
  65.     private EditText mPasswordView;
  66.     private View mProgressView;
  67.     private View mLoginFormView;
  68.     private GPSTracker gps;
  69.  
  70.     @Override
  71.     protected void onCreate(Bundle savedInstanceState) {
  72.         super.onCreate(savedInstanceState);
  73.         setContentView(R.layout.activity_login);
  74.  
  75.         // Set up the login form.
  76.         mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
  77.         populateAutoComplete();
  78.  
  79.         mPasswordView = (EditText) findViewById(R.id.password);
  80.         mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
  81.             @Override
  82.             public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
  83.                 if (id == R.id.login || id == EditorInfo.IME_NULL) {
  84.                     attemptLogin();
  85.                     return true;
  86.                 }
  87.                 return false;
  88.             }
  89.         });
  90.  
  91.         Button mEmailSignInButton = (Button) findViewById(R.id.sign_in_button);
  92.         mEmailSignInButton.setOnClickListener(new OnClickListener() {
  93.             @Override
  94.             public void onClick(View view) {
  95.                 attemptLogin();
  96.             }
  97.         });
  98.  
  99.         Button buttonProfilAplikasi = (Button) findViewById(R.id.buttonProfilAplikasi);
  100.         buttonProfilAplikasi.setOnClickListener(new OnClickListener() {
  101.             @Override
  102.             public void onClick(View v) {
  103.                 AlertDialog.Builder aboutDialog = new AlertDialog.Builder(LoginActivity.this);
  104.                 aboutDialog.setTitle("About App");
  105.                 // Get the layout inflater
  106.                 LayoutInflater inflater = getLayoutInflater();
  107.                 View view = inflater.inflate(R.layout.app_profile_dialog, null);
  108.                 // Inflate and set the layout for the dialog
  109.                 // Pass null as the parent view because its going in the dialog layout
  110.                 aboutDialog.setView(view)
  111.                         // Add action buttons
  112.                         .setNegativeButton(R.string.button_label_close, new DialogInterface.OnClickListener() {
  113.                             public void onClick(DialogInterface dialog, int id) {
  114.  
  115.                             }
  116.                         })
  117.                 ;
  118.                 aboutDialog.show();
  119.             }
  120.         });
  121.         mLoginFormView = findViewById(R.id.login_form);
  122.         mProgressView = findViewById(R.id.login_progress);
  123.  
  124.         // create class object
  125.         gps = new GPSTracker(LoginActivity.this);
  126.         // check if GPS enabled
  127.         if (gps.canGetLocation()) {
  128.  
  129.             double latitude = gps.getLatitude();
  130.             double longitude = gps.getLongitude();
  131.  
  132.             // \n is for new line
  133.             //Helper.toast(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude);
  134.  
  135.             Log.d("_onLocationChanged_", "Lat: " + String.valueOf(String.format("%.8f", latitude)) + " Long: " + String.valueOf(String.format("%.8f", longitude)));
  136.         } else {
  137.             // can't get location
  138.             // GPS or Network is not enabled
  139.             // Ask user to enable GPS/network in settings
  140.             gps.showSettingsAlert();
  141.         }
  142.     }
  143.  
  144.     private void populateAutoComplete() {
  145.         getLoaderManager().initLoader(0, null, this);
  146.     }
  147.  
  148.  
  149.     // Fungsi yang digunakan untuk melakukan login dari aplikasi
  150.     public void attemptLogin() {
  151.         // Check apakah object mAuthTask belum terinstansiasi
  152.         if (mAuthTask != null) {
  153.             return;
  154.         }
  155.  
  156.         // Reset errors.
  157.         mEmailView.setError(null);
  158.         mPasswordView.setError(null);
  159.  
  160.         // Store values at the time of the login attempt.
  161.         String email = mEmailView.getText().toString();
  162.         String password = mPasswordView.getText().toString();
  163.  
  164.         boolean cancel = false;
  165.         View focusView = null;
  166.  
  167.         // Check apakah password tidak kosong dan password valid
  168.         if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
  169.             mPasswordView.setError(getString(R.string.error_invalid_password));
  170.             focusView = mPasswordView;
  171.             cancel = true;
  172.         }
  173.  
  174.         // Check untuk valid email dan formatnya.
  175.         if (TextUtils.isEmpty(email)) {
  176.             mEmailView.setError(getString(R.string.error_field_required));
  177.             focusView = mEmailView;
  178.             cancel = true;
  179.         } else if (!isEmailValid(email)) {
  180.             mEmailView.setError(getString(R.string.error_invalid_email));
  181.             focusView = mEmailView;
  182.             cancel = true;
  183.         }
  184.  
  185.         // Jika cancel, maka tampilkan pesan error
  186.         // Status cancel bernilai true jika syarat login pada form login tidak terpenuhi
  187.         // Misalkan email / password kosong, dsb
  188.         if (cancel) {
  189.             // There was an error; don't attempt login and focus the first
  190.             // form field with an error.
  191.             focusView.requestFocus();
  192.         } else {
  193.             // Jika status cancel = false, atau tidak ada kesalahan, maka mulai melakukan verifikasi data login dengan server
  194.             showProgress(true);
  195.             mAuthTask = new UserLoginTask(email, password);
  196.             mAuthTask.execute((Void) null);
  197.         }
  198.     }
  199.  
  200.     private boolean isEmailValid(String email) {
  201.         //TODO: Replace this with your own logic
  202.         return email.contains("@");
  203.     }
  204.  
  205.     private boolean isPasswordValid(String password) {
  206.         //TODO: Replace this with your own logic
  207.         return password.length() > 2;
  208.     }
  209.  
  210.     // Loader icon untuk login
  211.     @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
  212.     public void showProgress(final boolean show) {
  213.         // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
  214.         // for very easy animations. If available, use these APIs to fade-in
  215.         // the progress spinner.
  216.         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
  217.             int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
  218.  
  219.             mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
  220.             mLoginFormView.animate().setDuration(shortAnimTime).alpha(
  221.                     show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
  222.                 @Override
  223.                 public void onAnimationEnd(Animator animation) {
  224.                     mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
  225.                 }
  226.             });
  227.  
  228.             mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
  229.             mProgressView.animate().setDuration(shortAnimTime).alpha(
  230.                     show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
  231.                 @Override
  232.                 public void onAnimationEnd(Animator animation) {
  233.                     mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
  234.                 }
  235.             });
  236.         } else {
  237.             // The ViewPropertyAnimator APIs are not available, so simply show
  238.             // and hide the relevant UI components.
  239.             mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
  240.             mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
  241.         }
  242.     }
  243.  
  244.     @Override
  245.     public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
  246.         return new CursorLoader(this,
  247.                 // Retrieve data rows for the device user's 'profile' contact.
  248.                 Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
  249.                         ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
  250.  
  251.                 // Select only email addresses.
  252.                 ContactsContract.Contacts.Data.MIMETYPE +
  253.                         " = ?", new String[]{ContactsContract.CommonDataKinds.Email
  254.                 .CONTENT_ITEM_TYPE},
  255.  
  256.                 // Show primary email addresses first. Note that there won't be
  257.                 // a primary email address if the user hasn't specified one.
  258.                 ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
  259.     }
  260.  
  261.     @Override
  262.     public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
  263.         List<String> emails = new ArrayList<String>();
  264.         cursor.moveToFirst();
  265.         while (!cursor.isAfterLast()) {
  266.             emails.add(cursor.getString(ProfileQuery.ADDRESS));
  267.             cursor.moveToNext();
  268.         }
  269.  
  270.         addEmailsToAutoComplete(emails);
  271.     }
  272.  
  273.     @Override
  274.     public void onLoaderReset(Loader<Cursor> cursorLoader) {
  275.  
  276.     }
  277.  
  278.     private interface ProfileQuery {
  279.         String[] PROJECTION = {
  280.                 ContactsContract.CommonDataKinds.Email.ADDRESS,
  281.                 ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
  282.         };
  283.  
  284.         int ADDRESS = 0;
  285.         int IS_PRIMARY = 1;
  286.     }
  287.  
  288.  
  289.     private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
  290.         //Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
  291.         ArrayAdapter<String> adapter =
  292.                 new ArrayAdapter<String>(LoginActivity.this,
  293.                         android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
  294.  
  295.         mEmailView.setAdapter(adapter);
  296.     }
  297.  
  298.     // Mendeklarasikan class UserLoginTask yang berfungsi untuk melakukan verifikasi data login dengan server
  299.     public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
  300.  
  301.         private final String mEmail;
  302.         private final String mPassword;
  303.  
  304.         UserLoginTask(String email, String password) {
  305.             mEmail = email;
  306.             mPassword = password;
  307.         }
  308.  
  309.         @Override
  310.         protected Boolean doInBackground(Void... params) {
  311.             // TODO: attempt authentication against a network service.
  312.  
  313.             List<NameValuePair> par = new ArrayList<NameValuePair>();
  314.             par.add(new BasicNameValuePair("email", mEmail));
  315.             par.add(new BasicNameValuePair("password", mPassword));
  316.             json = jParser.makeHttpRequest(Constants.MOBILE_API_SERVER_BASE_URL + "action_login.php", "POST", par);
  317.  
  318.             boolean valid = false;
  319.  
  320.             try {
  321.                 if (!json.getString("valid").equals("")) {
  322.                     valid = true;
  323.                     JSONObject jsonValid = json.getJSONObject("valid");
  324.                     Log.d("_MSG_VALID_", json.getString("valid"));
  325.                     user = new User(jsonValid.getInt("id"), jsonValid.getString("email"), jsonValid.getString("password"));
  326.                 }
  327.             } catch (JSONException e) {
  328.                 // TODO Auto-generated catch block
  329.                 e.printStackTrace();
  330.             }
  331.             return valid;
  332.         }
  333.  
  334.         @Override
  335.         protected void onPostExecute(final Boolean success) {
  336.             mAuthTask = null;
  337.             showProgress(false);
  338.  
  339.             // Melakukan pemeriksaan akun, jika sukses maka akan ditampilkan MainActivity
  340.             // Passing data informasi dari user melalui intent 'USER_SESSION'
  341.             if (success) {
  342.                 finish();
  343.                 Intent intent = new Intent(getApplicationContext(), MainActivity.class);
  344.                 intent.putExtra("USER_SESSION", user);
  345.                 startActivity(intent);
  346.             } else {
  347.                 Helper.toast(getApplicationContext(), "Invalid login");
  348.                 mPasswordView.setError(getString(R.string.error_incorrect_password));
  349.                 mPasswordView.requestFocus();
  350.             }
  351.         }
  352.  
  353.         @Override
  354.         protected void onCancelled() {
  355.             mAuthTask = null;
  356.             showProgress(false);
  357.         }
  358.     }
  359. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement