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

Mad 26

The document describes code for inserting records into a database using normal and fast methods. It includes XML layout code for a form with buttons to trigger the inserts. It also includes Java code for an activity class with click handlers for the buttons that execute asynchronous insert tasks. The tasks insert records and report timing and completion information.

Uploaded by

Parth Kulkarni
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)
11 views5 pages

Mad 26

The document describes code for inserting records into a database using normal and fast methods. It includes XML layout code for a form with buttons to trigger the inserts. It also includes Java code for an activity class with click handlers for the buttons that execute asynchronous insert tasks. The tasks insert records and report timing and completion information.

Uploaded by

Parth Kulkarni
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

Name :- Shravan M.

Palikundwar Practical No :- 26
Roll No :- 27

1. activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.Constra android:id="@+id/buttonNormalInsert"
intLayout
android:layout_width="wrap_content"
xmlns:android="http://schemas.android.co
m/apk/res/android" android:layout_height="wrap_content"

xmlns:app="http://schemas.android.com/a android:layout_below="@+id/editTextRec
pk/res-auto" ordNum"

xmlns:tools="http://schemas.android.com/t android:layout_alignLeft="@+id/editText
ools" RecordNum"
android:layout_width="match_parent" android:layout_marginStart="44dp"
android:layout_height="match_parent" android:layout_marginLeft="44dp"
tools:context=".MainActivity"> android:layout_marginTop="44dp"
<EditText
android:fontFamily="@font/poppins_medi
android:id="@+id/editTextRecordNum" um"
android:layout_width="318dp" android:text="Normal Insert"
android:layout_height="50dp"
app:layout_constraintStart_toStartOf="par
android:layout_alignParentLeft="true" ent"

android:layout_alignParentTop="true" app:layout_constraintTop_toBottomOf="
android:layout_marginStart="44dp" @+id/editTextRecordNum" />
android:layout_marginLeft="44dp" <Button
android:layout_marginTop="124dp" android:id="@+id/buttonFastInsert"
android:ems="10"
android:layout_width="wrap_content"
android:fontFamily="@font/poppins_medi
um" android:layout_height="wrap_content"
android:inputType="number"
android:singleLine="true" android:layout_alignBaseline="@+id/butt
android:textColor="#FFFFFF" onNormalInsert"

app:layout_constraintStart_toStartOf="par android:layout_alignBottom="@+id/butto
ent" nNormalInsert"
android:layout_marginTop="44dp"
app:layout_constraintTop_toTopOf="pare android:layout_marginEnd="48dp"
nt" android:layout_marginRight="48dp"
tools:ignore="MissingConstraints" />
<Button android:layout_toRightOf="@+id/buttonN
Name :- Shravan M. Palikundwar Practical No :- 26
Roll No :- 27
ormalInsert" android:layout_alignLeft="@+id/buttonNo
rmalInsert"
android:fontFamily="@font/poppins_medi android:layout_marginStart="16dp"
um" android:layout_marginLeft="16dp"
android:text="Fast Insert" android:layout_marginTop="36dp"

app:layout_constraintEnd_toEndOf="pare android:fontFamily="@font/poppins_medi
nt" um"
android:padding="10dp"
app:layout_constraintTop_toBottomOf=" android:text="Status"
@+id/editTextRecordNum" /> android:textColor="#FFFFFF"
<TextView android:textSize="18sp"
android:id="@+id/textViewStatus"
app:layout_constraintStart_toStartOf="par
android:layout_width="wrap_content" ent"

android:layout_height="wrap_content" app:layout_constraintTop_toBottomOf="
@+id/buttonNormalInsert" />
android:layout_below="@+id/buttonNorm </androidx.constraintlayout.widget.Constr
alInsert" aintLayout>

1. MainActivity.java

package com.example.coexp26; case R.id.buttonFastInsert:


new
import android.os.AsyncTask; AsyncInsertData("fast").execute();
import android.os.Bundle; break;
import android.app.Activity; }
import android.view.View; }
import };
android.widget.EditText; // EditText for entering desired number of
import android.widget.TextView; records to be inserted
public class MainActivity extends Activity editTextRecordNum = (EditText)
findViewById(R.id.editTextRecordNum);
{ // Button for normal and fast insert
final String TAG = "MainActivity.java";
EditText editTextRecordNum; findViewById(R.id.buttonNormalInsert).s
TextView tvStatus; etOnClickListener(handler);

@Override findViewById(R.id.buttonFastInsert).setO
protected void onCreate(Bundle nClickListener(handler);
savedInstanceState) { // status TextView tvStatus =
super.onCreate(savedInstanceState); (TextView)
findViewById(R.id.textViewStatus);
setContentView(R.layout.activity_main); }
View.OnClickListener handler = new // we used AsyncTask so it won't block the
View.OnClickListener() { UI thread during inserts.
public void onClick(View v) { class AsyncInsertData extends AsyncTask<String,
switch (v.getId()) { String, String> {
case R.id.buttonNormalInsert: DatabaseHandler databaseHandler;
new String type;
AsyncInsertData("normal").execute();
break;
Name :- Shravan M. Palikundwar Practical No :- 26
Roll No :- 27
long timeElapsed; long lStartTime =
protected AsyncInsertData(String System.nanoTime();
type){ if (type.equals("normal")) {
this.type = type;
this.databaseHandler = new databaseHandler.insertNormal(insertCount
DatabaseHandler(MainActivity.this); );
} } else {
// @type - can be 'normal' or 'fast'
@Override databaseHandler.insertFast(insertCount);
protected void onPreExecute() { }
super.onPreExecute(); // execution finished
tvStatus.setText("Inserting " + long lEndTime =
editTextRecordNum.getText() + " System.nanoTime();
records..."); // display execution time
} timeElapsed = lEndTime -
@Override lStartTime;
protected String } catch (Exception e) {
doInBackground(String... aurl) { e.printStackTrace();
try { }
// get number of records to be return null;
inserted }
int insertCount = protected void onPostExecute(String
Integer.parseInt(editTextRecordNum.getT unused) {
ext().toString()); tvStatus.setText("Done inserting "
+ databaseHandler.countRecords() + "
// empty the table records. Time elapsed: " + timeElapsed /
1000000 + " ms.");
databaseHandler.deleteRecords(); }}}
// keep track of execution time

2. DatabaseHandler.java

package com.example.coexp26; "DatabaseHandler.java";


// database version
import android.content.ContentValues; private static final int
import android.content.Context; DATABASE_VERSION = 7;
import android.database.Cursor; // database name
import protected static final String
android.database.sqlite.SQLiteDatabase; DATABASE_NAME = "NinjaDatabase2";
import // table details
android.database.sqlite.SQLiteOpenHelper public String tableName = "locations";
; public String fieldObjectId = "id";
import public String fieldObjectName =
android.database.sqlite.SQLiteStatement; "name";
import android.util.Log; public String fieldObjectDescription =
public class DatabaseHandler extends "description";
SQLiteOpenHelper { // constructor
// for our logs
public static final String TAG = public DatabaseHandler(Context
Name :- Shravan M. Palikundwar Practical No :- 26
Roll No :- 27
context) { }
super(context, DATABASE_NAME, db.setTransactionSuccessful();
null, DATABASE_VERSION); db.endTransaction();
}
db.close();
// creating table
}
@Override
// inserts the record without using
public void onCreate(SQLiteDatabase
transaction and prepare statement
db) {
String sql = "";
public void insertNormal(int
sql += "CREATE TABLE " +
insertCount){
tableName;
try{
sql += " ( ";
SQLiteDatabase db =
sql += fieldObjectId + " INTEGER
this.getWritableDatabase();
PRIMARY KEY AUTOINCREMENT,
for(int x=1; x<=insertCount; x++){
";
ContentValues values = new
sql += fieldObjectName + " TEXT, ";
ContentValues();
sql += fieldObjectDescription + "
values.put(fieldObjectName,
TEXT ";
"Name # " + x);
sql += " ) ";
db.execSQL(sql);
values.put(fieldObjectDescription,
String INDEX = "CREATE UNIQUE
"Description # " + x);
INDEX locations_index ON "
db.insert(tableName, null,
+ tableName + " (name,
values);
description)";
}
db.execSQL(INDEX);
db.close();
}
}catch(Exception e){
// When upgrading the database, it will
e.printStackTrace();
drop the current table and recreate.
}}
@Override
// deletes all records
public void onUpgrade(SQLiteDatabase
db, int oldVersion, int newVersion) { public void deleteRecords(){
SQLiteDatabase db =
String sql = "DROP TABLE IF
this.getWritableDatabase();
EXISTS " + tableName;
db.execSQL(sql); db.execSQL("delete from "+
onCreate(db); tableName);
} db.close();
// insert data using transaction and }
prepared statement // count records
public void insertFast(int insertCount) public int countRecords(){
{ SQLiteDatabase db =
// you can use INSERT only this.getWritableDatabase();
String sql = "INSERT OR Cursor cursor =
REPLACE INTO " + tableName + " ( db.rawQuery("SELECT count(*) from " +
name, description ) VALUES ( ?, ? )"; tableName, null);
SQLiteDatabase db = cursor.moveToFirst();
this.getWritableDatabase(); int recCount = cursor.getInt(0);
db.beginTransactionNonExclusive(); cursor.close();
// db.beginTransaction(); db.close();
SQLiteStatement stmt = return recCount;
db.compileStatement(sql); }}
for(int x=1; x<=insertCount; x++){
stmt.execute();
stmt.bindString(1, "Name # " +
stmt.clearBindings();
x); stmt.bindString(2, "Description
# "
+ x);
Name :- Shravan M. Palikundwar Practical No :- 26
Roll No :- 27

You might also like