You are on page 1of 19

Sqlite

activity_main.xml
Ganti Constraint Layout ke Linear Layout
<?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=".MainActivity"
android:orientation="vertical">

Buat EditText untuk username dan password


<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="username"
android:id="@+id/etUsername"/>

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="password"
android:id="@+id/etPassword"/>

Buat Button Login


<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:id="@+id/btnLogin"
></Button>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Register"
android:id="@+id/btnRegister"
></Button>
</LinearLayout>

Setelah itu package > new > activity > empty activity >
MainActivity2.java > activity_main2.xml

activity_main2.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=".MainActivity2"
android:orientation="vertical">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="HellowWorld"
android:id="@+id/tvUsers"></TextView>
</LinearLayout>

Mulai otak atik MainActivity.java

MainActivity.java
package com.example.try_sqlite;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements


View.OnClickListener {

Declare variable username, password, button


EditText etUsername;
EditText etPassword;
Button btnLogin, btnRegister;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Dapatkan id mereka masing-masing dan assign ke variable


etUsername = findViewById(R.id.etUsername);
etPassword = findViewById(R.id.etPassword);
btnLogin = findViewById(R.id.btnLogin);

Untuk button buatlah setOnClickListener(this), lalu alt enter


untuk implement
btnLogin.setOnClickListener(this);
btnRegister = findViewById(R.id.btnRegister);
btnRegister.setOnClickListener(this);

@Override
public void onClick(View v) {

if(v.getId()==R.id.btnLogin){
Buat arraylist untuk menyimpan data user
ArrayList<User> arrUsers = new ArrayList<>();

Contoh Database dasar (bukan database), gunakan model User


// User user1 = new User();
// user1.username="qqq";
// user1.password="qqq";
// arrUsers.add(user1);
//
// User user2 = new User();
// user2.username="www";
// user2.password="www";
// arrUsers.add(user2);

UserDAO userDao = new UserDAO();


arrUsers = userDao.getUsers(this);

String username = etUsername.getText().toString();


String password = etPassword.getText().toString();

Untuk looping through arraylist


for(int i=0; i<arrUsers.size();i++){
Validasi if untuk membandingkan name dan pass pada name dan
pass di arraylist
if(username.compareToIgnoreCase(arrUsers.get(i).username)==0 &&
password.compareToIgnoreCase(arrUsers.get(i).password)==0){
Untuk pindah halaman dari 1 ke 2
Intent niatPindah = new Intent(this,MainActivity2.class);
startActivity(niatPindah);
}
}
}
else if(v.getId()==R.id.btnRegister){
Untuk mengambil text dari variable lokal yang sudah dibuat
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();

User tempUserForReg = new User();


tempUserForReg.username= username;
tempUserForReg.password= password;

Validasi UserDAO
UserDAO userDao = new UserDAO();
userDao.insertUser(this, tempUserForReg);
Toast.makeText(this, "Insert berhasil",
Toast.LENGTH_SHORT).show();
}

Buat model untuk User dengan username dan password


User.java
package com.example.try_sqlite;
public class User {

String username;
String password;

Create Database Sqlite


MySqliteHelper.java
package com.example.try_sqlite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MySqliteHelper extends SQLiteOpenHelper {

static int version =1;

Context (parameter saja), nama sqlite, null, versi


public MySqliteHelper(Context context) {
super(context, "mysqlitedb", null, version);
}

Buat Table User dengan isi username password


public static String TABLE_MS_USER = "msUser";
public static String FIELD_MS_USER_USERNAME = "username";
public static String FIELD_MS_USER_PASSWORD = "password";

Semua table akan dibuat pada onCreate ini


@Override
public void onCreate(SQLiteDatabase db) {
Siapkan variable string untuk query
// String qCreate="CREATE TABLE IF NOT EXISTS 'msUser'
('username' TEXT,'password' TEXT)";
String qCreate="CREATE TABLE IF NOT EXISTS
'"+TABLE_MS_USER+"' ('"
+ FIELD_MS_USER_USERNAME +"' TEXT, '"
+FIELD_MS_USER_PASSWORD+"' TEXT)";
Untuk eksekusi sql
db.execSQL(qCreate);

Untuk insert data ke sqlite


String qInsert="INSERT INTO 'msUser' ('username', 'password')
VALUES ('qqq', 'qqq');";
db.execSQL(qInsert);

String qInsert2="INSERT INTO 'msUser' ('username', 'password')


VALUES ('www', 'www');";
db.execSQL(qInsert2);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {

}
}

Data Access Object


UserDAO.java
package com.example.try_sqlite;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import java.util.ArrayList;

public class UserDAO {


//dao = data access object

public ArrayList<User> getUsers(Context mCtx){


ArrayList<User> results = new ArrayList<>();

MySqliteHelper helper = new MySqliteHelper(mCtx);


SQLiteDatabase db = helper.getReadableDatabase();

String selectionString = null;


String[] selectionArgs = null;

Untuk select bintang, kek pointer


Cursor resultCursor = db.query(
helper.TABLE_MS_USER, null,
selectionString, selectionArgs,
null, null, null);
Looping selama data yang di cursor belum habis
while(resultCursor.moveToNext()){
User tempUser = new User();
tempUser.username = resultCursor.getString(0);
tempUser.password = resultCursor.getString(1);
results.add(tempUser);
}

return results;
}

Fungsi Insert
public void insertUser(Context mCtx, User user){
Log.v("insertUser","1");
MySqliteHelper helper = new MySqliteHelper(mCtx);
Log.v("insertUser","2");
SQLiteDatabase db = helper.getWritableDatabase();
Log.v("insertUser","3");
ContentValues cv = new ContentValues();
Log.v("insertUser","4");
cv.put(helper.FIELD_MS_USER_USERNAME, user.username);
Log.v("insertUser","5");
cv.put(helper.FIELD_MS_USER_PASSWORD, user.password);
Log.v("insertUser","6");
db.insertWithOnConflict(helper.TABLE_MS_USER, null,
cv, SQLiteDatabase.CONFLICT_REPLACE);
Log.v("insertUser","7");
db.close();
Log.v("insertUser","8");
}
}

MainActivity2.java
package com.example.try_sqlite;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

import java.util.ArrayList;

public class MainActivity2 extends AppCompatActivity {

TextView tvusers;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);

tvusers = findViewById(R.id.tvUsers);

UserDAO userDAO = new UserDAO();


ArrayList<User> users = userDAO.getUsers(this);

String results="";
for (int i =0;i<users.size();i++){
results = results+" "+users.get(i).username+" "+
users.get(i).password +" ||\n";
}
tvusers.setText(results);
}
}

Fragment
Note :
*Activity tidak bisa berada dalam satu activity lain
*Jadi saat kita menggunakan fragment, saat kita klik pada Tab Home,
maka Fragment dibawahnya akan berubah menjadi Fragment home, saat
kita klik Tab Product maka Fragment dibawahnya akan berubah menjadi
Fragment produk

Java
Main Activity
package com.example.tryfragmentbasic2023;

import android.net.Uri;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity implements
UpperFragment.OnFragmentInteractionListener{

UpperFragment upperFragment;
LowerFragment lowerFragment;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Check that the activity is using the layout version with


// the fragment_container FrameLayout
if (findViewById(R.id.upperContainer) != null) {

// However, if we're being restored from a previous state,


// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
if (savedInstanceState != null) {
return;
}

// Create a new Fragment to be placed in the activity layout


upperFragment = new UpperFragment();

// In case this activity was started with special instructions from


an
// Intent, pass the Intent's extras to the fragment as arguments
upperFragment.setArguments(getIntent().getExtras());

// Add the fragment to the 'fragment_container' FrameLayout

getSupportFragmentManager().beginTransaction().add(R.id.upperContain
er, upperFragment).commit();
}

if (findViewById(R.id.lowerContainer) != null) {
if (savedInstanceState != null) {return;}
lowerFragment = new LowerFragment();
lowerFragment.setArguments(getIntent().getExtras());

getSupportFragmentManager().beginTransaction().add(R.id.lowerContain
er, lowerFragment).commit();
}
}

@Override
public void onFragmentInteraction(String sentence) {
if(lowerFragment!=null)
lowerFragment.updateSentence(sentence);
}

Upper Fragment
package com.example.tryfragmentbasic2023;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import androidx.fragment.app.Fragment;

/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link UpperFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
*/
public class UpperFragment extends Fragment{

private OnFragmentInteractionListener mListener;

Button btnPotato, btnTomato;

// Required empty public constructor


public UpperFragment() {}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_upper, container,
false);
btnPotato = (Button) rootView.findViewById(R.id.buttonPotato);
btnPotato.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onPotato();
}
});
btnTomato = (Button) rootView.findViewById(R.id.buttonTomato);
btnTomato.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onTomato();
}
});
return rootView;
}

public void onPotato() {


if (mListener != null) {
mListener.onFragmentInteraction("This is potato");
}
}

public void onTomato() {


if (mListener != null) {
mListener.onFragmentInteraction("This is tomato");
}
}

@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}

@Override
public void onDetach() {
super.onDetach();
mListener = null;
}

/**This interface must be implemented by activities that contain this


* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.*/
public interface OnFragmentInteractionListener {
void onFragmentInteraction(String sentence);
}
}

Lower Fragment
package com.example.tryfragmentbasic2023;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.textservice.SentenceSuggestionsInfo;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

public class LowerFragment extends Fragment {

// Required empty public constructor


public LowerFragment() {}

TextView tvLowerFragment;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_lower, container,
false);
tvLowerFragment = (TextView)
rootView.findViewById(R.id.tvLowerFragment);
return rootView;
}

public void updateSentence(String newSentence){


tvLowerFragment.setText(newSentence);
}
}

Main Activity xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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:orientation="vertical"
tools:context="com.example.tryfragmentbasic2023.MainActivity">

<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:id="@+id/upperContainer"/>

<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:id="@+id/lowerContainer"/>

</LinearLayout>
UpperFragment xml
<FrameLayout
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"
tools:context="com.example.tryfragmentbasic2023.UpperFragment">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose Potato"
android:id="@+id/buttonPotato"
android:layout_gravity="center" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose Tomato"
android:id="@+id/buttonTomato"
android:layout_gravity="center" />
</LinearLayout>

</FrameLayout>

LowerFragment xml
<FrameLayout
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"
tools:context="com.example.tryfragmentbasic2023.LowerFragment">

<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/black"
android:id="@+id/tvLowerFragment"
android:textColor="@color/white"
android:text="You have choose a potato!"/>

</FrameLayout>

You might also like