0% found this document useful (0 votes)
4 views4 pages

Practical 19

The document outlines an Android application that includes an XML layout for the main activity, a database helper class for managing SQLite database operations, and a content provider for data access. It features a user interface with buttons to insert and fetch data, and the database stores user information such as name and age. The application is structured to handle data operations through content URIs and provides a simple way to display data in a TextView.

Uploaded by

janhavirhude
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)
4 views4 pages

Practical 19

The document outlines an Android application that includes an XML layout for the main activity, a database helper class for managing SQLite database operations, and a content provider for data access. It features a user interface with buttons to insert and fetch data, and the database stores user information such as name and age. The application is structured to handle data operations through content URIs and provides a simple way to display data in a TextView.

Uploaded by

janhavirhude
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/ 4

Practical 19 <application

android:allowBackup="true"
Activity_main.xml
android:dataExtractionRules="@xml/data_extraction_ru
<?xml version="1.0" encoding="utf-8"?> les"
<LinearLayout android:fullBackupContent="@xml/backup_rules"
xmlns:android="http://schemas.android.com/apk/res/an android:icon="@mipmap/ic_launcher"
droid" android:label="@string/app_name"
android:layout_width="match_parent" android:roundIcon="@mipmap/ic_launcher_round"
android:layout_height="match_parent" android:supportsRtl="true"
android:orientation="vertical" android:theme="@style/Theme.Pr19_e1"
android:padding="16dp"> tools:targetApi="31">

<TextView <activity
android:id="@+id/textView" android:name=".MainActivity"
android:layout_width="match_parent" android:exported="true">
android:layout_height="wrap_content" <intent-filter>
android:text="Data will appear here" <action
android:textSize="18sp" android:name="android.intent.action.MAIN" />
android:textStyle="bold" <category
android:padding="8dp" android:name="android.intent.category.LAUNCHER" />
android:background="#E0E0E0" </intent-filter>
android:gravity="center"/> </activity>

<Button <!-- Register Content Provider -->


android:id="@+id/btnInsert" <provider
android:layout_width="match_parent" android:name=".MyContentProvider"
android:layout_height="wrap_content"
android:text="Insert Data" /> android:authorities="com.example.mycontentprovider"
android:exported="true"
<Button android:grantUriPermissions="true"/>
android:id="@+id/btnFetch"
android:layout_width="match_parent" </application>
android:layout_height="wrap_content"
android:text="Fetch Data" /> </manifest>

</LinearLayout>

DataBaseHelper.java

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> package com.example.pr19_e1;
<manifest
xmlns:android="http://schemas.android.com/apk/res/an import android.content.Context;
droid" import android.database.sqlite.SQLiteDatabase;
xmlns:tools="http://schemas.android.com/tools"> import android.database.sqlite.SQLiteOpenHelper;

<uses-permission public class DatabaseHelper extends SQLiteOpenHelper {


android:name="android.permission.READ_EXTERNAL_ST private static final String DATABASE_NAME =
ORAGE"/> "mydatabase.db";
<uses-permission private static final int DATABASE_VERSION = 1;
android:name="android.permission.WRITE_EXTERNAL_S
TORAGE"/> public static final String TABLE_NAME = "users";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "name"; private static final int USER_ID = 2;
public static final String COLUMN_AGE = "age";
private static final UriMatcher uriMatcher = new
private static final String CREATE_TABLE = UriMatcher(UriMatcher.NO_MATCH);
"CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY static {
AUTOINCREMENT, " + uriMatcher.addURI(AUTHORITY, PATH_USERS,
COLUMN_NAME + " TEXT, " + USERS);
COLUMN_AGE + " INTEGER);"; uriMatcher.addURI(AUTHORITY, PATH_USERS + "/#",
USER_ID);
public DatabaseHelper(Context context) { }
super(context, DATABASE_NAME, null,
DATABASE_VERSION); private SQLiteDatabase database;
}
@Override
@Override public boolean onCreate() {
public void onCreate(SQLiteDatabase db) { DatabaseHelper dbHelper = new
db.execSQL(CREATE_TABLE); DatabaseHelper(getContext());
} database = dbHelper.getWritableDatabase();
return database != null;
@Override }
public void onUpgrade(SQLiteDatabase db, int
oldVersion, int newVersion) { @Override
db.execSQL("DROP TABLE IF EXISTS " + public Cursor query(Uri uri, String[] projection, String
TABLE_NAME); selection, String[] selectionArgs, String sortOrder) {
onCreate(db); Cursor cursor;
} switch (uriMatcher.match(uri)) {
} case USERS:
cursor =
database.query(DatabaseHelper.TABLE_NAME,
projection, selection, selectionArgs, null, null,
MyContentProvider.java sortOrder);
break;
package com.example.pr19_e1;
case USER_ID:
selection = DatabaseHelper.COLUMN_ID + "=?";
import android.content.ContentProvider;
selectionArgs = new
import android.content.ContentUris;
String[]{uri.getLastPathSegment()};
import android.content.ContentValues;
cursor =
import android.content.Context;
database.query(DatabaseHelper.TABLE_NAME,
import android.content.UriMatcher;
projection, selection, selectionArgs, null, null,
import android.database.Cursor;
sortOrder);
import android.database.SQLException;
break;
import android.database.sqlite.SQLiteDatabase;
default:
import android.net.Uri;
throw new
IllegalArgumentException("Unknown URI: " + uri);
public class MyContentProvider extends
}
ContentProvider {
private static final String AUTHORITY =
cursor.setNotificationUri(getContext().getContentResolv
"com.example.mycontentprovider";
er(), uri);
private static final String PATH_USERS = "users";
return cursor;
public static final Uri CONTENT_URI =
}
Uri.parse("content://" + AUTHORITY + "/" +
PATH_USERS);
@Override
public Uri insert(Uri uri, ContentValues values) {
private static final int USERS = 1;
long id = selectionArgs = new
database.insert(DatabaseHelper.TABLE_NAME, null, String[]{uri.getLastPathSegment()};
values); count =
if (id > 0) { database.update(DatabaseHelper.TABLE_NAME, values,
Uri newUri = selection, selectionArgs);
ContentUris.withAppendedId(CONTENT_URI, id); break;
default:
getContext().getContentResolver().notifyChange(newUri, throw new
null); IllegalArgumentException("Unknown URI: " + uri);
return newUri; }
} getContext().getContentResolver().notifyChange(uri,
throw new SQLException("Failed to insert row into " null);
+ uri); return count;
} }

@Override @Override
public int delete(Uri uri, String selection, String[] public String getType(Uri uri) {
selectionArgs) { return null;
int count; }
switch (uriMatcher.match(uri)) { }
case USERS:
count =
database.delete(DatabaseHelper.TABLE_NAME,
selection, selectionArgs); MainAcitivity.java
break;
package com.example.pr19_e1;
case USER_ID:
selection = DatabaseHelper.COLUMN_ID + "=?";
import android.content.ContentValues;
selectionArgs = new
import android.database.Cursor;
String[]{uri.getLastPathSegment()};
import android.net.Uri;
count =
import android.os.Bundle;
database.delete(DatabaseHelper.TABLE_NAME,
import android.view.View;
selection, selectionArgs);
import android.widget.Button;
break;
import android.widget.TextView;
default:
import androidx.appcompat.app.AppCompatActivity;
throw new
IllegalArgumentException("Unknown URI: " + uri);
public class MainActivity extends AppCompatActivity {
}
TextView textView;
getContext().getContentResolver().notifyChange(uri,
Button btnInsert, btnFetch;
null);
return count;
@Override
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
setContentView(R.layout.activity_main);
public int update(Uri uri, ContentValues values, String
selection, String[] selectionArgs) {
textView = findViewById(R.id.textView);
int count;
btnInsert = findViewById(R.id.btnInsert);
switch (uriMatcher.match(uri)) {
btnFetch = findViewById(R.id.btnFetch);
case USERS:
count =
// Insert Data on Button Click
database.update(DatabaseHelper.TABLE_NAME, values,
btnInsert.setOnClickListener(new
selection, selectionArgs);
View.OnClickListener() {
break;
@Override
case USER_ID:
public void onClick(View v) {
selection = DatabaseHelper.COLUMN_ID + "=?";
insertData("Alice", 25);
}
});

// Fetch Data on Button Click


btnFetch.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
fetchData();
}
});
}

private void insertData(String name, int age) {


ContentValues values = new ContentValues();
values.put(DatabaseHelper.COLUMN_NAME, name);
values.put(DatabaseHelper.COLUMN_AGE, age);

getContentResolver().insert(MyContentProvider.CONTEN
T_URI, values);
}

private void fetchData() {


Cursor cursor =
getContentResolver().query(MyContentProvider.CONTEN
T_URI, null, null, null, null);
StringBuilder result = new StringBuilder();

if (cursor != null) {
while (cursor.moveToNext()) {
int id =
cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseH
elper.COLUMN_ID));
String name =
cursor.getString(cursor.getColumnIndexOrThrow(Databa
seHelper.COLUMN_NAME));
int age =
cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseH
elper.COLUMN_AGE));
result.append("ID: ").append(id).append(",
Name: ").append(name).append(", Age:
").append(age).append("\n");
}
cursor.close();
}

textView.setText(result.toString());
}
}

You might also like