UAS MOBILE PROGRAMING
TUGAS UAS MOBILE PROGRAMING
APLIKASI ENSIKLOPEDIA HEWAN DENGAN LISTVIEW MENGGUNAKAN LOGIN YANG TERKNEKSI SQLITE DATABASE PADA ANDROID STUDIO
1. Deskripsi
Aplikasi mobile untuk memberi pengetahuan dan edukasi tentang hewan-hewan yang dilindungi di Indonesia.
2. XML text
2. XML text
- login.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/bc" tools:context=".LoginActivity"> <ProgressBar android:id="@+id/login_progress" style="?android:attr/progressBarStyleLarge" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:visibility="gone" /> <ScrollView android:id="@+id/login_form" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentTop="true"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="20dp" android:layout_marginEnd="20dp" android:layout_gravity="center_vertical" android:orientation="vertical" android:paddingBottom="50dp"> <TextView android:id="@+id/text_sign_title" fontPath="myfonts/Poppins-SemiBold_0.ttf" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:text="Selamat Datang" android:layout_gravity="center_horizontal" android:textColor="@color/text_black" android:textSize="26sp" tools:ignore="MissingPrefix" /> <LinearLayout android:id="@+id/email_login_form" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="80dp" android:orientation="horizontal"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:contentDescription="@string/app_name" android:layout_marginEnd="10dp" android:layout_marginRight="10dp" android:paddingTop="10dp" android:paddingBottom="10dp" android:src="@drawable/ic_email_blue" /> <EditText android:id="@+id/email" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:layout_marginStart="10dp" android:layout_marginEnd="10dp" android:hint="Email" android:inputType="textEmailAddress" android:singleLine="true" android:textColor="@color/black" android:textColorHint="@color/colorRed" android:textCursorDrawable="@drawable/cursor" android:textSize="16sp" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:orientation="horizontal"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="10dp" android:layout_marginRight="10dp" android:contentDescription="@string/app_name" android:paddingTop="10dp" android:paddingBottom="10dp" android:src="@drawable/ic_key" /> <EditText android:id="@+id/password" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:layout_marginStart="10dp" android:layout_marginEnd="10dp" android:hint="Password" android:inputType="textPassword" android:singleLine="true" android:textColor="@color/black" android:textColorHint="@color/black" android:textCursorDrawable="@drawable/cursor" android:textSize="16sp" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:orientation="horizontal"> <ImageView android:id="@+id/img1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="10dp" android:layout_marginRight="10dp" android:contentDescription="@string/app_name" android:paddingTop="10dp" android:paddingBottom="10dp" android:src="@drawable/ic_key_light" android:visibility="gone" /> <EditText android:id="@+id/passwordRepeat" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:layout_marginStart="10dp" android:layout_marginEnd="10dp" android:hint="Re-Password" android:inputType="textPassword" android:singleLine="true" android:textColor="@color/blue_lighht" android:textColorHint="@color/blue_lighht" android:textCursorDrawable="@drawable/cursor" android:textSize="16sp" android:visibility="gone" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <ImageView android:id="@+id/img2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="10dp" android:layout_marginRight="10dp" android:contentDescription="@string/app_name" android:paddingTop="10dp" android:paddingBottom="10dp" android:src="@drawable/ic_user" android:visibility="gone" /> <EditText android:id="@+id/nameBox" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:layout_marginStart="10dp" android:layout_marginEnd="10dp" android:hint="Nama" android:inputType="text" android:singleLine="true" android:textColor="@color/blue_lighht" android:textColorHint="@color/blue_lighht" android:textCursorDrawable="@drawable/cursor" android:textSize="16sp" android:visibility="gone" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:orientation="horizontal"> <ImageView android:id="@+id/img3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="10dp" android:layout_marginRight="10dp" android:contentDescription="@string/app_name" android:paddingTop="10dp" android:paddingBottom="10dp" android:src="@drawable/ic_mobile" android:visibility="gone" /> <EditText android:id="@+id/phoneBox" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:layout_marginStart="10dp" android:layout_marginEnd="10dp" android:hint="Telepon" android:inputType="phone" android:singleLine="true" android:textColor="@color/blue_lighht" android:textColorHint="@color/blue_lighht" android:textCursorDrawable="@drawable/cursor" android:textSize="16sp" android:visibility="gone" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/email_sign_in_button" style="?android:textAppearanceSmall" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:layout_marginRight="10dp" android:layout_weight="1" android:background="@color/blue_lighht" android:elevation="10dp" android:text="@string/action_sign_in_short" android:textColor="@color/colorWhite" android:textStyle="bold" /> <Button android:id="@+id/register_button" style="?android:textAppearanceSmall" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:layout_weight="1" android:background="@color/blue_lighht" android:elevation="10dp" android:clickable="true" android:onClick="registerRequest" android:text="@string/action_register" android:textColor="@color/colorWhite" /> <Button android:id="@+id/signup_button" style="?android:textAppearanceSmall" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:layout_marginRight="10dp" android:layout_weight="0.75" android:background="@color/blue_lighht" android:text="@string/action_submit" android:textColor="@color/colorWhite" android:textStyle="bold" android:visibility="gone" /> <Button android:id="@+id/signin_button" style="?android:textAppearanceSmall" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:layout_weight="1.25" android:clickable="true" android:onClick="signinRequest" android:text="@string/action_have_account" android:background="@color/blue_lighht" android:textColor="@color/colorWhite" android:visibility="gone" /> </LinearLayout> </LinearLayout> </ScrollView> </RelativeLayout>
- main.xml
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/bc" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:gravity="center_horizontal" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent"> <TextView android:id="@+id/txt_welcome" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/txt_welcome" android:textSize="10pt" android:textAllCaps="true"/> <TextView android:id="@+id/txt_profile_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/txt_welcome" android:layout_marginTop="20dp" android:text="" android:textStyle="bold" android:textSize="8pt" /> <Button android:id="@+id/btn_data" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/txt_profile_name" android:layout_marginTop="30dp" android:text="Lihat Data Hewan" android:background="@color/blue_lighht" android:textColor="@color/colorWhite" android:paddingHorizontal="40dp"/> </LinearLayout> </android.support.constraint.ConstraintLayout>
- menuutama.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/bc" tools:context=".MenuUtama"> <ListView android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/bc" android:id="@+id/ListView1" android:layout_centerHorizontal="true" android:layout_centerVertical="true"> </ListView> </RelativeLayout>
- komodo.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".Komodo"> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/activity_main" android:background="@drawable/bc"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <FrameLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <ImageView android:layout_width="match_parent" android:layout_height="wrap_content" android:adjustViewBounds="true" android:scaleType="fitXY" android:src="@drawable/komodo"/> </FrameLayout> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="16dp" android:text="KOMODO" android:textSize="32sp" android:textStyle="bold" android:textAlignment="center" android:textColor="@android:color/black"/> <TableLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" android:layout_marginBottom="16dp"> <TableRow android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="14sp" android:layout_marginRight="16dp" android:text="Kingdom"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="14sp" android:layout_weight="1" android:text="" android:textColor="@android:color/black"/> </TableRow> <TableRow android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="14sp" android:layout_marginRight="16dp" android:text="Filum"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="14sp" android:layout_weight="1" android:text="" android:textColor="@android:color/black"/> </TableRow> <TableRow android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="14sp" android:layout_marginRight="16dp" android:text="Kelas"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="14sp" android:layout_weight="1" android:text="" android:textColor="@android:color/black"/> </TableRow> <TableRow android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="14sp" android:layout_marginRight="16dp" android:text="Ordo"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="14sp" android:layout_weight="1" android:text="Squamata" android:textColor="@android:color/black"/> </TableRow> <TableRow android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="14sp" android:layout_marginRight="16dp" android:text="Family"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="14sp" android:layout_weight="1" android:text="Varanidae" android:textColor="@android:color/black"/> </TableRow> <TableRow android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="14sp" android:layout_marginRight="16dp" android:text="Genus"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="14sp" android:layout_weight="1" android:text="Varanus" android:textColor="@android:color/black"/> </TableRow> <TableRow android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="14sp" android:layout_marginRight="16dp" android:text="Spesies"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="14sp" android:layout_weight="1" android:text="Varanus Komodoensis" android:textColor="@android:color/black"/> </TableRow> </TableLayout> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/komodo" android:layout_margin="10dp" android:paddingLeft="10dp" android:paddingRight="10dp" android:textSize="16dp" android:textColor="@android:color/black"/> </LinearLayout> </ScrollView> </LinearLayout>
3. XML Graphic
- Login
- Main
4. SOURCE CODING JAVA
- Login.java
public class LoginActivity extends AppCompatActivity {
private UserLoginTask mAuthTask = null;
private EditText mEmailView;
private EditText mPasswordView;
private EditText passwordRepeat;
private EditText nameBox;
private EditText phoneBox;
private Button mEmailSignInButton;
private Button signup_button;
private Button register_button;
private Button signin_button;
private View mProgressView;
private View mLoginFormView;
private ImageView img1, img2, img3;
public final static String TAG_ID = "id";
public final static String TAG_EMAIL = "email";
public final static String TAG_NAME = "name";
public final static String TAG_PHONE = "phone";
public final static String TAG_PASSWORD = "password";
SharedPreferences sharedpreferences;
Boolean session = false;
String id, email, name;
public static final String my_shared_preferences = "my_shared_preferences";
public static final String session_status = "session_status";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
initiateCoreApp();
checkSession();
mEmailView = (EditText) findViewById(R.id.email);
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
nameBox = findViewById(R.id.nameBox);
phoneBox = findViewById(R.id.phoneBox);
img1 = (ImageView) findViewById(R.id.img1);
img2 = (ImageView) findViewById(R.id.img2);
img3 = (ImageView) findViewById(R.id.img3);
signup_button = (Button) findViewById(R.id.signup_button);
signup_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
attemptRegister();
}
});
register_button = (Button) findViewById(R.id.register_button);
signin_button = (Button) findViewById(R.id.signin_button);
passwordRepeat = (EditText) findViewById(R.id.passwordRepeat);
}
private void initiateCoreApp() {
Database database = new DatabaseHelper(this);
UserController.setDatabase(database);
}
private void attemptLogin() {
if (mAuthTask != null) {
return;
}
mEmailView.setError(null);
mPasswordView.setError(null);
String email = mEmailView.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
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;
}
if (cancel) {
focusView.requestFocus();
} else {
showProgress(true);
mAuthTask = new UserLoginTask(email, password);
mAuthTask.execute((Void) null);
}
}
public static boolean isEmailValid(String email) {
//TODO: Replace this with your own logic
return email.contains("@");
}
public static boolean isPasswordValid(String password) {
//TODO: Replace this with your own logic
return password.length() > 2;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
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 {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private final String mEmail;
private final String mPassword;
private ContentValues admin;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
@Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
admin = UserController.getInstance().getDataByEmail(mEmail);
if (admin != null) {
if (mPassword.equals(admin.getAsString("password"))) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(session_status, true);
editor.putString(TAG_ID, admin.getAsString("_id"));
editor.putString(TAG_EMAIL, admin.getAsString("email"));
editor.putString(TAG_NAME, admin.getAsString("name"));
editor.putString(TAG_PHONE, admin.getAsString("phone"));
editor.commit();
} else {
return false;
}
return true;
}
return false;
}
@Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra(TAG_ID, id);
intent.putExtra(TAG_EMAIL, email);
if (admin != null) {
intent.putExtra(TAG_NAME, admin.getAsString("name"));
}
finish();
startActivity(intent);
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
@Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
private void checkSession() {
sharedpreferences = getSharedPreferences(my_shared_preferences, Context.MODE_PRIVATE);
session = sharedpreferences.getBoolean(session_status, false);
id = sharedpreferences.getString(TAG_ID, null);
email = sharedpreferences.getString(TAG_EMAIL, null);
name = sharedpreferences.getString(TAG_NAME, null);
if (session) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra(TAG_ID, id);
intent.putExtra(TAG_EMAIL, email);
intent.putExtra(TAG_NAME, name);
finish();
startActivity(intent);
}
}
public void registerRequest(View view) {
img1.setVisibility(View.VISIBLE);
img2.setVisibility(View.VISIBLE);
img3.setVisibility(View.VISIBLE);
nameBox.setVisibility(View.VISIBLE);
phoneBox.setVisibility(View.VISIBLE);
mEmailSignInButton.setVisibility(View.GONE);
signup_button.setVisibility(View.VISIBLE);
register_button.setVisibility(View.GONE);
signin_button.setVisibility(View.VISIBLE);
passwordRepeat.setVisibility(View.VISIBLE);
}
public void signinRequest(View view) {
img1.setVisibility(View.GONE);
img2.setVisibility(View.GONE);
img3.setVisibility(View.GONE);
nameBox.setVisibility(View.GONE);
phoneBox.setVisibility(View.GONE);
mEmailSignInButton.setVisibility(View.VISIBLE);
signup_button.setVisibility(View.GONE);
register_button.setVisibility(View.VISIBLE);
signin_button.setVisibility(View.GONE);
passwordRepeat.setVisibility(View.GONE);
}
private void attemptRegister() {
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();
String password_repeat = passwordRepeat.getText().toString();
String full_name = nameBox.getText().toString();
String phone = phoneBox.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
if (!TextUtils.isEmpty(password_repeat) && !isPasswordValid(password_repeat)) {
passwordRepeat.setError(getString(R.string.error_invalid_password));
focusView = passwordRepeat;
cancel = true;
}
if (!password_repeat.equals(password)) {
passwordRepeat.setError(getString(R.string.error_invalid_password_repeat));
focusView = passwordRepeat;
cancel = true;
}
// Check for a valid email address.
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;
} else {
ContentValues adminData = UserController.getInstance().getDataByEmail(email);
if (adminData != null) {
mEmailView.setError(getString(R.string.error_unavailable_email));
focusView = mEmailView;
cancel = true;
}
}
if (TextUtils.isEmpty(full_name)) {
nameBox.setError(getString(R.string.error_field_required));
focusView = nameBox;
cancel = true;
}
if (TextUtils.isEmpty(phone)) {
phoneBox.setError(getString(R.string.error_field_required));
focusView = phoneBox;
cancel = true;
}
if (cancel) {
focusView.requestFocus();
} else {
showProgress(true);
ContentValues content = new ContentValues();
content.put("email", email);
content.put("name", full_name);
content.put("password", password);
content.put("phone", phone);
content.put("date_added", getCurrentTime());
int id = UserController.getInstance().register(content);
if (id > 0) {
mAuthTask = new UserLoginTask(email, password);
mAuthTask.execute((Void) null);
}
}
}
/**
* Geting current time
* @return
*/
private String getCurrentTime() {
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = df.format(c);
return formattedDate;
}
}
private UserLoginTask mAuthTask = null;
private EditText mEmailView;
private EditText mPasswordView;
private EditText passwordRepeat;
private EditText nameBox;
private EditText phoneBox;
private Button mEmailSignInButton;
private Button signup_button;
private Button register_button;
private Button signin_button;
private View mProgressView;
private View mLoginFormView;
private ImageView img1, img2, img3;
public final static String TAG_ID = "id";
public final static String TAG_EMAIL = "email";
public final static String TAG_NAME = "name";
public final static String TAG_PHONE = "phone";
public final static String TAG_PASSWORD = "password";
SharedPreferences sharedpreferences;
Boolean session = false;
String id, email, name;
public static final String my_shared_preferences = "my_shared_preferences";
public static final String session_status = "session_status";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
initiateCoreApp();
checkSession();
mEmailView = (EditText) findViewById(R.id.email);
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
nameBox = findViewById(R.id.nameBox);
phoneBox = findViewById(R.id.phoneBox);
img1 = (ImageView) findViewById(R.id.img1);
img2 = (ImageView) findViewById(R.id.img2);
img3 = (ImageView) findViewById(R.id.img3);
signup_button = (Button) findViewById(R.id.signup_button);
signup_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
attemptRegister();
}
});
register_button = (Button) findViewById(R.id.register_button);
signin_button = (Button) findViewById(R.id.signin_button);
passwordRepeat = (EditText) findViewById(R.id.passwordRepeat);
}
private void initiateCoreApp() {
Database database = new DatabaseHelper(this);
UserController.setDatabase(database);
}
private void attemptLogin() {
if (mAuthTask != null) {
return;
}
mEmailView.setError(null);
mPasswordView.setError(null);
String email = mEmailView.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
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;
}
if (cancel) {
focusView.requestFocus();
} else {
showProgress(true);
mAuthTask = new UserLoginTask(email, password);
mAuthTask.execute((Void) null);
}
}
public static boolean isEmailValid(String email) {
//TODO: Replace this with your own logic
return email.contains("@");
}
public static boolean isPasswordValid(String password) {
//TODO: Replace this with your own logic
return password.length() > 2;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
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 {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private final String mEmail;
private final String mPassword;
private ContentValues admin;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
@Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
admin = UserController.getInstance().getDataByEmail(mEmail);
if (admin != null) {
if (mPassword.equals(admin.getAsString("password"))) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(session_status, true);
editor.putString(TAG_ID, admin.getAsString("_id"));
editor.putString(TAG_EMAIL, admin.getAsString("email"));
editor.putString(TAG_NAME, admin.getAsString("name"));
editor.putString(TAG_PHONE, admin.getAsString("phone"));
editor.commit();
} else {
return false;
}
return true;
}
return false;
}
@Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra(TAG_ID, id);
intent.putExtra(TAG_EMAIL, email);
if (admin != null) {
intent.putExtra(TAG_NAME, admin.getAsString("name"));
}
finish();
startActivity(intent);
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
@Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
private void checkSession() {
sharedpreferences = getSharedPreferences(my_shared_preferences, Context.MODE_PRIVATE);
session = sharedpreferences.getBoolean(session_status, false);
id = sharedpreferences.getString(TAG_ID, null);
email = sharedpreferences.getString(TAG_EMAIL, null);
name = sharedpreferences.getString(TAG_NAME, null);
if (session) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra(TAG_ID, id);
intent.putExtra(TAG_EMAIL, email);
intent.putExtra(TAG_NAME, name);
finish();
startActivity(intent);
}
}
public void registerRequest(View view) {
img1.setVisibility(View.VISIBLE);
img2.setVisibility(View.VISIBLE);
img3.setVisibility(View.VISIBLE);
nameBox.setVisibility(View.VISIBLE);
phoneBox.setVisibility(View.VISIBLE);
mEmailSignInButton.setVisibility(View.GONE);
signup_button.setVisibility(View.VISIBLE);
register_button.setVisibility(View.GONE);
signin_button.setVisibility(View.VISIBLE);
passwordRepeat.setVisibility(View.VISIBLE);
}
public void signinRequest(View view) {
img1.setVisibility(View.GONE);
img2.setVisibility(View.GONE);
img3.setVisibility(View.GONE);
nameBox.setVisibility(View.GONE);
phoneBox.setVisibility(View.GONE);
mEmailSignInButton.setVisibility(View.VISIBLE);
signup_button.setVisibility(View.GONE);
register_button.setVisibility(View.VISIBLE);
signin_button.setVisibility(View.GONE);
passwordRepeat.setVisibility(View.GONE);
}
private void attemptRegister() {
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();
String password_repeat = passwordRepeat.getText().toString();
String full_name = nameBox.getText().toString();
String phone = phoneBox.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
if (!TextUtils.isEmpty(password_repeat) && !isPasswordValid(password_repeat)) {
passwordRepeat.setError(getString(R.string.error_invalid_password));
focusView = passwordRepeat;
cancel = true;
}
if (!password_repeat.equals(password)) {
passwordRepeat.setError(getString(R.string.error_invalid_password_repeat));
focusView = passwordRepeat;
cancel = true;
}
// Check for a valid email address.
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;
} else {
ContentValues adminData = UserController.getInstance().getDataByEmail(email);
if (adminData != null) {
mEmailView.setError(getString(R.string.error_unavailable_email));
focusView = mEmailView;
cancel = true;
}
}
if (TextUtils.isEmpty(full_name)) {
nameBox.setError(getString(R.string.error_field_required));
focusView = nameBox;
cancel = true;
}
if (TextUtils.isEmpty(phone)) {
phoneBox.setError(getString(R.string.error_field_required));
focusView = phoneBox;
cancel = true;
}
if (cancel) {
focusView.requestFocus();
} else {
showProgress(true);
ContentValues content = new ContentValues();
content.put("email", email);
content.put("name", full_name);
content.put("password", password);
content.put("phone", phone);
content.put("date_added", getCurrentTime());
int id = UserController.getInstance().register(content);
if (id > 0) {
mAuthTask = new UserLoginTask(email, password);
mAuthTask.execute((Void) null);
}
}
}
/**
* Geting current time
* @return
*/
private String getCurrentTime() {
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = df.format(c);
return formattedDate;
}
}
- MainActivity.java
public class MainActivity extends AppCompatActivity { TextView txt_profile_name; Button btn_data; SharedPreferences sharedpreferences; Intent intent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txt_profile_name = (TextView) findViewById(R.id.txt_profile_name); txt_profile_name.setText(getIntent().getExtras().get("name").toString()); btn_data = (Button) findViewById(R.id.btn_data); btn_data.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { logout(); } }); } private void logout() { sharedpreferences = getSharedPreferences( LoginActivity.my_shared_preferences, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putBoolean(LoginActivity.session_status, false); editor.putString(LoginActivity.TAG_ID, null); editor.putString(LoginActivity.TAG_EMAIL, null); editor.putString(LoginActivity.TAG_NAME, null); editor.putString(LoginActivity.TAG_PHONE, null); editor.commit(); intent = new Intent(MainActivity.this, MenuUtama.class); finish(); startActivity(intent); } }
- Menu utama.java
public class MenuUtama extends AppCompatActivity { ListView Tampilan; String[] hewan={"KOMODO","BADAK","HARIMAU SUMATERA","ELANG JAWA","ANOA", "ORANG UTAN","TARSIUS","JALAK BALI","TRENGGILING","BABIRUSA"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_menu_utama); Tampilan=(ListView)findViewById(R.id.ListView1); ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,hewan); Tampilan.setAdapter(adapter); Tampilan.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { int itemke = arg2; String itemText = (String) Tampilan.getItemAtPosition(arg2); Toast.makeText(getBaseContext(), "Anda Meng Klik " + itemText, Toast.LENGTH_LONG).show(); if (itemText.equals("KOMODO")) { Intent hewanintent = new Intent(arg0.getContext(), Komodo.class); startActivityForResult(hewanintent, 0); } else if (itemText.equals("BADAK")) { Intent hewanintent = new Intent(arg0.getContext(), Badak.class); startActivityForResult(hewanintent, 0); } else if (itemText.equals("HARIMAU SUMATERA")) { Intent hewanintent = new Intent(arg0.getContext(), Harimausum.class); startActivityForResult(hewanintent, 0); } } }); } }
- komodo.java
public class Komodo extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_komodo); } }
- databasehelper.java
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import java.util.ArrayList; import java.util.List; public class DatabaseHelper extends SQLiteOpenHelper implements Database { private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = DatabaseContents.DATABASE.toString(); public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + DatabaseContents.TABLE_USERS + "(" + "_id INTEGER PRIMARY KEY," + "name TEXT(100)," + "email TEXT(32)," + "password TEXT(256)," + "phone TEXT(32)," + "status INTEGER DEFAULT 1," + "date_added DATETIME" + ");"); Log.d("CREATE DATABASE", "Create " + DatabaseContents.TABLE_USERS + " Successfully."); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + DatabaseContents.TABLE_USERS); onCreate(db); } @Override public List<Object> select(String queryString) { try { SQLiteDatabase database = this.getWritableDatabase(); List<Object> list = new ArrayList<Object>(); Cursor cursor = database.rawQuery(queryString, null); if (cursor != null) { if (cursor.moveToFirst()) { do { ContentValues content = new ContentValues(); String[] columnNames = cursor.getColumnNames(); for (String columnName : columnNames) { content.put(columnName, cursor.getString(cursor .getColumnIndex(columnName))); } list.add(content); } while (cursor.moveToNext()); } } cursor.close(); database.close(); return list; } catch (Exception e) { e.printStackTrace(); return null; } } @Override public int insert(String tableName, Object content) { try { SQLiteDatabase database = this.getWritableDatabase(); int id = (int) database.insert(tableName, null, (ContentValues) content); database.close(); return id; } catch (Exception e) { e.printStackTrace(); return -1; } } @Override public boolean update(String tableName, Object content) { try { SQLiteDatabase database = this.getWritableDatabase(); ContentValues cont = (ContentValues) content; // this array will always contains only one element. String[] array = new String[]{cont.get("_id")+""}; database.update(tableName, cont, " _id = ?", array); return true; } catch (Exception e) { e.printStackTrace(); return false; } } @Override public boolean delete(String tableName, int id) { try { SQLiteDatabase database = this.getWritableDatabase(); database.delete(tableName, " _id = ?", new String[]{id+""}); return true; } catch (Exception e) { e.printStackTrace(); return false; } } @Override public boolean execute(String queryString) { try{ SQLiteDatabase database = this.getWritableDatabase(); database.execSQL(queryString); return true; }catch(Exception e){ e.printStackTrace(); return false; } } }
- kontrol pengguna.java
public class UserController { private static Database database; private static UserController instance; private UserController() {} public static UserController getInstance() { if (instance == null) instance = new UserController(); return instance; } public static void setDatabase(Database db) { database = db; } public ContentValues getDataByEmail(String email) { String queryString = "SELECT * FROM " + DatabaseContents.TABLE_USERS + " WHERE email = '"+ email +"'"; List<Object> contents = database.select(queryString); if (contents.isEmpty()) { return null; } ContentValues content = (ContentValues) contents.get(0); return content; } public Object getUsers() { List<Object> contents = database.select("SELECT * FROM " + DatabaseContents.TABLE_USERS); return contents; } public int register(ContentValues content) { int id = database.insert(DatabaseContents.TABLE_USERS.toString(), content); return id; } public boolean update(ContentValues content) { boolean update = database.update(DatabaseContents.TABLE_USERS.toString(), content); return update; } }
6. Screenshoot Aplikasi
7. Demo APK
Nama : Deny Supriyadi
Nim : 161021450456
Kelas : 06TPLM003
Matkul : Mobile Programing
Sekian aplikasi sederhana listview menggunakan login sqlite database, semoga mampu mendapatkan nilai yang memuaskan. Terimakasih.
Komentar
Posting Komentar