Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package co.fppc.ig;
- import android.animation.Animator;
- import android.animation.AnimatorListenerAdapter;
- import android.annotation.TargetApi;
- import android.app.Activity;
- import android.app.AlertDialog;
- import android.app.LoaderManager.LoaderCallbacks;
- import android.content.CursorLoader;
- import android.content.DialogInterface;
- import android.content.Intent;
- import android.content.Loader;
- import android.database.Cursor;
- import android.net.Uri;
- import android.os.AsyncTask;
- import android.os.Build;
- import android.os.Bundle;
- import android.provider.ContactsContract;
- import android.text.TextUtils;
- import android.util.Log;
- import android.view.KeyEvent;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.view.inputmethod.EditorInfo;
- import android.widget.ArrayAdapter;
- import android.widget.AutoCompleteTextView;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.TextView;
- import org.apache.http.NameValuePair;
- import org.apache.http.message.BasicNameValuePair;
- import org.json.JSONException;
- import org.json.JSONObject;
- import java.util.ArrayList;
- import java.util.List;
- import co.fppc.ig.database.model.User;
- import co.fppc.ig.library.Constants;
- import co.fppc.ig.library.GPSTracker;
- import co.fppc.ig.library.Helper;
- import co.fppc.ig.library.JSONParser;
- /**
- * A login screen that offers login via email/password.
- */
- public class LoginActivity extends Activity implements LoaderCallbacks<Cursor> {
- private User user;
- JSONParser jParser = new JSONParser();
- JSONObject json;
- /**
- * Keep track of the login task to ensure we can cancel it if requested.
- */
- // Mendeklarasikan instance/object dari UserLoginTask.
- // UserLoginTask adalah class untuk melakukan pengambilan data verifikasi login antara android dengan server
- // UserLoginTask didefinisikan didalam kelas ini sebagai inner class
- private UserLoginTask mAuthTask = null;
- // UI references.
- private AutoCompleteTextView mEmailView;
- private EditText mPasswordView;
- private View mProgressView;
- private View mLoginFormView;
- private GPSTracker gps;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_login);
- // Set up the login form.
- mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
- populateAutoComplete();
- mPasswordView = (EditText) findViewById(R.id.password);
- mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
- @Override
- public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
- if (id == R.id.login || id == EditorInfo.IME_NULL) {
- attemptLogin();
- return true;
- }
- return false;
- }
- });
- Button mEmailSignInButton = (Button) findViewById(R.id.sign_in_button);
- mEmailSignInButton.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View view) {
- attemptLogin();
- }
- });
- Button buttonProfilAplikasi = (Button) findViewById(R.id.buttonProfilAplikasi);
- buttonProfilAplikasi.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- AlertDialog.Builder aboutDialog = new AlertDialog.Builder(LoginActivity.this);
- aboutDialog.setTitle("About App");
- // Get the layout inflater
- LayoutInflater inflater = getLayoutInflater();
- View view = inflater.inflate(R.layout.app_profile_dialog, null);
- // Inflate and set the layout for the dialog
- // Pass null as the parent view because its going in the dialog layout
- aboutDialog.setView(view)
- // Add action buttons
- .setNegativeButton(R.string.button_label_close, new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int id) {
- }
- })
- ;
- aboutDialog.show();
- }
- });
- mLoginFormView = findViewById(R.id.login_form);
- mProgressView = findViewById(R.id.login_progress);
- // create class object
- gps = new GPSTracker(LoginActivity.this);
- // check if GPS enabled
- if (gps.canGetLocation()) {
- double latitude = gps.getLatitude();
- double longitude = gps.getLongitude();
- // \n is for new line
- //Helper.toast(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude);
- Log.d("_onLocationChanged_", "Lat: " + String.valueOf(String.format("%.8f", latitude)) + " Long: " + String.valueOf(String.format("%.8f", longitude)));
- } else {
- // can't get location
- // GPS or Network is not enabled
- // Ask user to enable GPS/network in settings
- gps.showSettingsAlert();
- }
- }
- private void populateAutoComplete() {
- getLoaderManager().initLoader(0, null, this);
- }
- // Fungsi yang digunakan untuk melakukan login dari aplikasi
- public void attemptLogin() {
- // Check apakah object mAuthTask belum terinstansiasi
- if (mAuthTask != null) {
- return;
- }
- // Reset errors.
- mEmailView.setError(null);
- mPasswordView.setError(null);
- // Store values at the time of the login attempt.
- String email = mEmailView.getText().toString();
- String password = mPasswordView.getText().toString();
- boolean cancel = false;
- View focusView = null;
- // Check apakah password tidak kosong dan password valid
- if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
- mPasswordView.setError(getString(R.string.error_invalid_password));
- focusView = mPasswordView;
- cancel = true;
- }
- // Check untuk valid email dan formatnya.
- if (TextUtils.isEmpty(email)) {
- mEmailView.setError(getString(R.string.error_field_required));
- focusView = mEmailView;
- cancel = true;
- } else if (!isEmailValid(email)) {
- mEmailView.setError(getString(R.string.error_invalid_email));
- focusView = mEmailView;
- cancel = true;
- }
- // Jika cancel, maka tampilkan pesan error
- // Status cancel bernilai true jika syarat login pada form login tidak terpenuhi
- // Misalkan email / password kosong, dsb
- if (cancel) {
- // There was an error; don't attempt login and focus the first
- // form field with an error.
- focusView.requestFocus();
- } else {
- // Jika status cancel = false, atau tidak ada kesalahan, maka mulai melakukan verifikasi data login dengan server
- showProgress(true);
- mAuthTask = new UserLoginTask(email, password);
- mAuthTask.execute((Void) null);
- }
- }
- private boolean isEmailValid(String email) {
- //TODO: Replace this with your own logic
- return email.contains("@");
- }
- private boolean isPasswordValid(String password) {
- //TODO: Replace this with your own logic
- return password.length() > 2;
- }
- // Loader icon untuk login
- @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
- public void showProgress(final boolean show) {
- // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
- // for very easy animations. If available, use these APIs to fade-in
- // the progress spinner.
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
- int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
- mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
- mLoginFormView.animate().setDuration(shortAnimTime).alpha(
- show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
- @Override
- public void onAnimationEnd(Animator animation) {
- mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
- }
- });
- mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
- mProgressView.animate().setDuration(shortAnimTime).alpha(
- show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
- @Override
- public void onAnimationEnd(Animator animation) {
- mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
- }
- });
- } else {
- // The ViewPropertyAnimator APIs are not available, so simply show
- // and hide the relevant UI components.
- mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
- mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
- }
- }
- @Override
- public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
- return new CursorLoader(this,
- // Retrieve data rows for the device user's 'profile' contact.
- Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
- ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
- // Select only email addresses.
- ContactsContract.Contacts.Data.MIMETYPE +
- " = ?", new String[]{ContactsContract.CommonDataKinds.Email
- .CONTENT_ITEM_TYPE},
- // Show primary email addresses first. Note that there won't be
- // a primary email address if the user hasn't specified one.
- ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
- }
- @Override
- public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
- List<String> emails = new ArrayList<String>();
- cursor.moveToFirst();
- while (!cursor.isAfterLast()) {
- emails.add(cursor.getString(ProfileQuery.ADDRESS));
- cursor.moveToNext();
- }
- addEmailsToAutoComplete(emails);
- }
- @Override
- public void onLoaderReset(Loader<Cursor> cursorLoader) {
- }
- private interface ProfileQuery {
- String[] PROJECTION = {
- ContactsContract.CommonDataKinds.Email.ADDRESS,
- ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
- };
- int ADDRESS = 0;
- int IS_PRIMARY = 1;
- }
- private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
- //Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
- ArrayAdapter<String> adapter =
- new ArrayAdapter<String>(LoginActivity.this,
- android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
- mEmailView.setAdapter(adapter);
- }
- // Mendeklarasikan class UserLoginTask yang berfungsi untuk melakukan verifikasi data login dengan server
- public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
- private final String mEmail;
- private final String mPassword;
- UserLoginTask(String email, String password) {
- mEmail = email;
- mPassword = password;
- }
- @Override
- protected Boolean doInBackground(Void... params) {
- // TODO: attempt authentication against a network service.
- List<NameValuePair> par = new ArrayList<NameValuePair>();
- par.add(new BasicNameValuePair("email", mEmail));
- par.add(new BasicNameValuePair("password", mPassword));
- json = jParser.makeHttpRequest(Constants.MOBILE_API_SERVER_BASE_URL + "action_login.php", "POST", par);
- boolean valid = false;
- try {
- if (!json.getString("valid").equals("")) {
- valid = true;
- JSONObject jsonValid = json.getJSONObject("valid");
- Log.d("_MSG_VALID_", json.getString("valid"));
- user = new User(jsonValid.getInt("id"), jsonValid.getString("email"), jsonValid.getString("password"));
- }
- } catch (JSONException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return valid;
- }
- @Override
- protected void onPostExecute(final Boolean success) {
- mAuthTask = null;
- showProgress(false);
- // Melakukan pemeriksaan akun, jika sukses maka akan ditampilkan MainActivity
- // Passing data informasi dari user melalui intent 'USER_SESSION'
- if (success) {
- finish();
- Intent intent = new Intent(getApplicationContext(), MainActivity.class);
- intent.putExtra("USER_SESSION", user);
- startActivity(intent);
- } else {
- Helper.toast(getApplicationContext(), "Invalid login");
- mPasswordView.setError(getString(R.string.error_incorrect_password));
- mPasswordView.requestFocus();
- }
- }
- @Override
- protected void onCancelled() {
- mAuthTask = null;
- showProgress(false);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement