0% found this document useful (0 votes)
21 views5 pages

Practical NO - 26

This document outlines the implementation of an Android application that performs asynchronous tasks using SQLite. It includes XML layout files for the user interface, Java code for the main activity handling data insertion, retrieval, and database reset operations, as well as a custom adapter for displaying data in a list view. The application utilizes AsyncTask for background processing to ensure smooth user experience while interacting with the database.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views5 pages

Practical NO - 26

This document outlines the implementation of an Android application that performs asynchronous tasks using SQLite. It includes XML layout files for the user interface, Java code for the main activity handling data insertion, retrieval, and database reset operations, as well as a custom adapter for displaying data in a list view. The application utilizes AsyncTask for background processing to ensure smooth user experience while interacting with the database.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Practical NO.26 : Perform Async Task using SQLite.

• activity_main.xml

<RelativeLayout android:layout_height="wrap_content"

xmlns:android="http://schemas.android.com/ android:layout_below="@id/button_add"
apk/res/android" android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
xmlns:tools="http://schemas.android.com/to android:text="Show Data"/>
ols" <Button
android:layout_width="match_parent" android:id="@+id/button_reset_db"
android:layout_height="match_parent" android:layout_width="wrap_content"
tools:context=".MainActivity"> android:layout_height="wrap_content"
<EditText
android:id="@+id/editText" android:layout_below="@id/button_show_d
android:layout_width="match_parent" ata"
android:layout_height="wrap_content" android:layout_centerHorizontal="true"
android:hint="Enter data" android:layout_marginTop="16dp"
android:layout_margin="16dp"/> android:text="Reset DB"/>
<Button <ListView
android:id="@+id/button_add" android:id="@+id/listView"
android:layout_width="wrap_content" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="match_parent"
android:layout_below="@id/editText"
android:layout_centerHorizontal="true" android:layout_below="@id/button_reset_db
android:layout_marginTop="16dp" "
android:text="Add Data"/> android:layout_marginTop="16dp"/>
<Button </RelativeLayout>
android:id="@+id/button_show_data"
android:layout_width="wrap_content"

• MainActivity.java

package com.example.twentysix; private Button buttonAdd,


buttonShowData, buttonResetDB;
import android.os.AsyncTask; private ListView listView;
import android.os.Bundle; private DatabaseHelper databaseHelper;
import android.view.View; private DataAdapter dataAdapter;
import android.widget.Button; private ArrayList<String> dataList;
import android.widget.EditText;
import android.widget.ListView; @Override
import android.widget.Toast; protected void onCreate(Bundle
savedInstanceState) {
import super.onCreate(savedInstanceState);
androidx.appcompat.app.AppCompatActivity; setContentView(R.layout.activity_main);

import java.util.ArrayList; editText = findViewById(R.id.editText);


buttonAdd =
public class MainActivity extends findViewById(R.id.button_add);
AppCompatActivity { buttonShowData =
private EditText editText; findViewById(R.id.button_show_data);
buttonResetDB =
findViewById(R.id.button_reset_db); doInBackground(String... params) {
listView = findViewById(R.id.listView); return
databaseHelper.insertData(params[0]);
databaseHelper = new }
DatabaseHelper(this);
dataList = new ArrayList<>(); @Override
dataAdapter = new DataAdapter(this, protected void onPostExecute(Boolean
dataList); result) {
listView.setAdapter(dataAdapter); if (result) {
Toast.makeText(MainActivity.this,
// Add Data Button "Data inserted successfully",
buttonAdd.setOnClickListener(new Toast.LENGTH_SHORT).show();
View.OnClickListener() { editText.setText("");
@Override } else {
public void onClick(View v) { Toast.makeText(MainActivity.this,
String data = "Failed to insert data",
editText.getText().toString().trim(); Toast.LENGTH_SHORT).show();
}
if (!data.isEmpty()) { }
new }
InsertDataTask().execute(data);
} else { // Fetch Data Task
private class FetchDataTask extends
Toast.makeText(MainActivity.this, "Please AsyncTask<Void, Void, ArrayList<String>>
enter data", Toast.LENGTH_SHORT).show(); {
} @Override
} protected ArrayList<String>
}); doInBackground(Void... voids) {
return databaseHelper.getAllData();
// Show Data Button }

buttonShowData.setOnClickListener(new @Override
View.OnClickListener() { protected void
@Override onPostExecute(ArrayList<String> result) {
public void onClick(View v) { if (result != null && !result.isEmpty())
new FetchDataTask().execute(); {
} dataList.clear();
}); dataList.addAll(result);

// Reset DB Button dataAdapter.notifyDataSetChanged();


buttonResetDB.setOnClickListener(new } else {
View.OnClickListener() { Toast.makeText(MainActivity.this,
@Override "No data found",
public void onClick(View v) { Toast.LENGTH_SHORT).show();
new }
ResetDatabaseTask().execute(); }
} }
});
} // Reset Database Task
private class ResetDatabaseTask extends
// Insert Data Task AsyncTask<Void, Void, Boolean> {
private class InsertDataTask extends @Override
AsyncTask<String, Void, Boolean> { protected Boolean
@Override doInBackground(Void... voids) {
protected Boolean return databaseHelper.resetDatabase();
} } else {
Toast.makeText(MainActivity.this,
@Override "Failed to reset database",
protected void onPostExecute(Boolean Toast.LENGTH_SHORT).show();
result) { }
if (result) { }
Toast.makeText(MainActivity.this, }
"Database reset successfully", }
Toast.LENGTH_SHORT).show();
dataList.clear();

dataAdapter.notifyDataSetChanged();

• DatabaseHelper.java

package com.example.twentysix; context) {


super(context, DATABASE_NAME,
import android.content.ContentValues; null, DATABASE_VERSION);
import android.content.Context; }
import android.database.Cursor;
import @Override
android.database.sqlite.SQLiteDatabase; public void onCreate(SQLiteDatabase
import db) {
android.database.sqlite.SQLiteOpenHelp
er; db.execSQL(CREATE_TABLE_QUERY)
;
import java.util.ArrayList; }

public class DatabaseHelper extends @Override


SQLiteOpenHelper { public void
onUpgrade(SQLiteDatabase db, int
private static final String oldVersion, int newVersion) {
DATABASE_NAME = "my_database"; db.execSQL("DROP TABLE IF
private static final int EXISTS " + TABLE_NAME);
DATABASE_VERSION = 1; onCreate(db);
}
private static final String
TABLE_NAME = "my_table"; public boolean insertData(String data)
private static final String {
COLUMN_ID = "id"; SQLiteDatabase db =
private static final String this.getWritableDatabase();
COLUMN_DATA = "data"; ContentValues values = new
ContentValues();
private static final String values.put(COLUMN_DATA, data);
CREATE_TABLE_QUERY = long result =
"CREATE TABLE " + db.insert(TABLE_NAME, null, values);
TABLE_NAME + " (" + return result != -1;
COLUMN_ID + " }
INTEGER PRIMARY KEY
AUTOINCREMENT," + public ArrayList<String> getAllData()
COLUMN_DATA + " {
TEXT)"; ArrayList<String> dataList = new
ArrayList<>();
public DatabaseHelper(Context SQLiteDatabase db =
this.getReadableDatabase(); return dataList;
Cursor cursor = }
db.rawQuery("SELECT * FROM " +
TABLE_NAME, null); public boolean resetDatabase() {
SQLiteDatabase db =
if (cursor.moveToFirst()) { this.getWritableDatabase();
do { db.execSQL("DELETE FROM " +
String data = TABLE_NAME);
cursor.getString(1); // Get data from db.execSQL("VACUUM"); //
column 1 Optional to optimize DB size
dataList.add(data); return true;
} while (cursor.moveToNext()); }
} }
cursor.close();

• DataAdapter.java

package com.example.twentysix;
@Override
import android.content.Context; public View getView(int position, View
import android.view.LayoutInflater; convertView, ViewGroup parent) {
import android.view.View; String data = getItem(position);
import android.view.ViewGroup;
import android.widget.ArrayAdapter; if (convertView == null) {
import android.widget.TextView; convertView =
LayoutInflater.from(getContext()).inflate(R.layout.list_
item, parent, false);
import java.util.ArrayList;
}

public class DataAdapter extends


TextView textView =
ArrayAdapter<String> {
convertView.findViewById(R.id.textViewItem);
public DataAdapter(Context context,
textView.setText(data);
ArrayList<String> dataList) {
return convertView;
super(context, 0, dataList);
}
}
}
• List_item.xml

<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textViewItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:textSize="16sp"
android:textColor="#000000"/>
Output:

You might also like