///////////////////////Sqllite datbase///////////////////////
SQLiteOpenHelper
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
class DatabaseHelper(context: Context) :
SQLiteOpenHelper(context, DATABASE_NAME, null,
DATABASE_VERSION) {
companion object {
const val DATABASE_NAME = "[Link]"
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 [Link](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 [Link](TABLE_NAME, values, "$COLUMN_ID
= ?", arrayOf([Link]()))
}
// Delete data from the database
fun deleteUser(id: Int): Int {
val db = writableDatabase
return [Link](TABLE_NAME, "$COLUMN_ID = ?",
arrayOf([Link]()))
}
// Select all data from the database
fun getAllUsers(): Cursor {
val db = readableDatabase
return [Link](TABLE_NAME, null, null, null, null, null,
null)
}
}
********MainActivity**********
import [Link]
import [Link]
import [Link]
import [Link]
class MainActivity : AppCompatActivity() {
private lateinit var dbHelper: DatabaseHelper
override fun onCreate(savedInstanceState: Bundle?) {
[Link](savedInstanceState)
setContentView([Link].activity_main)
dbHelper = DatabaseHelper(this)
// Insert data
val userId = [Link]("John Doe", 30)
[Link](this, "User inserted with ID: $userId",
Toast.LENGTH_SHORT).show()
// Update data
val updatedRows = [Link]([Link](),
"John Smith", 31)
[Link](this, "Rows updated: $updatedRows",
Toast.LENGTH_SHORT).show()
// Delete data
val deletedRows = [Link]([Link]())
[Link](this, "Rows deleted: $deletedRows",
Toast.LENGTH_SHORT).show()
// Select all data and display in a Toast
val cursor: Cursor = [Link]()
if ([Link]()) {
do {
val id =
[Link]([Link]([Link]
_ID))
val name =
[Link]([Link]([Link]
MN_NAME))
val age =
[Link]([Link]([Link]
_AGE))
[Link](this, "ID: $id, Name: $name, Age:
$age", Toast.LENGTH_LONG).show()
} while ([Link]())
}
[Link]()
}
}
////////////////////////////////notification
code/////////////////////////////////////////
****[Link]:
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
class MainActivity : AppCompatActivity() {
private val CHANNEL_ID = "my_channel_id"
override fun onCreate(savedInstanceState: Bundle?) {
[Link](savedInstanceState)
setContentView([Link].activity_main)
// Create the notification channel
createNotificationChannel()
// Show the notification
showNotification()
}
// Function to create the notification channel
private fun createNotificationChannel() {
if ([Link].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
[Link](channel)
}
}
// Function to show the notification
private fun showNotification() {
val builder = [Link](this,
CHANNEL_ID)
.setSmallIcon([Link].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 =
[Link](this)
[Link](1, [Link]()) // Notify with
ID = 1
}
}
/////////////////// progresss notification //////////////////////////
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
class MainActivity : AppCompatActivity() {
private val CHANNEL_ID = "progress_channel"
private val notificationId = 1
private lateinit var notificationManager:
NotificationManagerCompat
private lateinit var builder: [Link]
private var progress = 0
override fun onCreate(savedInstanceState: Bundle?) {
[Link](savedInstanceState)
setContentView([Link].activity_main)
// Create the notification channel (only for Android O+)
createNotificationChannel()
// Initialize the NotificationManager
notificationManager =
[Link](this)
// Initialize the builder for the progress notification
builder = [Link](this, CHANNEL_ID)
.setSmallIcon([Link].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
[Link](notificationId, [Link]())
// Simulate the download process (with a delay)
startProgress()
}
// Create the notification channel (required for Android O and
above)
private fun createNotificationChannel() {
if ([Link].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
[Link](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([Link]())
val runnable = object : Runnable {
override fun run() {
// Simulate progress
if (progress <= 100) {
// Update the progress
[Link](100, progress, false)
[Link](notificationId,
[Link]())
progress += 10 // Increase progress by 10% each
time
// Post a delay of 500 milliseconds and call run()
again to update the progress
[Link](this, 500)
} else {
// Task is complete, show completion notification
[Link]("Download Complete")
.setProgress(0, 0, false)
[Link](notificationId,
[Link]())
}
}
}
// Start updating progress
[Link](runnable)
}
}
////////////////// Retrofit library //////////////////////
**********[Link] (app)***********
dependencies {
// Retrofit
implementation '[Link].retrofit2:retrofit:2.9.0'
implementation '[Link].retrofit2:converter-
gson:2.9.0'
// OkHttp for logging (optional but helpful for debugging)
implementation '[Link].okhttp3:logging-
interceptor:4.9.1'
}
**************MainActivity******************
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
class MainActivity : AppCompatActivity() {
private lateinit var userTextView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
[Link](savedInstanceState)
setContentView([Link].activity_main)
userTextView = findViewById([Link])
// 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 = [Link](userId)
[Link](object : Callback<User> {
override fun onResponse(call: Call<User>, response:
Response<User>) {
if ([Link]) {
// If response is successful, display the user's info
val user = [Link]()
[Link] = "ID: ${user?.id}\nName: $
{user?.name}\nEmail: ${user?.email}"
} else {
// Handle unsuccessful response
[Link](this@MainActivity, "Error: $
{[Link]()}", Toast.LENGTH_SHORT).show()
}
}
override fun onFailure(call: Call<User>, t: Throwable) {
// Handle failure (e.g., no internet)
[Link](this@MainActivity, "Network failure:
${[Link]}", Toast.LENGTH_SHORT).show()
}
})
}
}
////////////////////////moshi_library//////////////////
**********[Link] ***********
dependencies {
implementation '[Link]:moshi:1.15.0' // Latest
version at the time
implementation '[Link]:moshi-kotlin:1.15.0'
implementation '[Link].retrofit2:converter-
moshi:2.9.0' // if using Retrofit
}
*************json*************
{
"id": 1,
"name": "John Doe",
"email": "[Link]@[Link]"
}
//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 [Link]
import
[Link]
import [Link]
// Create a Moshi instance with the Kotlin adapter factory
val moshi =
[Link]().add(KotlinJsonAdapterFactory()).build()
// Create a JSON adapter for the User class
val jsonAdapter: JsonAdapter<User> =
[Link](User::[Link])
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", "[Link]@[Link]")
// Convert the User object to JSON string
val json = [Link](user)
println(json)
This will output something like:
json
Copy code
{"id":1,"name":"John Doe","email":"[Link]@[Link]"}
Deserialization (JSON to Object)
kotlin
Copy code
val jsonString = """
{
"id": 1,
"name": "John Doe",
"email": "[Link]@[Link]"
}
"""
// Convert JSON string to User object
val userFromJson = [Link](jsonString)
println(userFromJson)
This will print:
kotlin
Copy code
User(id=1, name=John Doe, email=[Link]@[Link])
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 [Link]
import [Link]
val retrofit = [Link]()
.baseUrl("[Link]
.addConverterFactory([Link](moshi))
// Add Moshi converter
.build()
// Define your API interface and make requests as usual
//Example: Complete Kotlin Code
import [Link]
import
[Link]
import [Link]
data class User(
val id: Int,
val name: String,
val email: String
)
fun main() {
// Initialize Moshi with Kotlin adapter factory
val moshi =
[Link]().add(KotlinJsonAdapterFactory()).build()
// Create JSON adapter for User class
val jsonAdapter: JsonAdapter<User> =
[Link](User::[Link])
// Serialize example
val user = User(1, "John Doe", "[Link]@[Link]")
val json = [Link](user)
println("Serialized JSON: $json")
// Deserialize example
val jsonString = """{"id":1,"name":"John
Doe","email":"[Link]@[Link]"}"""
val userFromJson = [Link](jsonString)
println("Deserialized User: $userFromJson")
}
Output:
Serialized JSON: {"id":1,"name":"John
Doe","email":"[Link]@[Link]"}
Deserialized User: User(id=1, name=John Doe,
email=[Link]@[Link])