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

android_practical

The document provides a comprehensive overview of implementing SQLite database operations, notifications, and Retrofit library integration in an Android application. It includes code examples for creating a database helper class, managing user data, sending notifications, and using the Retrofit library for API calls with Moshi for JSON serialization and deserialization. Additionally, it demonstrates how to handle progress notifications and includes setup instructions for dependencies in the build.gradle file.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

android_practical

The document provides a comprehensive overview of implementing SQLite database operations, notifications, and Retrofit library integration in an Android application. It includes code examples for creating a database helper class, managing user data, sending notifications, and using the Retrofit library for API calls with Moshi for JSON serialization and deserialization. Additionally, it demonstrates how to handle progress notifications and includes setup instructions for dependencies in the build.gradle file.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

///////////////////////Sqllite datbase///////////////////////

SQLiteOpenHelper

import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.Cursor
import android.database.sqlite.SQLiteOpenHelper

class DatabaseHelper(context: Context) :


SQLiteOpenHelper(context, DATABASE_NAME, null,
DATABASE_VERSION) {

companion object {
const val DATABASE_NAME = "MyDatabase.db"
const val DATABASE_VERSION = 1
const val TABLE_NAME = "users"
const val COLUMN_ID = "id"
const val COLUMN_NAME = "name"
const val COLUMN_AGE = "age"
}

// Create table SQL query


override fun onCreate(db: SQLiteDatabase?) {
val createTableQuery = "CREATE TABLE $TABLE_NAME ("
+
"$COLUMN_ID INTEGER PRIMARY KEY
AUTOINCREMENT, " +
"$COLUMN_NAME TEXT, " +
"$COLUMN_AGE INTEGER)"
db?.execSQL(createTableQuery)
}

// Update database if schema changes


override fun onUpgrade(db: SQLiteDatabase?, oldVersion:
Int, newVersion: Int) {
db?.execSQL("DROP TABLE IF EXISTS $TABLE_NAME")
onCreate(db)
}

// Insert data into the database


fun insertUser(name: String, age: Int): Long {
val db = writableDatabase
val values = ContentValues().apply {
put(COLUMN_NAME, name)
put(COLUMN_AGE, age)
}
return db.insert(TABLE_NAME, null, values)
}

// Update data in the database


fun updateUser(id: Int, name: String, age: Int): Int {
val db = writableDatabase
val values = ContentValues().apply {
put(COLUMN_NAME, name)
put(COLUMN_AGE, age)
}
return db.update(TABLE_NAME, values, "$COLUMN_ID
= ?", arrayOf(id.toString()))
}

// Delete data from the database


fun deleteUser(id: Int): Int {
val db = writableDatabase
return db.delete(TABLE_NAME, "$COLUMN_ID = ?",
arrayOf(id.toString()))
}

// Select all data from the database


fun getAllUsers(): Cursor {
val db = readableDatabase
return db.query(TABLE_NAME, null, null, null, null, null,
null)
}
}

********MainActivity**********

import android.database.Cursor
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

private lateinit var dbHelper: DatabaseHelper

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
dbHelper = DatabaseHelper(this)

// Insert data
val userId = dbHelper.insertUser("John Doe", 30)
Toast.makeText(this, "User inserted with ID: $userId",
Toast.LENGTH_SHORT).show()

// Update data
val updatedRows = dbHelper.updateUser(userId.toInt(),
"John Smith", 31)
Toast.makeText(this, "Rows updated: $updatedRows",
Toast.LENGTH_SHORT).show()

// Delete data
val deletedRows = dbHelper.deleteUser(userId.toInt())
Toast.makeText(this, "Rows deleted: $deletedRows",
Toast.LENGTH_SHORT).show()

// Select all data and display in a Toast


val cursor: Cursor = dbHelper.getAllUsers()
if (cursor.moveToFirst()) {
do {
val id =
cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COLUMN
_ID))
val name =
cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLU
MN_NAME))
val age =
cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COLUMN
_AGE))
Toast.makeText(this, "ID: $id, Name: $name, Age:
$age", Toast.LENGTH_LONG).show()
} while (cursor.moveToNext())
}
cursor.close()
}
}

////////////////////////////////notification
code/////////////////////////////////////////

****MainActivity.kt:
import android.app.NotificationChannel
import android.app.NotificationManager
import android.os.Build
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import android.os.Bundle

class MainActivity : AppCompatActivity() {

private val CHANNEL_ID = "my_channel_id"

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Create the notification channel


createNotificationChannel()

// Show the notification


showNotification()
}

// Function to create the notification channel


private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "My Channel"
val descriptionText = "Channel for simple notifications"
val importance =
NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(CHANNEL_ID, name,
importance).apply {
description = descriptionText
}
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE)
as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}

// Function to show the notification


private fun showNotification() {
val builder = NotificationCompat.Builder(this,
CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_info) // Icon
for the notification
.setContentTitle("Hello") // Title of the notification
.setContentText("This is a simple notification") //
Message of the notification
.setPriority(NotificationCompat.PRIORITY_DEFAULT) //
Priority
.setAutoCancel(true) // Automatically removes the
notification when tapped

val notificationManager =
NotificationManagerCompat.from(this)
notificationManager.notify(1, builder.build()) // Notify with
ID = 1
}
}
/////////////////// progresss notification //////////////////////////

import android.app.NotificationChannel
import android.app.NotificationManager
import android.os.Build
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import android.os.Bundle
import android.os.Handler
import android.os.Looper

class MainActivity : AppCompatActivity() {

private val CHANNEL_ID = "progress_channel"


private val notificationId = 1
private lateinit var notificationManager:
NotificationManagerCompat
private lateinit var builder: NotificationCompat.Builder
private var progress = 0

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Create the notification channel (only for Android O+)


createNotificationChannel()
// Initialize the NotificationManager
notificationManager =
NotificationManagerCompat.from(this)

// Initialize the builder for the progress notification


builder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(android.R.drawable.stat_sys_download)
.setContentTitle("Downloading File")
.setContentText("Download in progress")
.setPriority(NotificationCompat.PRIORITY_LOW)
.setProgress(100, 0, false) // Initialize progress to 0%

// Show initial progress notification


notificationManager.notify(notificationId, builder.build())

// Simulate the download process (with a delay)


startProgress()
}

// Create the notification channel (required for Android O and


above)
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "Progress Channel"
val descriptionText = "Channel for progress
notifications"
val importance =
NotificationManager.IMPORTANCE_LOW
val channel = NotificationChannel(CHANNEL_ID, name,
importance).apply {
description = descriptionText
}
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE)
as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}

// Function to simulate a background task and update the


progress
private fun startProgress() {
// Handler to update the progress in the notification
val handler = Handler(Looper.getMainLooper())
val runnable = object : Runnable {
override fun run() {
// Simulate progress
if (progress <= 100) {
// Update the progress
builder.setProgress(100, progress, false)
notificationManager.notify(notificationId,
builder.build())
progress += 10 // Increase progress by 10% each
time

// Post a delay of 500 milliseconds and call run()


again to update the progress
handler.postDelayed(this, 500)
} else {
// Task is complete, show completion notification
builder.setContentText("Download Complete")
.setProgress(0, 0, false)
notificationManager.notify(notificationId,
builder.build())
}
}
}

// Start updating progress


handler.post(runnable)
}
}

////////////////// Retrofit library //////////////////////

**********build.gradle (app)***********
dependencies {
// Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-
gson:2.9.0'

// OkHttp for logging (optional but helpful for debugging)


implementation 'com.squareup.okhttp3:logging-
interceptor:4.9.1'
}

**************MainActivity******************
import android.os.Bundle
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class MainActivity : AppCompatActivity() {

private lateinit var userTextView: TextView

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

userTextView = findViewById(R.id.userTextView)

// Fetch user data from the API


getUser(1) // Example: Fetching user with ID 1
}

// Function to make the network request


private fun getUser(userId: Int) {
val call = RetrofitClient.apiService.getUser(userId)

call.enqueue(object : Callback<User> {
override fun onResponse(call: Call<User>, response:
Response<User>) {
if (response.isSuccessful) {
// If response is successful, display the user's info
val user = response.body()
userTextView.text = "ID: ${user?.id}\nName: $
{user?.name}\nEmail: ${user?.email}"
} else {
// Handle unsuccessful response
Toast.makeText(this@MainActivity, "Error: $
{response.code()}", Toast.LENGTH_SHORT).show()
}
}

override fun onFailure(call: Call<User>, t: Throwable) {


// Handle failure (e.g., no internet)
Toast.makeText(this@MainActivity, "Network failure:
${t.message}", Toast.LENGTH_SHORT).show()
}
})
}
}

////////////////////////moshi_library//////////////////

**********build.gradle ***********

dependencies {
implementation 'com.squareup.moshi:moshi:1.15.0' // Latest
version at the time
implementation 'com.squareup.moshi:moshi-kotlin:1.15.0'
implementation 'com.squareup.retrofit2:converter-
moshi:2.9.0' // if using Retrofit
}

*************json*************
{
"id": 1,
"name": "John Doe",
"email": "[email protected]"
}

//You can create a Kotlin data class to represent this:


*****************kotlin******************

data class User(


val id: Int,
val name: String,
val email: String
)

Step 3: Set Up Moshi and Converter


Now, you need to set up Moshi for JSON serialization and
deserialization.
kotlin
Copy code
import com.squareup.moshi.Moshi
import
com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import com.squareup.moshi.JsonAdapter

// Create a Moshi instance with the Kotlin adapter factory


val moshi =
Moshi.Builder().add(KotlinJsonAdapterFactory()).build()

// Create a JSON adapter for the User class


val jsonAdapter: JsonAdapter<User> =
moshi.adapter(User::class.java)

Step 4: Serialize and Deserialize JSON


Now, let's serialize (convert an object to JSON) and deserialize
(convert JSON to an object) using Moshi.

Serialization (Object to JSON)


kotlin
Copy code
val user = User(1, "John Doe", "[email protected]")

// Convert the User object to JSON string


val json = jsonAdapter.toJson(user)
println(json)
This will output something like:
json
Copy code
{"id":1,"name":"John Doe","email":"[email protected]"}

Deserialization (JSON to Object)


kotlin
Copy code
val jsonString = """
{
"id": 1,
"name": "John Doe",
"email": "[email protected]"
}
"""

// Convert JSON string to User object


val userFromJson = jsonAdapter.fromJson(jsonString)
println(userFromJson)
This will print:
kotlin
Copy code
User(id=1, name=John Doe, [email protected])
Step 5: Use Moshi with Retrofit (Optional)
If you are using Retrofit to make API requests, you can easily
integrate Moshi with it by adding the Moshi converter.

import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory

val retrofit = Retrofit.Builder()


.baseUrl("https://api.example.com/")
.addConverterFactory(MoshiConverterFactory.create(moshi))
// Add Moshi converter
.build()

// Define your API interface and make requests as usual


//Example: Complete Kotlin Code

import com.squareup.moshi.Moshi
import
com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import com.squareup.moshi.JsonAdapter

data class User(


val id: Int,
val name: String,
val email: String
)

fun main() {
// Initialize Moshi with Kotlin adapter factory
val moshi =
Moshi.Builder().add(KotlinJsonAdapterFactory()).build()

// Create JSON adapter for User class


val jsonAdapter: JsonAdapter<User> =
moshi.adapter(User::class.java)

// Serialize example
val user = User(1, "John Doe", "[email protected]")
val json = jsonAdapter.toJson(user)
println("Serialized JSON: $json")

// Deserialize example
val jsonString = """{"id":1,"name":"John
Doe","email":"[email protected]"}"""
val userFromJson = jsonAdapter.fromJson(jsonString)
println("Deserialized User: $userFromJson")
}

Output:

Serialized JSON: {"id":1,"name":"John


Doe","email":"[email protected]"}
Deserialized User: User(id=1, name=John Doe,
[email protected])

You might also like