· 5 years ago · Apr 15, 2020, 01:56 AM
1y Studio
2
330 Menit Membuat Login Android Dengan SQLite Database
4 August 6, 2019 Guntoro Android Simple Example, Android Studio, Material Design, Mobile Development
5Jika sebelumnya kita pernah belajar membuat ui login desain menarik dalam 30 menit menggunakan android studio. Kali ini kita akan belajar membuat form login android pada android studio dengan menggunakan sqlite database.
6
7Baca Juga :
8
930 Menit Membuat Aplikasi Penjualan Dengan Android Studio
10Membuat Aplikasi dengan SQLite dan Android Studio
11Apa itu firebase ? Inilah ulasan lengkapnya
12Pemrograman mobile : Panduan untuk pemula
13Untuk aplikasi login sqlite yang sudah running kamu bisa melihatnya pada video dibawah ini.
14
15
16
17Membuat Login Android Dengan SQLite Database
18Tanpa basa basi langsung saja kita praktekan membuat login android menggunakan sqlite database.
19
201. Buat Project Baru
21Langkah pertama silahkan buat project baru di android studio dengan menggunakan nama project loginsqlite. Jika masih bingung kamu bisa membaca tutorial membuat project pertama di android.
22
23
24
252. Library Material Design
26Tambahkan library material design dengan cara klik gradle (module:app) > masukan 1 baris kode berikut pada dependencies > klik sync now (pastikan terknoneksi dengan internet )
27
28implementation 'com.android.support:design:26.1.0'
29
30
313. Edit String
32Edit string yang nantinya digunakan untuk nama aplikasi dan beberapa komponen widget. Buka res > values > string.xml. disini Kamu bisa pelajari struktur folder android .
33
34<resources>
35 <string name="app_name">LoginRegisterScreenDesign</string>
36 <string name="create_account"><font color="#00ff00">text</font></string>
37 <string name="email">Email</string>
38 <string name="password">Password</string>
39 <string name="login">Login</string>
40 <string name="username">Username</string>
41 <string name="register">Register</string>
42 <string name="back_to_login">Back to Login</string>
43</resources>
44
45
46
47
48
494. Edit Color
50Edit warna yang dengan cara buka res > values > colors.xml.
51
52<?xml version="1.0" encoding="utf-8"?>
53<resources>
54 <color name="colorPrimary">#607d8b</color>
55 <color name="colorPrimaryDark">#455a64</color>
56 <color name="colorAccent">#0c0099</color>
57</resources>
58
595. Drawable
60Copykan gambar/ icon pendukung (download disini ). Caranya klik kanan pada drawable > klik paste.
61
62
63
646. Edit Style
65Edit tema pada res > values > styles.xml. Dalam aplikasi yang akan kita buat ini kita tidak akan menampilkan action bar (app bar). Sehingga kode-kodenya kita edit menjadi seperti seperti berikut.
66
67<resources>
68
69 <!-- Base application theme. -->
70 <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
71 <!-- Customize your theme here. -->
72 <item name="colorPrimary">@color/colorPrimary</item>
73 <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
74 <item name="colorAccent">@color/colorAccent</item>
75 </style>
76
77 <style name="AppTheme.NoActionBar">
78 <item name="windowActionBar">false</item>
79 <item name="windowNoTitle">true</item>
80 </style>
81
82 <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
83
84 <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
85
86</resources>
87
88
897. Activity Login
90Buat activity login dengan cara klik folder java > klik kanan nama package > New > Activity > Empty Activity > Isikan Nama LoginActivity. Sehingga akan terdapat class java LoginActivity.java dan layout activity_login.xml.
91
92LoginActivity.java
93Masukan kode-kode berikut dibawah nama package.
94
95import android.content.Intent;
96import android.os.Bundle;
97import android.support.design.widget.Snackbar;
98import android.support.design.widget.TextInputLayout;
99import android.support.v7.app.AppCompatActivity;
100import android.text.Html;
101import android.text.Spanned;
102import android.view.View;
103import android.widget.Button;
104import android.widget.EditText;
105import android.widget.TextView;
106
107public class LoginActivity extends AppCompatActivity {
108
109 //Declaration EditTexts
110 EditText editTextEmail;
111 EditText editTextPassword;
112
113 //Declaration TextInputLayout
114 TextInputLayout textInputLayoutEmail;
115 TextInputLayout textInputLayoutPassword;
116
117 //Declaration Button
118 Button buttonLogin;
119
120 //Declaration SqliteHelper
121 SqliteHelper sqliteHelper;
122
123 @Override
124 protected void onCreate(Bundle savedInstanceState) {
125 super.onCreate(savedInstanceState);
126 setContentView(R.layout.activity_login);
127 sqliteHelper = new SqliteHelper(this);
128 initCreateAccountTextView();
129 initViews();
130
131 //set click event of login button
132 buttonLogin.setOnClickListener(new View.OnClickListener() {
133 @Override
134 public void onClick(View view) {
135
136 //Check user input is correct or not
137 if (validate()) {
138
139 //Get values from EditText fields
140 String Email = editTextEmail.getText().toString();
141 String Password = editTextPassword.getText().toString();
142
143 //Authenticate user
144 User currentUser = sqliteHelper.Authenticate(new User(null, null, Email, Password));
145
146 //Check Authentication is successful or not
147 if (currentUser != null) {
148 Snackbar.make(buttonLogin, "Successfully Logged in!", Snackbar.LENGTH_LONG).show();
149
150 //User Logged in Successfully Launch You home screen activity
151 Intent intent=new Intent(LoginActivity.this,MainActivity.class);
152 startActivity(intent);
153 finish();
154
155 } else {
156
157 //User Logged in Failed
158 Snackbar.make(buttonLogin, "Failed to log in , please try again", Snackbar.LENGTH_LONG).show();
159
160 }
161 }
162 }
163 });
164
165
166 }
167
168 //this method used to set Create account TextView text and click event( maltipal colors
169 // for TextView yet not supported in Xml so i have done it programmatically)
170 private void initCreateAccountTextView() {
171 TextView textViewCreateAccount = (TextView) findViewById(R.id.textViewCreateAccount);
172 textViewCreateAccount.setText(fromHtml("<font color='#ffffff'>I don't have account yet. </font><font color='#0c0099'>create one</font>"));
173 textViewCreateAccount.setOnClickListener(new View.OnClickListener() {
174 @Override
175 public void onClick(View view) {
176 Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
177 startActivity(intent);
178 }
179 });
180 }
181
182 //this method is used to connect XML views to its Objects
183 private void initViews() {
184 editTextEmail = (EditText) findViewById(R.id.editTextEmail);
185 editTextPassword = (EditText) findViewById(R.id.editTextPassword);
186 textInputLayoutEmail = (TextInputLayout) findViewById(R.id.textInputLayoutEmail);
187 textInputLayoutPassword = (TextInputLayout) findViewById(R.id.textInputLayoutPassword);
188 buttonLogin = (Button) findViewById(R.id.buttonLogin);
189
190 }
191
192 //This method is for handling fromHtml method deprecation
193 @SuppressWarnings("deprecation")
194 public static Spanned fromHtml(String html) {
195 Spanned result;
196 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
197 result = Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY);
198 } else {
199 result = Html.fromHtml(html);
200 }
201 return result;
202 }
203
204 //This method is used to validate input given by user
205 public boolean validate() {
206 boolean valid = false;
207
208 //Get values from EditText fields
209 String Email = editTextEmail.getText().toString();
210 String Password = editTextPassword.getText().toString();
211
212 //Handling validation for Email field
213 if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
214 valid = false;
215 textInputLayoutEmail.setError("Please enter valid email!");
216 } else {
217 valid = true;
218 textInputLayoutEmail.setError(null);
219 }
220
221 //Handling validation for Password field
222 if (Password.isEmpty()) {
223 valid = false;
224 textInputLayoutPassword.setError("Please enter valid password!");
225 } else {
226 if (Password.length() > 5) {
227 valid = true;
228 textInputLayoutPassword.setError(null);
229 } else {
230 valid = false;
231 textInputLayoutPassword.setError("Password is to short!");
232 }
233 }
234
235 return valid;
236 }
237
238
239}
240activity_login.xml
241Untuk membuat layout halaman login, silahkan ketikan kode-kode dibawah ini.
242
243<?xml version="1.0" encoding="utf-8"?>
244<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
245 xmlns:app="http://schemas.android.com/apk/res-auto"
246 android:layout_width="match_parent"
247 android:layout_height="match_parent"
248 xmlns:tools="http://schemas.android.com/tools"
249 android:background="@color/colorPrimary"
250 android:fitsSystemWindows="true"
251 tools:context=".LoginActivity">
252
253 <LinearLayout
254 android:layout_width="match_parent"
255 android:layout_height="wrap_content"
256 android:layout_gravity="center_vertical"
257 android:layout_marginLeft="16dp"
258 android:layout_marginRight="16dp"
259 android:orientation="vertical">
260
261 <ImageView
262 android:id="@+id/imageView"
263 android:layout_width="100dp"
264 android:layout_height="100dp"
265 android:layout_gravity="center_horizontal"
266 android:layout_margin="16dp"
267 android:src="@drawable/usericon" />
268
269 <android.support.design.widget.TextInputLayout
270 android:id="@+id/textInputLayoutEmail"
271 android:layout_width="match_parent"
272 android:layout_height="wrap_content"
273 android:layout_marginTop="16dp"
274 app:errorEnabled="true">
275
276 <android.support.design.widget.TextInputEditText
277 android:id="@+id/editTextEmail"
278 android:layout_width="match_parent"
279 android:layout_height="wrap_content"
280 android:hint="@string/email"
281 android:inputType="textEmailAddress" />
282 </android.support.design.widget.TextInputLayout>
283
284 <android.support.design.widget.TextInputLayout
285 android:id="@+id/textInputLayoutPassword"
286 android:layout_width="match_parent"
287 android:layout_height="wrap_content"
288 android:layout_marginTop="8dp"
289 app:errorEnabled="true"
290 app:passwordToggleEnabled="true"
291 app:passwordToggleTint="@color/colorAccent">
292
293 <android.support.design.widget.TextInputEditText
294 android:id="@+id/editTextPassword"
295 android:layout_width="match_parent"
296 android:layout_height="wrap_content"
297 android:hint="@string/password"
298 android:inputType="textPassword" />
299 </android.support.design.widget.TextInputLayout>
300
301 <Button
302 android:id="@+id/buttonLogin"
303 android:layout_width="match_parent"
304 android:layout_height="wrap_content"
305 android:layout_gravity="center_horizontal"
306 android:layout_marginTop="16dp"
307 android:background="@color/colorAccent"
308 android:text="@string/login"
309 android:textColor="@android:color/white" />
310
311 <TextView
312 android:id="@+id/textViewCreateAccount"
313 android:layout_width="match_parent"
314 android:layout_height="wrap_content"
315 android:layout_marginBottom="16dp"
316 android:layout_marginTop="16dp"
317 android:gravity="center_horizontal" />
318 </LinearLayout>
319</ScrollView>
320membuat login android dengan sqlite database
321Layout Login
322
323
3248. Activity Register
325Buat activity register dengan cara klik java > klik kanan nama package > New > Activity > Empty Activity > Isikan Nama RegisterActivity. Sehingga akan terdapat class java RegisterActivity.java dan layout activity_register.xml.
326
327RegisterActivity.java
328Untuk kode-kode RegisterActivity.java (tempatkan dibawah nama package) adalah :
329
330import android.os.Bundle;
331import android.os.Handler;
332import android.support.annotation.Nullable;
333import android.support.design.widget.Snackbar;
334import android.support.design.widget.TextInputLayout;
335import android.support.v7.app.AppCompatActivity;
336import android.view.View;
337import android.widget.Button;
338import android.widget.EditText;
339import android.widget.TextView;
340
341
342
343public class RegisterActivity extends AppCompatActivity {
344
345 //Declaration EditTexts
346 EditText editTextUserName;
347 EditText editTextEmail;
348 EditText editTextPassword;
349
350 //Declaration TextInputLayout
351 TextInputLayout textInputLayoutUserName;
352 TextInputLayout textInputLayoutEmail;
353 TextInputLayout textInputLayoutPassword;
354
355 //Declaration Button
356 Button buttonRegister;
357
358 //Declaration SqliteHelper
359 SqliteHelper sqliteHelper;
360
361 @Override
362 protected void onCreate(@Nullable Bundle savedInstanceState) {
363 super.onCreate(savedInstanceState);
364 setContentView(R.layout.activity_register);
365 sqliteHelper = new SqliteHelper(this);
366 initTextViewLogin();
367 initViews();
368 buttonRegister.setOnClickListener(new View.OnClickListener() {
369 @Override
370 public void onClick(View view) {
371 if (validate()) {
372 String UserName = editTextUserName.getText().toString();
373 String Email = editTextEmail.getText().toString();
374 String Password = editTextPassword.getText().toString();
375
376 //Check in the database is there any user associated with this email
377 if (!sqliteHelper.isEmailExists(Email)) {
378
379 //Email does not exist now add new user to database
380 sqliteHelper.addUser(new User(null, UserName, Email, Password));
381 Snackbar.make(buttonRegister, "User created successfully! Please Login ", Snackbar.LENGTH_LONG).show();
382 new Handler().postDelayed(new Runnable() {
383 @Override
384 public void run() {
385 finish();
386 }
387 }, Snackbar.LENGTH_LONG);
388 }else {
389
390 //Email exists with email input provided so show error user already exist
391 Snackbar.make(buttonRegister, "User already exists with same email ", Snackbar.LENGTH_LONG).show();
392 }
393
394
395 }
396 }
397 });
398 }
399
400 //this method used to set Login TextView click event
401 private void initTextViewLogin() {
402 TextView textViewLogin = (TextView) findViewById(R.id.textViewLogin);
403 textViewLogin.setOnClickListener(new View.OnClickListener() {
404 @Override
405 public void onClick(View view) {
406 finish();
407 }
408 });
409 }
410
411 //this method is used to connect XML views to its Objects
412 private void initViews() {
413 editTextEmail = (EditText) findViewById(R.id.editTextEmail);
414 editTextPassword = (EditText) findViewById(R.id.editTextPassword);
415 editTextUserName = (EditText) findViewById(R.id.editTextUserName);
416 textInputLayoutEmail = (TextInputLayout) findViewById(R.id.textInputLayoutEmail);
417 textInputLayoutPassword = (TextInputLayout) findViewById(R.id.textInputLayoutPassword);
418 textInputLayoutUserName = (TextInputLayout) findViewById(R.id.textInputLayoutUserName);
419 buttonRegister = (Button) findViewById(R.id.buttonRegister);
420
421 }
422
423 //This method is used to validate input given by user
424 public boolean validate() {
425 boolean valid = false;
426
427 //Get values from EditText fields
428 String UserName = editTextUserName.getText().toString();
429 String Email = editTextEmail.getText().toString();
430 String Password = editTextPassword.getText().toString();
431
432 //Handling validation for UserName field
433 if (UserName.isEmpty()) {
434 valid = false;
435 textInputLayoutUserName.setError("Please enter valid username!");
436 } else {
437 if (UserName.length() > 5) {
438 valid = true;
439 textInputLayoutUserName.setError(null);
440 } else {
441 valid = false;
442 textInputLayoutUserName.setError("Username is to short!");
443 }
444 }
445
446 //Handling validation for Email field
447 if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
448 valid = false;
449 textInputLayoutEmail.setError("Please enter valid email!");
450 } else {
451 valid = true;
452 textInputLayoutEmail.setError(null);
453 }
454
455 //Handling validation for Password field
456 if (Password.isEmpty()) {
457 valid = false;
458 textInputLayoutPassword.setError("Please enter valid password!");
459 } else {
460 if (Password.length() > 5) {
461 valid = true;
462 textInputLayoutPassword.setError(null);
463 } else {
464 valid = false;
465 textInputLayoutPassword.setError("Password is to short!");
466 }
467 }
468
469
470 return valid;
471 }
472}
473activity_register.xml
474Masukan koe-kode dibawah ini untuk merancang layout register.
475
476<?xml version="1.0" encoding="utf-8"?>
477<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
478 xmlns:app="http://schemas.android.com/apk/res-auto"
479 android:layout_width="match_parent"
480 android:layout_height="match_parent"
481 xmlns:tools="http://schemas.android.com/tools"
482 android:background="@color/colorPrimary"
483 android:fitsSystemWindows="true"
484 tools:context=".RegisterActivity">
485
486 <LinearLayout
487 android:layout_width="match_parent"
488 android:layout_height="wrap_content"
489 android:layout_gravity="center_vertical"
490 android:layout_marginLeft="16dp"
491 android:layout_marginRight="16dp"
492 android:orientation="vertical">
493
494 <ImageView
495 android:id="@+id/imageView"
496 android:layout_width="100dp"
497 android:layout_height="100dp"
498 android:layout_gravity="center_horizontal"
499 android:layout_margin="10dp"
500 android:src="@drawable/usericon" />
501
502 <android.support.design.widget.TextInputLayout
503 app:errorEnabled="true"
504 android:id="@+id/textInputLayoutUserName"
505 android:layout_width="match_parent"
506 android:layout_height="wrap_content"
507 android:layout_marginTop="10dp">
508
509 <android.support.design.widget.TextInputEditText
510 android:id="@+id/editTextUserName"
511 android:layout_width="match_parent"
512 android:layout_height="wrap_content"
513 android:hint="@string/username"
514 android:inputType="textPersonName" />
515 </android.support.design.widget.TextInputLayout>
516
517 <android.support.design.widget.TextInputLayout
518 android:id="@+id/textInputLayoutEmail"
519 android:layout_width="match_parent"
520 android:layout_height="wrap_content"
521 android:layout_marginTop="10dp"
522 app:errorEnabled="true">
523
524 <android.support.design.widget.TextInputEditText
525 android:id="@+id/editTextEmail"
526 android:layout_width="match_parent"
527 android:layout_height="wrap_content"
528 android:hint="@string/email"
529 android:inputType="textEmailAddress" />
530 </android.support.design.widget.TextInputLayout>
531
532 <android.support.design.widget.TextInputLayout
533 android:id="@+id/textInputLayoutPassword"
534 android:layout_width="match_parent"
535 android:layout_height="wrap_content"
536 android:layout_marginTop="8dp"
537 app:errorEnabled="true"
538 app:passwordToggleEnabled="true"
539 app:passwordToggleTint="@color/colorAccent">
540
541 <android.support.design.widget.TextInputEditText
542 android:id="@+id/editTextPassword"
543 android:layout_width="match_parent"
544 android:layout_height="wrap_content"
545 android:hint="@string/password"
546 android:inputType="textPassword" />
547 </android.support.design.widget.TextInputLayout>
548
549 <Button
550 android:id="@+id/buttonRegister"
551 android:layout_width="match_parent"
552 android:layout_height="wrap_content"
553 android:textColor="@android:color/white"
554 android:layout_gravity="center_horizontal"
555 android:layout_marginTop="10dp"
556 android:layout_weight="1"
557 android:background="@color/colorAccent"
558 android:text="@string/register" />
559
560 <TextView
561 android:id="@+id/textViewLogin"
562 android:layout_width="wrap_content"
563 android:layout_height="wrap_content"
564 android:layout_gravity="center_horizontal"
565 android:layout_marginTop="10dp"
566 android:gravity="center"
567 android:text="@string/back_to_login"
568 android:textColor="@android:color/white" />
569 </LinearLayout>
570</ScrollView>
571
572
573membuat login android dengan sqlite database
574Layout Register
575Sangat di Rekomendasikan : Modul Android Studio Keren dan Lengkap Yang Wajib Kamu Punya
576
577
5789. Class SqliteHelper
579Tambahkan class SqliteHelper. Untuk membuatnya silahkan klik folder java > klik kanan pada nama package > pilih new > class > beri nama class SqliteHelper. Masukan kode-kode berikut ini pada SqliteHelper.java (tempatkan dibawah nama package).
580
581import android.content.ContentValues;
582import android.content.Context;
583import android.database.Cursor;
584import android.database.sqlite.SQLiteDatabase;
585import android.database.sqlite.SQLiteOpenHelper;
586
587
588
589public class SqliteHelper extends SQLiteOpenHelper {
590
591 //DATABASE NAME
592 public static final String DATABASE_NAME = "loopwiki.com";
593
594 //DATABASE VERSION
595 public static final int DATABASE_VERSION = 1;
596
597 //TABLE NAME
598 public static final String TABLE_USERS = "users";
599
600 //TABLE USERS COLUMNS
601 //ID COLUMN @primaryKey
602 public static final String KEY_ID = "id";
603
604 //COLUMN user name
605 public static final String KEY_USER_NAME = "username";
606
607 //COLUMN email
608 public static final String KEY_EMAIL = "email";
609
610 //COLUMN password
611 public static final String KEY_PASSWORD = "password";
612
613 //SQL for creating users table
614 public static final String SQL_TABLE_USERS = " CREATE TABLE " + TABLE_USERS
615 + " ( "
616 + KEY_ID + " INTEGER PRIMARY KEY, "
617 + KEY_USER_NAME + " TEXT, "
618 + KEY_EMAIL + " TEXT, "
619 + KEY_PASSWORD + " TEXT"
620 + " ) ";
621
622
623 public SqliteHelper(Context context) {
624 super(context, DATABASE_NAME, null, DATABASE_VERSION);
625 }
626
627 @Override
628 public void onCreate(SQLiteDatabase sqLiteDatabase) {
629 //Create Table when oncreate gets called
630 sqLiteDatabase.execSQL(SQL_TABLE_USERS);
631
632 }
633
634 @Override
635 public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
636 //drop table to create new one if database version updated
637 sqLiteDatabase.execSQL(" DROP TABLE IF EXISTS " + TABLE_USERS);
638 }
639
640 //using this method we can add users to user table
641 public void addUser(User user) {
642
643 //get writable database
644 SQLiteDatabase db = this.getWritableDatabase();
645
646 //create content values to insert
647 ContentValues values = new ContentValues();
648
649 //Put username in @values
650 values.put(KEY_USER_NAME, user.userName);
651
652 //Put email in @values
653 values.put(KEY_EMAIL, user.email);
654
655 //Put password in @values
656 values.put(KEY_PASSWORD, user.password);
657
658 // insert row
659 long todo_id = db.insert(TABLE_USERS, null, values);
660 }
661
662 public User Authenticate(User user) {
663 SQLiteDatabase db = this.getReadableDatabase();
664 Cursor cursor = db.query(TABLE_USERS,// Selecting Table
665 new String[]{KEY_ID, KEY_USER_NAME, KEY_EMAIL, KEY_PASSWORD},//Selecting columns want to query
666 KEY_EMAIL + "=?",
667 new String[]{user.email},//Where clause
668 null, null, null);
669
670 if (cursor != null && cursor.moveToFirst()&& cursor.getCount()>0) {
671 //if cursor has value then in user database there is user associated with this given email
672 User user1 = new User(cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));
673
674 //Match both passwords check they are same or not
675 if (user.password.equalsIgnoreCase(user1.password)) {
676 return user1;
677 }
678 }