0% found this document useful (0 votes)
20 views

SQL Lite Create, Delete

The document describes an Android application that allows users to add, edit, and delete words from a SQLite database using a RecyclerView. It includes code for the AndroidManifest, MainActivity, EditWordActivity, WordListAdapter, and WordListOpenHelper classes.

Uploaded by

ekosup442
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

SQL Lite Create, Delete

The document describes an Android application that allows users to add, edit, and delete words from a SQLite database using a RecyclerView. It includes code for the AndroidManifest, MainActivity, EditWordActivity, WordListAdapter, and WordListOpenHelper classes.

Uploaded by

ekosup442
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

NIM : A11.2018.

11600

Nama : SAFIELLA AULIA WIDYA KUSUMA

WordListSQLIneractive

Hasil Program :

Code Program :
AndroidManifest.java
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/r
es/android"
package="com.example.wordlistsqlineractive">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/
Theme.WordListSQLIneractive">
<activity
android:name=".EditWordActivity" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

MainActivity.java
package com.example.wordlistsqlineractive;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import
com.google.android.material.floatingactionbutton.FloatingActionButton
;

public class MainActivity extends AppCompatActivity {


private static final String TAG =
MainActivity.class.getSimpleName();

public static final int WORD_EDIT = 1;


public static final int WORD_ADD = -1;

private WordListOpenHelper mDB;


private RecyclerView mRecyclerView;
private WordListAdapter mAdapter;
private int mLastPosition;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDB = new WordListOpenHelper(this);

// Create recycler view.


mRecyclerView = (RecyclerView)
findViewById(R.id.recyclerview); // Create an mAdapter
and supply the data to be displayed. mAdapter = new
WordListAdapter(this, /* mDB.getAllEntries(),*/ mDB);
// Connect the mAdapter with the recycler view.
mRecyclerView.setAdapter(mAdapter);
// Give the recycler view a default layout manager.
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
// Add a floating action click handler for creating new
entries. FloatingActionButton fab = (FloatingActionButton)
findViewById(R.id.fab); fab.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View view) {
// Starts empty edit activity.
Intent intent = new
Intent(getBaseContext(),
EditWordActivity.class);
startActivityForResult(intent, WORD_EDIT);
}
});
}
public void onActivityResult(int requestCode, int
resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (requestCode == WORD_EDIT) {
if (resultCode == RESULT_OK) {
String word = data.getStringExtra(EditWordActivity.EXTRA_REPLY);

// Update the database.


if (!TextUtils.isEmpty(word)) {
int id = data.getIntExtra(WordListAdapter.EXTRA_ID, -99);

if (id == WORD_ADD) {
mDB.insert(word);
} else if (id >= 0) {
mDB.update(id, word);
}
// Update the UI.
mAdapter.notifyDataSetChanged();
} else {
Toast.makeText(
getApplicationContext(),
R.string.empty_not_saved,
Toast.LENGTH_LONG).show();
}
}
}
}
}

EditWordActivity.java
package com.example.wordlistsqlineractive;

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

import androidx.appcompat.app.AppCompatActivity;

public class EditWordActivity extends AppCompatActivity {

private static final String TAG =


EditWordActivity.class.getSimpleName();
private static final int NO_ID = -99;
private static final String NO_WORD = "";

// Unique tag for the intent reply.


public static final String EXTRA_REPLY =
"com.example.android.wordlistsql.REPLY";

int mId = MainActivity.WORD_ADD;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_word);

EditText mEditWordView = (EditText)


findViewById(R.id.edit_word);
// Get data sent from calling activity.
Bundle extras = getIntent().getExtras();

// If we are passed content, fill it in for the


user to edit. if (extras != null) {
int id = extras.getInt(WordListAdapter.EXTRA_ID, NO_ID);
String word = extras.getString(WordListAdapter.EXTRA_WORD,
NO_WORD); if ((id != NO_ID) && (word != NO_WORD)) {
mId = id;
mEditWordView.setText(word);
}
} // Otherwise, start with empty fields.
}

public void returnReply(View view) {


String word = ((EditText)
findViewById(R.id.edit_word)).getText().toString();

Intent replyIntent = new Intent();


replyIntent.putExtra(EXTRA_REPLY, word);
replyIntent.putExtra(WordListAdapter.EXTRA_ID, mId);
setResult(RESULT_OK, replyIntent);
finish();
}
}

WordListAdapter.java
package com.example.wordlistsqlineractive;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

public class WordListAdapter extends


RecyclerView.Adapter<WordListAdapter.WordViewHolder> {
/**
* Custom view holder with a text view and two buttons.
*/
class WordViewHolder extends RecyclerView.ViewHolder {
public final TextView wordItemView;
Button delete_button;
Button edit_button;

public WordViewHolder(View itemView) {


super(itemView);
wordItemView = (TextView)
itemView.findViewById(R.id.word); delete_button =
(Button)itemView.findViewById(R.id.delete_button);
edit_button =
(Button)itemView.findViewById(R.id.edit_button);
}
}

private static final String TAG =


WordListAdapter.class.getSimpleName();

public static final String EXTRA_ID = "ID";


public static final String EXTRA_WORD = "WORD";
public static final String EXTRA_POSITION = "POSITION";

private final LayoutInflater mInflater;


WordListOpenHelper mDB;
Context mContext;

public WordListAdapter(Context context,


WordListOpenHelper db) { mInflater =
LayoutInflater.from(context);
mContext = context;
mDB = db;
}

@Override
public WordViewHolder onCreateViewHolder(ViewGroup
parent, int viewType) { View itemView =
mInflater.inflate(R.layout.activity_word_item, parent,
false);
return new WordViewHolder(itemView);
}

@Override
public void onBindViewHolder(WordViewHolder
holder, int position) { WordItem current =
mDB.query(position);
holder.wordItemView.setText(current.getWord());
// Keep a reference to the view holder for the click
listener final WordViewHolder h = holder; // needs to be
final for use in callback // Attach a click listener to the
DELETE button.
holder.delete_button.setOnClickListener(new
MyButtonOnClickListener( current.getId(), null) {

@Override
public void onClick(View v ) {
// You have to get the position like this, you can't
hold a reference

Log.d (TAG + "onClick", "VHPos " + h.getAdapterPosition() + "


ID " + id);
int deleted = mDB.delete(id);
if (deleted >= 0)
notifyItemRemoved(h.getAdapterPosition());
}
});

// Attach a click listener to the EDIT button.


holder.edit_button.setOnClickListener(new
MyButtonOnClickListener( current.getId(),
current.getWord()) {

@Override
public void onClick(View v) {
Intent intent = new Intent(mContext,
EditWordActivity.class); intent.putExtra(EXTRA_ID,
id);
intent.putExtra(EXTRA_POSITION, h.getAdapterPosition());
intent.putExtra(EXTRA_WORD, word);

// Start an empty edit activity.


((Activity)
mContext).startActivityForResult(intent,
MainActivity.WORD_EDIT);
}
});
}

@Override
public int getItemCount() {
return (int) mDB.count();
}
}

WordListOpenHelper.java
package com.example.wordlistsqlineractive;

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

public class WordListOpenHelper extends SQLiteOpenHelper {

private static final String TAG =


WordListOpenHelper.class.getSimpleName();

// Declaring all these as constants makes code a lot


more readable, and looking like SQL.

// Versions has to be 1 first time or app will crash.


private static final int DATABASE_VERSION = 1;
private static final String WORD_LIST_TABLE
= "word_entries"; private static final
String DATABASE_NAME = "wordlist";

// Column names...
public static final String KEY_ID = "_id";
public static final String KEY_WORD = "word";

// ... and a string array of columns.


private static final String[] COLUMNS =
{KEY_ID, KEY_WORD};

// Build the SQL query that creates the table.


private static final String WORD_LIST_TABLE_CREATE =
"CREATE TABLE " + WORD_LIST_TABLE + " (" +
KEY_ID + " INTEGER PRIMARY KEY, " + // will auto-increment
if no value passed
KEY_WORD + " TEXT );";

private SQLiteDatabase mWritableDB;


private SQLiteDatabase mReadableDB;

public WordListOpenHelper(Context context) {


super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.d(TAG, "Construct WordListOpenHelper");
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(WORD_LIST_TABLE_CREATE);
fillDatabaseWithData(db);
// We cannot initialize mWritableDB and mReadableDB here,
because this creates an infinite
// loop of on Create being repeatedly called.
}

public void fillDatabaseWithData(SQLiteDatabase db) {

String[] words = {"Android", "Adapter", "ListView",


"AsyncTask", "Android Studio",
"SQLiteDatabase", "SQLOpenHelper", "Data model",
"ViewHolder", "Android Performance",
"OnClickListener"};

// Create a container for the data.


ContentValues values = new ContentValues();

for (int i=0; i < words.length;i++) {


// Put column/value pairs into the container. put()
overwrites existing values.
values.put(KEY_WORD, words[i]);
db.insert(WORD_LIST_TABLE, null, values);
}
}

public WordItem query(int position) {


String query = "SELECT * FROM " + WORD_LIST_TABLE +
" ORDER BY " + KEY_WORD + " ASC " +
"LIMIT " + position + ",1";
Cursor cursor = null;
WordItem entry = new WordItem();

try {
if (mReadableDB == null) {mReadableDB =
getReadableDatabase();} cursor =
mReadableDB.rawQuery(query, null);
cursor.moveToFirst();
entry.setId(cursor.getInt(cursor.getColumnIndex(KEY_ID)
));
entry.setWord(cursor.getString(cursor.getColumnIndex(KEY
_WORD))); } catch (Exception e) {
Log.d(TAG, "QUERY EXCEPTION! " + e.getMessage());
} finally {
// Must close cursor and db now that we are
done with it. cursor.close();
return entry;
}
}

public long count() {


if (mReadableDB == null) {mReadableDB =
getReadableDatabase();} return
DatabaseUtils.queryNumEntries(mReadableDB,
WORD_LIST_TABLE); }

public long insert(String word) {


long newId = 0;
ContentValues values = new ContentValues();
values.put(KEY_WORD, word);
try {
if (mWritableDB == null) {mWritableDB =
getWritableDatabase();} newId =
mWritableDB.insert(WORD_LIST_TABLE, null, values); }
catch (Exception e) {
Log.d(TAG, "INSERT EXCEPTION! " +
e.getMessage()); }
return newId;
}

public int update(int id, String word) {


int mNumberOfRowsUpdated = -1;
try {
if (mWritableDB == null) {mWritableDB =
getWritableDatabase();} ContentValues values = new
ContentValues();
values.put(KEY_WORD, word);

mNumberOfRowsUpdated = mWritableDB.update(WORD_LIST_TABLE,
//table to change
values, // new values to insert
KEY_ID + " = ?", // selection criteria
for row (in this case, the _id column)
new String[]{String.valueOf(id)}); //selection args;
the actual value of the id

} catch (Exception e) {
Log.d (TAG, "UPDATE EXCEPTION! " +
e.getMessage()); }
return mNumberOfRowsUpdated;
}

public int delete(int id) {


int deleted = 0;
try {
if (mWritableDB == null) {mWritableDB =
getWritableDatabase();} deleted =
mWritableDB.delete(WORD_LIST_TABLE, //table name
KEY_ID + " = ? ", new String[]{String.valueOf(id)});
} catch (Exception e) {
Log.d (TAG, "DELETE EXCEPTION! " +
e.getMessage()); } return deleted;
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) {
Log.w(WordListOpenHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to
" + newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + WORD_LIST_TABLE);
onCreate(db);
}
}

WordItem.java
package com.example.wordlistsqlineractive;

public class WordItem {


private int mId;
private String mWord;

public WordItem() {}

public int getId() {


return this.mId;
}

public String getWord() {


return this.mWord;
}

public void setId(int id) {


this.mId = id;
}

public void setWord(String word) {


this.mWord = word;
}
}

MyButtonOnClickListener.java
package com.example.wordlistsqlineractive;

import android.view.View;

/**
* Instantiated for the Edit and Delete
buttons in WordListAdapter. */
public class MyButtonOnClickListener implements
View.OnClickListener { private static final String TAG =
View.OnClickListener.class.getSimpleName();

int id;
String word;

public MyButtonOnClickListener(int id, String word) {


this.id = id;
this.word = word;
}

public void onClick(View v) {


// Implemented in WordListAdapter
}
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://
schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.recyclerview.widget.RecyclerView>

<com.google.android.material.floatingactionbutton.Fl
oatingActionButton android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
android:clickable="true"
android:src="@drawable/ic_add_24dp"
android:focusable="true"
android:contentDescription="@string/todo" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

activity_edit_word.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/a
ndroid" android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<EditText
android:id="@+id/edit_word"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-light"
android:hint="@string/hint_word"
android:inputType="textAutoComplete"
android:padding="@dimen/small_padding"
android:layout_marginBottom="@dime
n/big_padding"
android:layout_marginTop="@dimen/bi
g_padding"
android:textSize="18sp" />

<Button
android:id="@+id/button_save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/teal_700"
android:onClick="returnReply"
android:text="@string/button_save"
android:textColor="@color/white" />

</LinearLayout>

activity_word_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/a
ndroid" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dp">

<TextView
android:id="@+id/word"
android:layout_width="match_parent"
style="@style/word_title" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<Button
android:id="@+id/delete_button"
android:layout_width="match_parent"
android:layout_height="@dimen/button_height"
android:layout_weight="2"
android:background="@color/teal_700"
android:text="@string/button_delete"
android:textColor="@color/white" />

<Button
android:id="@+id/edit_button"
android:layout_width="match_parent"
android:layout_height="@dimen/button_height"
android:layout_weight="1"
android:background="@color/teal_700"
android:text="@string/button_edit"
android:textColor="@color/white"/>

</LinearLayout>
<Button
android:layout_width="match_parent"
android:layout_height="@dimen/divider_height"
android:background="@color/teal_700" />

</LinearLayout>

WordListSQLIneractiveWithSearch

Hasil Program :

Code Program :
AndroidManifest.java
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/r
es/android"
package="com.example.wordlistsqlinteractivewith
search">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/
Theme.WordListSQLInteractiveWithSearch">
<activity android:name=".SearchActivity" />
<activity android:name=".EditWordActivity"/>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

MainActivity.java
package com.example.wordlistsqlinteractivewithsearch;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import
com.google.android.material.floatingactionbutton.Floatin
gActionButton; public class MainActivity extends
AppCompatActivity {
private static final String TAG =
MainActivity.class.getSimpleName();

public static final int WORD_EDIT = 1;


public static final int WORD_ADD = -1;

private WordListOpenHelper mDB;


private RecyclerView mRecyclerView;
private WordListAdapter mAdapter;

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

mDB = new WordListOpenHelper(this);

// Create recycler view.


mRecyclerView = (RecyclerView)
findViewById(R.id.recyclerview); // Create an mAdapter
and supply the data to be displayed. mAdapter = new
WordListAdapter(this, /* mDB.getAllEntries(),*/ mDB);
// Connect the mAdapter with the recycler view.
mRecyclerView.setAdapter(mAdapter);
// Give the recycler view a default layout manager.
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

// Add a floating action click handler for creating new


entries. FloatingActionButton fab = (FloatingActionButton)
findViewById(R.id.fab); fab.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View view) {
// Starts empty edit activity.
Intent intent = new Intent(getBaseContext(),
EditWordActivity.class);
startActivityForResult(intent, WORD_EDIT);
}
});
}

/**
* Inflates the menu, and adds items to the action bar
if it is present. *
* @param menu Menu to inflate.
* @return Returns true if the menu inflated.
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_search:
// Starts search activity.
Intent intent = new
Intent(getBaseContext(),com.example.wordlistsqlinteractivewit
hsearch.SearchActivit y.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}

public void onActivityResult(int requestCode, int


resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (requestCode == WORD_EDIT) {
if (resultCode == RESULT_OK) {
String word = data.getStringExtra(EditWordActivity.EXTRA_REPLY);

// Update the database.


if (!TextUtils.isEmpty(word)) {
int id = data.getIntExtra(WordListAdapter.EXTRA_ID, -99);

if (id == WORD_ADD) {
mDB.insert(word);
} else if (id >= 0) {
mDB.update(id, word);
}
// Update the UI.
mAdapter.notifyDataSetChanged();
} else {
Toast.makeText(
getApplicationContext(),
R.string.empty_word_not_saved,
Toast.LENGTH_LONG).show();
}
}
}
}
}

EditWordActivity.java
package com.example.wordlistsqlinteractivewithsearch;

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

import androidx.appcompat.app.AppCompatActivity;

public class EditWordActivity extends AppCompatActivity {

private static final String TAG =


com.example.wordlistsqlinteractivewithsearch.EditWordActivity
.class.getSimpleName( );

private static final int NO_ID = -99;


private static final String NO_WORD = "";

// Unique tag for the intent reply.


public static final String EXTRA_REPLY =
"com.example.android.wordlistsql.REPLY";

int mId = MainActivity.WORD_ADD;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_word);

EditText mEditWordView = (EditText)


findViewById(R.id.edit_word);
// Get data sent from calling activity.
Bundle extras = getIntent().getExtras();

// If we are passed content, fill it in for the


user to edit. if (extras != null) {
int id = extras.getInt(WordListAdapter.EXTRA_ID, NO_ID);
String word = extras.getString(WordListAdapter.EXTRA_WORD,
NO_WORD); if ((id != NO_ID) && (word != NO_WORD)) {
mId = id;
mEditWordView.setText(word);
}
} // Otherwise, start with empty fields.
}

public void returnReply(View view) {


String word = ((EditText)
findViewById(R.id.edit_word)).getText().toString();

Intent replyIntent = new Intent();


replyIntent.putExtra(EXTRA_REPLY, word);
replyIntent.putExtra(WordListAdapter.EXTRA_ID, mId);
setResult(RESULT_OK, replyIntent);
finish();
}
}

WordListAdapter.java
package com.example.wordlistsqlinteractivewithsearch;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

public class WordListAdapter extends


RecyclerView.Adapter<WordListAdapter.WordViewHolder> {

/**
* Custom view holder with a text view and two buttons.
*/
class WordViewHolder extends RecyclerView.ViewHolder {
public final TextView wordItemView;
Button delete_button;
Button edit_button;

public WordViewHolder(View itemView) {


super(itemView);
wordItemView = (TextView)
itemView.findViewById(R.id.word); delete_button =
(Button)itemView.findViewById(R.id.delete_button);
edit_button =
(Button)itemView.findViewById(R.id.edit_button); }
}

private static final String TAG =


com.example.wordlistsqlinteractivewithsearch.WordListAdapter.
class.getSimpleName() ;

public static final String EXTRA_ID = "ID";


public static final String EXTRA_WORD = "WORD";
public static final String EXTRA_POSITION = "POSITION";
private final LayoutInflater mInflater;
WordListOpenHelper mDB;
Context mContext;

public WordListAdapter(Context context,


WordListOpenHelper db) { mInflater =
LayoutInflater.from(context);
mContext = context;
mDB = db;
}

@Override
public WordViewHolder onCreateViewHolder(ViewGroup
parent, int viewType) { View itemView =
mInflater.inflate(R.layout.activity_word_item, parent,
false);
return new WordViewHolder(itemView);
}

@Override
public void onBindViewHolder(WordViewHolder
holder, int position) { WordItem current =
mDB.query(position);
holder.wordItemView.setText(current.getWord());
// Keep a reference to the view holder for the click
listener final WordViewHolder h = holder; // needs to be
final for use in callback // Attach a click listener to the
DELETE button.
holder.delete_button.setOnClickListener(new
MyButtonOnClickListener( current.getId(), null) {

@Override
public void onClick(View v ) {
// You have to get the position like this, you can't
hold a reference

Log.d (TAG + "onClick", "VHPos " + h.getAdapterPosition() + "


ID " + id);
int deleted = mDB.delete(id);
if (deleted >= 0)
notifyItemRemoved(h.getAdapterPosition());
}
});

// Attach a click listener to the EDIT button.


holder.edit_button.setOnClickListener(new
MyButtonOnClickListener( current.getId(),
current.getWord()) {

@Override
public void onClick(View v) {
Intent intent = new Intent(mContext,
EditWordActivity.class); intent.putExtra(EXTRA_ID, id);
intent.putExtra(EXTRA_POSITION,
h.getAdapterPosition());
intent.putExtra(EXTRA_WORD, word);

// Start an empty edit activity.


((Activity)
mContext).startActivityForResult(intent,
MainActivity.WORD_EDIT);
}
});
}

@Override
public int getItemCount() {
return (int) mDB.count();
}
}

WordListOpenHelper.java
package com.example.wordlistsqlinteractivewithsearch;

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

public class WordListOpenHelper extends SQLiteOpenHelper {

private static final String TAG =


WordListOpenHelper.class.getSimpleName();

// Declaring all these as constants makes code a lot more


readable and looking like SQL.

// Version has to be 1 first time or app will crash.


private static final int DATABASE_VERSION = 1;
private static final String WORD_LIST_TABLE
= "word_entries"; private static final
String DATABASE_NAME = "wordlist";

// Column names...
public static final String KEY_ID = "_id";
public static final String KEY_WORD = "word";

// ... and a string array of columns.


private static final String[] COLUMNS =
{KEY_ID, KEY_WORD};

// Build the SQL query that creates the table.


private static final String WORD_LIST_TABLE_CREATE =
"CREATE TABLE " + WORD_LIST_TABLE + " (" +
KEY_ID + " INTEGER PRIMARY KEY, " + // will auto-increment
if no value passed
KEY_WORD + " TEXT );";

private SQLiteDatabase mWritableDB;


private SQLiteDatabase mReadableDB;
public WordListOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.d(TAG, "Construct WordListOpenHelper");
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(WORD_LIST_TABLE_CREATE);
fillDatabaseWithData(db);
}

public void fillDatabaseWithData(SQLiteDatabase db) {

String[] words = {"Android", "Adapter", "ListView",


"AsyncTask", "Android Studio",
"SQLiteDatabase", "SQLOpenHelper", "Data model",
"ViewHolder", "Android Performance",
"OnClickListener"};

// Create a container for the data.


ContentValues values = new ContentValues();

for (int i=0; i < words.length; i++) {


// Put column/value pairs for current row into the
container. values.put(KEY_WORD, words[i]); // put()
overrides existing values. // Insert the row.
db.insert(WORD_LIST_TABLE, null, values);
}
}

public Cursor search(String searchString) {


String[] columns = new String[]{KEY_WORD};
String where = KEY_WORD + " LIKE ?";
searchString = "%" + searchString + "%";
String[] whereArgs = new String[]{searchString};

Cursor cursor = null;


try {
if (mReadableDB == null) {
mReadableDB = getReadableDatabase();
}
cursor = mReadableDB.query(WORD_LIST_TABLE, columns, where,
whereArgs, null, null, null);
} catch (Exception e) {
Log.d(TAG, "SEARCH EXCEPTION! " + e); // Just log the
exception }
return cursor;
}

public WordItem query(int position) {


String query = "SELECT * FROM " + WORD_LIST_TABLE +
" ORDER BY " + KEY_WORD + " ASC " +
"LIMIT " + position + ",1";

Cursor cursor = null;


WordItem entry = new WordItem();

try {
if (mReadableDB == null) {
mReadableDB = getReadableDatabase();
}
cursor = mReadableDB.rawQuery(query, null);
cursor.moveToFirst();
entry.setId(cursor.getInt(cursor.getColumnIndex(KEY_ID)
));
entry.setWord(cursor.getString(cursor.getColumnIndex(KEY
_WORD))); } catch (Exception e) {
Log.d(TAG, "QUERY EXCEPTION! " + e); // Just log the
exception } finally {
// Must close cursor and db now that we are
done with it. cursor.close();
return entry;
}
}

public long count() {


if (mReadableDB == null) {
mReadableDB = getReadableDatabase();
}
return DatabaseUtils.queryNumEntries(mReadableDB,
WORD_LIST_TABLE); }

public long insert(String word) {


long newId = 0;
ContentValues values = new ContentValues();
values.put(KEY_WORD, word);
try {
if (mWritableDB == null) {
mWritableDB = getWritableDatabase();
}
newId = mWritableDB.insert(WORD_LIST_TABLE,
null, values); } catch (Exception e) {
Log.d(TAG, "INSERT EXCEPTION! " + e);
}
return newId;
}

public int update(int id, String word) {


int mNumberOfRowsUpdated = -1;
try {
if (mWritableDB == null) {
mWritableDB = getWritableDatabase();
}
ContentValues values = new ContentValues();
values.put(KEY_WORD, word);

mNumberOfRowsUpdated = mWritableDB.update(WORD_LIST_TABLE,
//table to change
values, // new values to insert
KEY_ID + " = ?", // selection criteria
for row (in this case, the _id column)
new String[]{String.valueOf(id)}); //selection args;
the actual value of the id

} catch (Exception e) {
Log.d (TAG, "UPDATE EXCEPTION! " + e);
}
return mNumberOfRowsUpdated;
}
/**
* Deletes one entry identified by its id.
*
* @param id ID of the entry to delete.
* @return The number of rows deleted. Since we are
deleting by id, this should be 0 or 1.
*/
public int delete(int id) {
int deleted = 0;
try {
if (mWritableDB == null) {
mWritableDB = getWritableDatabase();
}
deleted = mWritableDB.delete(WORD_LIST_TABLE,
//table name KEY_ID + " =? ", new String[]
{String.valueOf(id)}); } catch (Exception e) {
Log.d (TAG, "DELETE EXCEPTION! " +
e); } return deleted;
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) {
Log.w(WordListOpenHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to
" + newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + WORD_LIST_TABLE);
onCreate(db);
}
}

WordItem.java
package com.example.wordlistsqlinteractivewithsearch;

public class WordItem {

private int mId;


private String mWord;

public WordItem() {}

public int getId() {


return this.mId;
}

public String getWord() {


return this.mWord;
}

public void setId(int id) {


this.mId = id;
}

public void setWord(String word) {


this.mWord = word;
}
}

MyButtonOnClickListener.java
package com.example.wordlistsqlinteractivewithsearch;
import android.view.View;

/**
* Instantiated for the Edit and Delete
buttons in WordListAdapter. */
public class MyButtonOnClickListener implements
View.OnClickListener { private static final String TAG =
View.OnClickListener.class.getSimpleName();

int id;
String word;

public MyButtonOnClickListener(int id, String word) {


this.id = id;
this.word = word;
}

public void onClick(View v) {


// Implemented in WordListAdapter
}
}

SearchActivity.java
package com.example.wordlistsqlinteractivewithsearch;

import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class SearchActivity extends AppCompatActivity {

private static final String TAG =


EditWordActivity.class.getSimpleName(); private
WordListOpenHelper mDB;
private EditText mEditWordView;
private TextView mTextView;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);

mDB = new WordListOpenHelper(this);

mEditWordView = ((EditText)
findViewById(R.id.search_word)); mTextView =
((TextView) findViewById(R.id.search_result));
}

// Click handler for Search button.


public void showResult(View view) {
String word = mEditWordView.getText().toString();
mTextView.setText("Result for " + word + ":\n\n");
// Search for the word in the database.
Cursor cursor = mDB.search(word);
// You must move the cursor to the first item.
cursor.moveToFirst();
// Only process a non-null cursor with rows.
if (cursor != null & cursor.getCount() > 0) {
int index;
String result;
// Iterate over the cursor, while there
are entries. do {
// Don't guess at the column index. Get the index for the
named column.
index =
cursor.getColumnIndex(WordListOpenHelper.KEY_WORD);
// Get the value from the column for the current
cursor. result = cursor.getString(index);
// Add result to what's already in the text
view. mTextView.append(result + "\n");
} while (cursor.moveToNext());
cursor.close();
} else {
mTextView.append(getString(R.string.no
_result)); }
}
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://
schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.recyclerview.widget.RecyclerView>

<com.google.android.material.floatingactionbutton.Fl
oatingActionButton android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
android:clickable="true"
android:src="@drawable/ic_add_24dp"
android:focusable="true"
android:contentDescription="@string/todo" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

activity_edit_word.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/a
ndroid" android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<EditText
android:id="@+id/edit_word"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-light"
android:hint="@string/hint_word"
android:inputType="textAutoComplete"
android:padding="@dimen/small_padding"
android:layout_marginBottom="@dime
n/big_padding"
android:layout_marginTop="@dimen/bi
g_padding"
android:textSize="18sp" />

<Button
android:id="@+id/button_save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/teal_700"
android:onClick="returnReply"
android:text="@string/button_save"
android:textColor="@color/white" />

</LinearLayout>

activity_word_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/a
ndroid" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dp">

<TextView
android:id="@+id/word"
android:layout_width="match_parent"
style="@style/word_title" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<Button
android:id="@+id/delete_button"
android:layout_width="match_parent"
android:layout_height="@dimen/
button_height"
android:layout_weight="2"
android:background="@color/teal_700"
android:text="@string/button_delete"
android:textColor="@color/white" />

<Button
android:id="@+id/edit_button"
android:layout_width="match_parent"
android:layout_height="@dimen/
button_height"
android:layout_weight="1"
android:background="@color/teal_700"
android:text="@string/button_edit"
android:textColor="@color/white"/>

</LinearLayout>
<Button
android:layout_width="match_parent"
android:layout_height="@dimen/divider_height"
android:background="@color/teal_700" />

</LinearLayout>

activity_search.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/a
ndroid" android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<EditText
android:id="@+id/search_word"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-light"
android:hint="@string/hint_word"
android:inputType="textAutoComplete"
android:padding="@dimen/small_padding"
android:layout_marginBottom="@dime
n/big_padding"
android:layout_marginTop="@dimen/bi
g_padding"
android:textSize="18sp" />

<Button
android:id="@+id/button_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/teal_700"
android:onClick="showResult"
android:text="@string/button_search"
android:textColor="@color/white" />

<TextView
android:id="@+id/search_result"
android:layout_width="match_parent"
android:layout_height="300dp"
android:textSize="18sp"
android:hint="@string/search_results"/>

</LinearLayout>

Hasil Program :
Code Program :

Hasil Program :

Code Program :

You might also like