Professional Documents
Culture Documents
26
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.
2.
Android defines AsyncTask as “a class that extends the Object class to allow short operations
to run asynchronously in the background.”
Services are used for long running operations.
3.
Use AsyncTask or Service in background for a process that takes a long time to do its work.
X. Exercise
Note: Faculty must ensure that every group of students use different input value.
(Use blank space for answers or attach more pages if needed)
1. Write a program to insert data in SQLite database using AsyncTask
Answers:
1.
//MainActivity.java
package com.jamiapolytechnic.experiment261;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
@Override
protected void onPreExecute() {
}
@Override
protected Void doInBackground(Void... params) {
dbObj = new Database_SpeedDial(MainActivity.this);
}
return null;
}
@Override
protected void onPostExecute(Void res) {
//System.out.println("Inside onPostExecute");
}
}
}
//=====================================================================
//activity_main.xml
<Button
android:id="@+id/btn_addcontact_add"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add Contact"
android:gravity="center"
android:onClick="process" />
<Button
android:id="@+id/btn_addcontact_cancel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Cancel"
android:gravity="center"
android:onClick="process" />
<TextView
android:id="@+id/message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_marginTop="100dp"
android:textColor="#0000ff"
android:text="Messages here"/>
</LinearLayout>
//=====================================================================
//Database_SpeedDial.java
package com.jamiapolytechnic.experiment261;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class Database_SpeedDial extends SQLiteOpenHelper{
static String name = "speeddial_contacts";
static int version = 1;
SQLiteDatabase db;
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS cntcts(name TEXT, number TEXT)");
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}