0% found this document useful (0 votes)
26 views9 pages

Practical No 19

The document provides a complete implementation of an Android application that includes a custom content provider for inserting and retrieving user data. It consists of an XML layout file for the user interface and Java code for the main activity and content provider logic. The application allows users to add names and display a list of added users using SQLite as the database backend.

Uploaded by

Sumedh Raut
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)
26 views9 pages

Practical No 19

The document provides a complete implementation of an Android application that includes a custom content provider for inserting and retrieving user data. It consists of an XML layout file for the user interface and Java code for the main activity and content provider logic. The application allows users to add names and display a list of added users using SQLite as the database backend.

Uploaded by

Sumedh Raut
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/ 9

Que - Write a program to create your own content provider to insert and access data in

android application.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/andr
oid"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:layout_margin="20dp">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Name Below !"
android:textColor="@color/black"
android:textSize="20dp"
android:layout_marginLeft="30dp"
android:layout_marginTop="30dp"/>
<EditText
android:id="@+id/txtName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:ems="10"
android:layout_marginRight="30dp"/>
<Button
android:id="@+id/btnAdd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClickAddDetails"
android:layout_marginLeft="30dp"
android:layout_marginTop="20dp"
android:text="Add User"
android:layout_marginRight="30dp"/>

<Button
android:id="@+id/btnRetrieve"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClickShowDetails"
android:layout_marginLeft="30dp"
android:text="Show Users"
android:layout_marginTop="20dp"
android:layout_marginRight="30dp"/>
<TextView
android:id="@+id/res"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:clickable="false"
android:textSize="20dp"
android:textColor="#A52A2A"
android:layout_marginTop="50dp"
android:ems="10"/>

</LinearLayout>

MainActivity.java

package co6i.micro.project.practical19;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm = (InputMethodManager)getSystemServic
e(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken
(), 0);
return true;
}
public void onClickAddDetails(View view) {
ContentValues values = new ContentValues();
values.put(UsersProvider.name, ((EditText) findViewById(R.id
.txtName)).getText().toString());
getContentResolver().insert(UsersProvider.CONTENT_URI, value
s);
Toast.makeText(getBaseContext(), "New Record Inserted", Toas
t.LENGTH_LONG).show();
}

public void onClickShowDetails(View view) {


// Retrieve employee records
TextView resultView= (TextView) findViewById(R.id.res);
Cursor cursor = getContentResolver().query(Uri.parse("conten
t://co6i.micro.project.practical19.UsersProvider/users"), null, null
, null, null);
if(((Cursor) cursor).moveToFirst()) {
StringBuilder strBuild=new StringBuilder();
while (!cursor.isAfterLast()) {
strBuild.append("\n"+cursor.getString(cursor.getColu
mnIndex("id"))+ " - "+ cursor.getString(cursor.getColumnIndex("name"
)));
cursor.moveToNext();
}
resultView.setText(strBuild);
}
else {
resultView.setText("No Records Found");
}
}
}

UsersProvider.java

package co6i.micro.project.practical19;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;

import java.util.HashMap;

public class UsersProvider extends ContentProvider {


static final String PROVIDER_NAME = "co6i.micro.project.practica
l19.UsersProvider";
static final String URL = "content://" + PROVIDER_NAME + "/users
";
static final Uri CONTENT_URI = Uri.parse(URL);

static final String id = "id";


static final String name = "name";
static final int uriCode = 1;
static final UriMatcher uriMatcher;
private static HashMap<String, String> values;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(PROVIDER_NAME, "users", uriCode);
uriMatcher.addURI(PROVIDER_NAME, "users/*", uriCode);
}

@Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)) {
case uriCode:
return "vnd.android.cursor.dir/users";
default:
throw new IllegalArgumentException("Unsupported URI:
" + uri);
}
}

@Override
public boolean onCreate() {
Context context = getContext();
DatabaseHelper dbHelper = new DatabaseHelper(context);
db = dbHelper.getWritableDatabase();
if (db != null) {
return true;
}
return false;
}

@Override
public Cursor query(Uri uri, String[] projection, String selecti
on,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(TABLE_NAME);

switch (uriMatcher.match(uri)) {
case uriCode:
qb.setProjectionMap(values);
break;
default:
throw new IllegalArgumentException("Unknown URI " +
uri);
}
if (sortOrder == null || sortOrder == "") {
sortOrder = id;
}
Cursor c = qb.query(db, projection, selection, selectionArgs
, null,
null, sortOrder);
c.setNotificationUri(getContext().getContentResolver(), uri)
;
return c;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
long rowID = db.insert(TABLE_NAME, "", values);
if (rowID > 0) {
Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID
);
getContext().getContentResolver().notifyChange(_uri, nul
l);
return _uri;
}
throw new SQLiteException("Failed to add a record into " + u
ri);
}
@Override
public int update(Uri uri, ContentValues values, String selectio
n,
String[] selectionArgs) {
int count = 0;
switch (uriMatcher.match(uri)) {
case uriCode:
count = db.update(TABLE_NAME, values, selection, sel
ectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " +
uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
@Override
public int delete(Uri uri, String selection, String[] selectionA
rgs) {
int count = 0;
switch (uriMatcher.match(uri)) {
case uriCode:
count = db.delete(TABLE_NAME, selection, selectionAr
gs);
break;
default:
throw new IllegalArgumentException("Unknown URI " +
uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
private SQLiteDatabase db;
static final String DATABASE_NAME = "EmpDB";
static final String TABLE_NAME = "Employees";
static final int DATABASE_VERSION = 1;
static final String CREATE_DB_TABLE = " CREATE TABLE " + TABLE_N
AME
+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ " name TEXT NOT NULL);";

private static class DatabaseHelper extends SQLiteOpenHelper {


DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_DB_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
Output –

You might also like