Practical No. 26: Perform Async Task Using Sqlite. I. Practical Significance
Practical No. 26: Perform Async Task Using Sqlite. I. Practical Significance
Practical No. 26: Perform Async Task Using Sqlite. I. Practical Significance
I. Practical Significance
Android AsyncTask is an abstract class provided by Android which gives us the
liberty to perform heavy tasks in the background and keep the UI thread light thus
making the application more responsive.
VII. Minimum Theoretical Background
Android application runs on a single thread when launched. Due to this single
thread model tasks that take longer time to fetch the response can make the
application non- responsive. To avoid this, we use android AsyncTask to perform
the heavy tasks in background on a dedicated thread and passing the results back to
the UI thread. Hence use of AsyncTask in android application keeps the UI thread
responsive at all times.
IX. Practical related Questions
1. List the basic methods used in an androidAsynk.
1. onPreExecute(), invoked on the UI thread before the task is executed. This
step is normally used to setup the task, for instance by showing a progress bar
in the user interface.
2. doInBackground(Params...), invoked on the background thread immediately
after onPreExecute() finishes executing. This step is used to perform
background computation that can take a long time. The parameters of the
asynchronous task are passed to this step. The result of the computation must
be returned by this step and will be passed back to the last step. This step can
also use publishProgress(Progress...) to publish one or more units of progress.
3. onProgressUpdate(Progress...), invoked on the UI thread after a call
to publishProgress(Progress...). The timing of the execution is undefined. This
method is used to display any form of progress in the user interface while the
background computation is still executing. For instance, it can be used to
animate a progress bar or show logs in a text field.
4. onPostExecute(Result), invoked on the UI thread after the background
computation finishes. The result of the background computation is passed to
this step as a parameter.
2. Differentiate between AsyncTask andServices.
3. Name the method used, if a process takes a long time to do its work?
1. A foreground process is one that is required for what the user is currently
doing. Various application components can cause its containing process to be
considered foreground in different ways.
2. A visible process is doing work that the user is currently aware of, so killing
it would have a noticeable negative impact on the user experience.
3. A service process is one holding a Service that has been started with
the startService() method. Though these processes are not directly visible to
the user, they are generally doing things that the user cares about (such as
background network data upload or download), so the system will always
keep such processes running unless there is not enough memory to retain all
foreground and visible processes.
4. A cached process is one that is not currently needed, so the system is free to
kill it as desired when resources like memory are needed elsewhere. In a
normally behaving system, these are the only processes involved in resource
management: a well running system will have multiple cached processes
always available (for more efficient switching between applications) and
regularly kill the oldest ones as needed. Only in very critical (and
undesireable) situations will the system get to a point where all cached
processes are killed and it must start killing service processes.
X. Exercise
1. Write a program to insert data in SQLite database using AsyncTask
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
xmlns:android="http://schemas.android.com/apk/res/android
"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="97dp"
android:layout_y="20dp"
android:gravity="center_horizontal"
android:text="Student Details"
android:textColor="@color/black"
android:textStyle="bold"
android:textAlignment="center"
android:textSize="30sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="20dp"
android:layout_y="110dp"
android:text="Enter Rollno:"
android:textColor="@color/black"
android:textSize="20sp" />
<EditText
android:id="@+id/Rollno"
android:textColor="@color/black"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="175dp"
android:layout_y="100dp"
android:inputType="number"
android:textSize="20sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="20dp"
android:layout_y="160dp"
android:text="Enter Name:"
android:textColor="@color/black"
android:textSize="20sp" />
<EditText
android:id="@+id/Name"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:textColor="@color/black"
android:layout_x="175dp"
android:layout_y="150dp"
android:inputType="text"
android:textSize="20sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="20dp"
android:layout_y="210dp"
android:text="Enter Marks:"
android:textColor="@color/black"
android:textSize="20sp" />
<EditText
android:id="@+id/Marks"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:textColor="@color/black"
android:layout_x="175dp"
android:layout_y="200dp"
android:inputType="number"
android:textSize="20sp" />
<Button
android:id="@+id/Insert"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="25dp"
android:layout_y="300dp"
android:background="#E91E63"
android:text="Insert"
android:textColor="@color/white"
android:textSize="26dp"
app:backgroundTint="#E91E63" />
<Button
android:id="@+id/Delete"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="210dp"
android:layout_y="298dp"
android:background="#E91E63"
android:text="Delete"
android:textColor="@color/white"
android:textSize="26dp"
app:backgroundTint="#E91E63" />
<Button
android:id="@+id/Update"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="23dp"
android:layout_y="396dp"
android:background="#E91E63"
android:text="Update"
android:textColor="@color/white"
android:textSize="26dp"
app:backgroundTint="#E91E63" />
<Button
android:id="@+id/View"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="217dp"
android:layout_y="392dp"
android:background="#E91E63"
android:text="View"
android:textColor="@color/white"
android:textSize="26dp"
app:backgroundTint="#E91E63" />
<Button
android:id="@+id/ViewAll"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_x="100dp"
android:layout_y="500dp"
android:background="#E91E63"
android:text="View All"
android:textColor="@color/white"
android:textSize="26dp"
app:backgroundTint="#E91E63" />
</AbsoluteLayout>
MainActivity.java
package com.example.pract_26;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
Rollno=(EditText)findViewById(R.id.Rollno);
Name=(EditText)findViewById(R.id.Name);
Marks=(EditText)findViewById(R.id.Marks);
Insert=(Button)findViewById(R.id.Insert);
Delete=(Button)findViewById(R.id.Delete);
Update=(Button)findViewById(R.id.Update);
View=(Button)findViewById(R.id.View);
ViewAll=(Button)findViewById(R.id.ViewAll);
Insert.setOnClickListener(this);
Delete.setOnClickListener(this);
Update.setOnClickListener(this);
View.setOnClickListener(this);
ViewAll.setOnClickListener(this);
if(Rollno.getText().toString().trim().length()==0||
Name.getText().toString().trim().length()==0||
Marks.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter all
values");
return;
}
db.execSQL("INSERT INTO student
VALUES('"+Rollno.getText()+"','"+Name.getText()+
"','"+Marks.getText()+"');");
showMessage("Success", "Record added");
clearText();
}
// Deleting a record from the Student table
if(view==Delete)
{
// Checking for empty roll number
if(Rollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter
Rollno");
return;
}
Cursor c=db.rawQuery("SELECT * FROM student
WHERE rollno='"+Rollno.getText()+"'", null);
if(c.moveToFirst())
{
db.execSQL("DELETE FROM student WHERE
rollno='"+Rollno.getText()+"'");
showMessage("Success", "Record Deleted");
}
else
{
showMessage("Error", "Invalid Rollno");
}
clearText();
}
// Updating a record in the Student table
if(view==Update)
{
// Checking for empty roll number
if(Rollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter
Rollno");
return;
}
Cursor c=db.rawQuery("SELECT * FROM student
WHERE rollno='"+Rollno.getText()+"'", null);
if(c.moveToFirst()) {
db.execSQL("UPDATE student SET name='" +
Name.getText() + "',marks='" + Marks.getText() +
"' WHERE
rollno='"+Rollno.getText()+"'");
showMessage("Success", "Record
Modified");
}
else {
showMessage("Error", "Invalid Rollno");
}
clearText();
}
// Display a record from the Student table
if(view==View)
{
// Checking for empty roll number
if(Rollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter
Rollno");
return;
}
Cursor c=db.rawQuery("SELECT * FROM student
WHERE rollno='"+Rollno.getText()+"'", null);
if(c.moveToFirst())
{
Name.setText(c.getString(1));
Marks.setText(c.getString(2));
}
else
{
showMessage("Error", "Invalid Rollno");
clearText();
}
}
// Displaying all the records
if(view==ViewAll)
{
Cursor c=db.rawQuery("SELECT * FROM student",
null);
if(c.getCount()==0)
{
showMessage("Error", "No records found");
return;
}
StringBuffer buffer=new StringBuffer();
while(c.moveToNext())
{
buffer.append("Rollno:
"+c.getString(0)+"\n");
buffer.append("Name:
"+c.getString(1)+"\n");
buffer.append("Marks:
"+c.getString(2)+"\n\n");
}
showMessage("Student Details",
buffer.toString());
}
}
public void showMessage(String title,String message)
{
Builder builder=new Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
public void clearText()
{
Rollno.setText("");
Name.setText("");
Marks.setText("");
Rollno.requestFocus();
}
}