A content provider component supplies data from one application to others on request. Such requests are handled by the methods of the ContentResolver class. A content provider can use different ways to store its data and the data can be stored in a database, in files, or even over a network.
Content providers let you centralize content in one place and have many different applications access it as needed. A content provider behaves very much like a database where you can query it, edit its content, as well as add or delete content using insert(), update(), delete(), and query() methods. In most cases this data is stored in an SQlite database.
A content provider is implemented as a subclass of ContentProvider class and must implement a standard set of APIs that enable other applications to perform transactions.
1 2 3 |
public class Custom_ContentProvider extends ContentProvider { } |
To query a content provider, you specify the query string in the form of a URI which has following format:
1 |
<prefix>://<authority>/<data_type>/<id> |
Here is the detail of various parts of the URI –
Part | Description |
---|---|
prefix | This is always set to content:// |
authority | This specifies the name of the content provider, for example contacts, browser etc. For third-party content providers, this could be the fully qualified name, such as com.androhub.statusprovider |
data_type | This indicates the type of data that this particular provider provides. For example, if you are getting all the contacts from the Contacts content provider, then the data path would be people and URI would look like this content://contacts/people |
id | This specifies the specific record requested. For example, if you are looking for contact number 5 in the Contacts content provider then URI would look like this content://contacts/people/5. |
This involves number of simple steps to create your own content provider.
Here is the list of methods which you need to override in Content Provider class to have your Content Provider working:
In last tutorial we had covered the topic how to fetch the contact details from phone contacts using content provider i.e. inbuilt content provider. In this tutorial we are going to create our custom content provider.
In this tutorial, we are going to learn how to create custom content provider and how to fetch the data from this content provider from another app.
1. Create a new project in Eclipse by navigating to File ⇒ New Android ⇒ Application Project and fill required details. By default my activity is MainActivity.java.
2. Open res ⇒ values ⇒ strings.xml and add below string values. This are some strings that i am going to use in this tutorial.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">ContentProvider Example</string> <string name="hello_world">Hello world!</string> <string name="menu_settings">Settings</string> <string name="name">Enter Name</string> <string name="email">Enter email id</string> <string name="contact">Enter conctact number</string> <string name="add">Add Data</string> <string name="save_data">Save Data using Content Provider</string> <string name="click">Click on Button to Show all Saved Data</string> <string name="show">Show Data</string> </resources> |
3. Now, create a new java class naming Custom_ContentProvider.java extending ContentProvider. In this java class we put all queries like insert, update, delete and query. We also created a sqlite database to store the data.
If you are unaware of sqlite database you can check the tutorial here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 |
package com.contentprovider_demo; import java.util.HashMap; 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.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; public class Custom_ContentProvider extends ContentProvider { static final String PROVIDER_NAME = "com.contentprovider_demo.Custom_ContentProvider";// Provider // name static final String URL = "content://" + PROVIDER_NAME + "/androhub";// Provider // url static final Uri CONTENT_URI = Uri.parse(URL);// Contnet Uri in URI format // All fields of database static final String id = "id"; static final String name = "name"; static final String email = "email"; static final String number = "number"; // Uri code static final int uriCode = 1; static final UriMatcher uriMatcher; private static HashMap<String, String> values; static { // Match the uri code to provider name uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(PROVIDER_NAME, "androhub", uriCode); uriMatcher.addURI(PROVIDER_NAME, "androhub/*", uriCode); } // detele uri method @Override public int delete(Uri uri, String selection, String[] selectionArgs) { int count = 0;// Count to tell how many rows deleted switch (uriMatcher.match(uri)) { case uriCode: count = db.delete(TABLE_NAME, selection, selectionArgs); break; default: count = 0; throw new IllegalArgumentException("Unknown URI " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } // return type of content provider @Override public String getType(Uri uri) { switch (uriMatcher.match(uri)) { case uriCode: return "vnd.android.cursor.dir/androhub"; default: throw new IllegalArgumentException("Unsupported URI: " + uri); } } // Insert method @Override public Uri insert(Uri uri, ContentValues values) { long rowID = db.insert(TABLE_NAME, "", values);// Insert data into // database // If row id is greater than 0 then notify content provider if (rowID > 0) { Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID); getContext().getContentResolver().notifyChange(_uri, null); return _uri; } throw new SQLException("Failed to add a record into " + uri); } @Override public boolean onCreate() { Context context = getContext(); DatabaseHelper dbHelper = new DatabaseHelper(context); db = dbHelper.getWritableDatabase(); if (db != null) { return true; } return false; } // Read all data method @Override public Cursor query(Uri uri, String[] projection, String selection, 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 = name; } Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder); c.setNotificationUri(getContext().getContentResolver(), uri); return c; } // Update data @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { int count = 0;// Count to tell number of rows updated switch (uriMatcher.match(uri)) { case uriCode: count = db.update(TABLE_NAME, values, selection, selectionArgs); break; default: count = 0; throw new IllegalArgumentException("Unknown URI " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } /** SqlLite Database **/ private SQLiteDatabase db; static final String DATABASE_NAME = "ContentProvider_Database";// Database // name static final String TABLE_NAME = "User_Details";// Table Name static final int DATABASE_VERSION = 1;// Database Version static final String CREATE_DB_TABLE = " CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY AUTOINCREMENT, " + name + " TEXT NOT NULL, " + email + " TEXT NOT NULL, " + number + " TEXT NOT NULL" + " );"; // Create table query 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);// Create table } // On database version upgrade create new table @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); onCreate(db); } } } |
4. After creating custom content provider we have to put it into manifest file inside provider tag.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.contentprovider_demo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="22" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.contentprovider_demo.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <provider android:name="com.contentprovider_demo.Custom_ContentProvider" android:authorities="com.contentprovider_demo.Custom_ContentProvider" android:exported="true" android:multiprocess="true" > </provider> </application> </manifest> |
5. Now create a basic xml layout naming activity_main.xml. In this layout i put some edittext and two buttons.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ffffff" android:fillViewport="true" > <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical" android:padding="5dp" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:gravity="center" android:padding="10dp" android:text="@string/save_data" android:textColor="#F44336" android:textSize="20sp" android:textStyle="bold" /> <EditText android:id="@+id/txtName" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:hint="@string/name" android:inputType="textCapWords" android:padding="10dp" /> <EditText android:id="@+id/txtEmail" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:hint="@string/email" android:inputType="textEmailAddress" android:padding="10dp" /> <EditText android:id="@+id/txtContact" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:hint="@string/contact" android:inputType="number" android:padding="10dp" /> <Button android:id="@+id/btnAdd" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:padding="5dp" android:text="@string/add" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:gravity="center" android:padding="10dp" android:text="@string/click" android:textColor="#F44336" android:textSize="20sp" android:textStyle="bold" /> <Button android:id="@+id/btnShow" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:padding="5dp" android:text="@string/show" /> <TextView android:id="@+id/result" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:padding="10dp" android:textColor="#000000" android:textSize="15sp" /> </LinearLayout> </ScrollView> |
6. Finally come to MainActivity.java and add the following code to it. In this java class we have two onClickListener buttons :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
package com.contentprovider_demo; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private static EditText name, email, number; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); name = (EditText) findViewById(R.id.txtName); email = (EditText) findViewById(R.id.txtEmail); number = (EditText) findViewById(R.id.txtContact); findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { // Get all text fields into string String getName = name.getText().toString(); String getEmail = email.getText().toString(); String getNumber = number.getText().toString(); // Check if all fields are not null if (!getName.equals("") && getName.length() != 0 && !getEmail.equals("") && getEmail.length() != 0 && !getNumber.equals("") && getNumber.length() != 0) { onClickAddData(getName, getEmail, getNumber);// Add data // empty all fields name.setText(""); email.setText(""); number.setText(""); } // else show toast else Toast.makeText(MainActivity.this, "Please fill all details.", Toast.LENGTH_SHORT) .show(); } }); findViewById(R.id.btnShow).setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { TextView resultView = (TextView) findViewById(R.id.result); Cursor cursor = getContentResolver().query( Custom_ContentProvider.CONTENT_URI, null, null, null, null);// Get cursor // Check if it is null or not if (cursor != null && cursor.moveToFirst()) { StringBuilder result = new StringBuilder(); // Loop to all items while (!cursor.isAfterLast()) { // Add data to string builder result.append("Id - " + cursor.getString(cursor.getColumnIndex("id")) + "nName - " + cursor.getString(cursor .getColumnIndex("name")) + "nEmail - " + cursor.getString(cursor .getColumnIndex("email")) + "nContact Number - " + cursor.getString(cursor .getColumnIndex("number")) + "nn"); cursor.moveToNext(); } resultView.setText(result);// finally set string builder to // textview } else { // if cursor is null then set data empty resultView.setText("Empty data!!"); } } }); } // Add data method private void onClickAddData(String name, String email, String number) { ContentValues values = new ContentValues();// Content values to add data values.put(Custom_ContentProvider.name, name); values.put(Custom_ContentProvider.email, email); values.put(Custom_ContentProvider.number, number); Uri uri = getContentResolver().insert( Custom_ContentProvider.CONTENT_URI, values);// Insert data to // content provider Toast.makeText(getBaseContext(), "New Data Inserted.", Toast.LENGTH_LONG).show(); } } |
7. Finally you are done with custom content provider example.
1. Create a new project in Eclipse by navigating to File ⇒ New Android ⇒ Application Project and fill required details. By default my activity is MainActivity.java.
2. Open res ⇒ values ⇒ strings.xml and add below string values. This are some strings that i am going to use in this tutorial.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">ContentProviderUser Example</string> <string name="hello_world">Hello world!</string> <string name="menu_settings">Settings</string> <string name="show_data">Show Data</string> <string name="fetch">Fetch Data from Content Provider</string> <string name="id">Enter Id</string> <string name="update">Update</string> <string name="delete">Delete</string> <string name="update_delete">Enter Id to Update/Delete Data</string> <string name="insert">Insert</string> <string name="insert_data">Click to Insert New Data</string> </resources> |
3. Create a xml layout naming activity_main.xml. This layout contains some buttons for showing data, inserting new data, update data and delete data.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ffffff" android:fillViewport="true" > <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="5dp" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:gravity="center" android:padding="10dp" android:text="@string/fetch" android:textColor="#F44336" android:textSize="20sp" android:textStyle="bold" /> <Button android:id="@+id/btnRetrieve" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:padding="5dp" android:text="@string/show_data" /> <TextView android:id="@+id/result" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:clickable="false" android:padding="5dp" android:textColor="#000000" android:textSize="15sp" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:gravity="center" android:padding="10dp" android:text="@string/update_delete" android:textColor="#F44336" android:textSize="20sp" android:textStyle="bold" /> <EditText android:id="@+id/id" android:layout_width="fill_parent" android:layout_height="wrap_content" android:focusableInTouchMode="true" android:hint="@string/id" android:inputType="number" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <Button android:id="@+id/btnUpdate" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:layout_weight="1" android:padding="5dp" android:text="@string/update" /> <Button android:id="@+id/btnDelete" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:layout_weight="1" android:padding="5dp" android:text="@string/delete" /> </LinearLayout> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:gravity="center" android:padding="10dp" android:text="@string/insert_data" android:textColor="#F44336" android:textSize="20sp" android:textStyle="bold" /> <Button android:id="@+id/btnInsert" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:padding="5dp" android:text="@string/insert" /> </LinearLayout> </ScrollView> |
4. Now, create a new class naming Random_Datas.java that contains three string array for adding new data inside content provider.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package com.contentprovider_user_demo; public class Random_Datas { /** Strings array to insert/update data in Content Provider **/ public static final String[] Name = { "Androhub", "Andrew", "Philip", "Sachin", "New User", "Guest" }; public static final String[] Number = { "9008091221", "9977112561", "908456124", "8904561245", "8953234903", "7845362793" }; } |
5. Finally come to your MainActivity.java and follow some steps while fetching data from custom provider app.
1 |
private static final String uri = "content://com.contentprovider_demo.Custom_ContentProvider/androhub"; |
Final source code of MainActivity.java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 |
package com.contentprovider_user_demo; import java.util.Random; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor>, OnClickListener { private static TextView resultView; private static EditText id; private static Button retrieve, update, delete, insert; private static CursorLoader cursorLoader; private static final String uri = "content://com.contentprovider_demo.Custom_ContentProvider/androhub";// Content // URI @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Find Ids resultView = (TextView) findViewById(R.id.result); id = (EditText) findViewById(R.id.id); retrieve = (Button) findViewById(R.id.btnRetrieve); update = (Button) findViewById(R.id.btnUpdate); delete = (Button) findViewById(R.id.btnDelete); insert = (Button) findViewById(R.id.btnInsert); // Implement click listener retrieve.setOnClickListener(this); update.setOnClickListener(this); delete.setOnClickListener(this); insert.setOnClickListener(this); } // On click call representative methods @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnRetrieve: onClickDisplayData();// Fetch data break; case R.id.btnUpdate: // Update data according to Id String getId = id.getText().toString(); if (!getId.equals("") && getId.length() != 0) updateData(new String[] { getId }); else Toast.makeText(MainActivity.this, "Id is empty.", Toast.LENGTH_SHORT).show(); break; case R.id.btnDelete: // Delete data according to Id String getId_ = id.getText().toString(); if (!getId_.equals("") && getId_.length() != 0) deleteData(new String[] { getId_ }); else Toast.makeText(MainActivity.this, "Id is empty.", Toast.LENGTH_SHORT).show(); break; case R.id.btnInsert: // Insert data insertData(); break; } } private void onClickDisplayData() { // Initate loader manager getSupportLoaderManager().initLoader(1, null, this); } @Override public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) { try { cursorLoader = new CursorLoader(this, Uri.parse(uri), null, null, null, null);// Get cursor loader from URI } catch (NullPointerException e) { // if exception occurs toast occurs Toast.makeText( MainActivity.this, "There is no app found corresponding to your content provider.", Toast.LENGTH_LONG).show(); } catch (Exception e) { Toast.makeText(MainActivity.this, "Error in fetching data. Try again.", Toast.LENGTH_SHORT) .show(); e.printStackTrace(); } return cursorLoader; } @Override public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) { // First check if cursor is not null if (cursor != null && cursor.moveToFirst()) { StringBuilder result = new StringBuilder(); // Now loop to all items and append it to string builder while (!cursor.isAfterLast()) { result.append("Id - " + cursor.getString(cursor.getColumnIndex("id")) + "nName - " + cursor.getString(cursor.getColumnIndex("name")) + "nEmail - " + cursor.getString(cursor.getColumnIndex("email")) + "nContact Number - " + cursor.getString(cursor.getColumnIndex("number")) + "nn"); cursor.moveToNext(); } resultView.setText(result);// Finally set string builder to textview } else { // If cursor is null then display toast and set empty data. resultView.setText("Empty data!!"); Toast.makeText( MainActivity.this, "May be there is no app corresponding to your provider or there is null data.", Toast.LENGTH_LONG).show(); } } @Override public void onLoaderReset(Loader<Cursor> arg0) { } // Random int value generator method between 0-5 private int RandomInt() { Random random = new Random(); int randomValue = random.nextInt(5); return randomValue; } // Update data method private void updateData(String[] id) { Cursor cursor = getContentResolver().query(Uri.parse(uri), null, null, null, null);// Get cursor from Uri // If cursor is not null then update data else show toast if (cursor != null) { int randomValue = RandomInt();// Get random integer ContentValues values = new ContentValues();// Content values to // insert data values.put("name", Random_Datas.Name[randomValue]);// add data from // RandomDatas // class values.put("email", Random_Datas.Email[randomValue]); values.put("number", Random_Datas.Number[randomValue]); int count = getContentResolver().update(Uri.parse(uri), values, "id = ?", id);// now update provider using ID // If count is not 0 then row is updated else no row is updated if (count != 0) Toast.makeText(MainActivity.this, "Row updated", Toast.LENGTH_LONG).show(); else Toast.makeText( MainActivity.this, "May be there is no row to update or the id you pass is not present in database.", Toast.LENGTH_LONG).show(); } else { Toast.makeText( MainActivity.this, "May be there is no app corresponding to your provider or there is null data.", Toast.LENGTH_LONG).show(); } } // Delete data private void deleteData(String[] id) { // Firstly get the cursor then check if it is null or not Cursor cursor = getContentResolver().query(Uri.parse(uri), null, null, null, null); if (cursor != null) { int count = getContentResolver().delete(Uri.parse(uri), "id = ? ", id);// Delete row according to id if (count != 0) Toast.makeText(MainActivity.this, "Row deleted", Toast.LENGTH_LONG).show(); else Toast.makeText( MainActivity.this, "May be there is no row to delete or the id you pass is not present in database.", Toast.LENGTH_LONG).show(); } else { Toast.makeText( MainActivity.this, "May be there is no app corresponding to your provider or there is null data.", Toast.LENGTH_LONG).show(); } } // Insert random data private void insertData() { Cursor cursor = getContentResolver().query(Uri.parse(uri), null, null, null, null); // First check if cursor is null or not if (cursor != null) { int randomValue = RandomInt(); ContentValues values = new ContentValues(); values.put("name", Random_Datas.Name[randomValue]); values.put("email", Random_Datas.Email[randomValue]); values.put("number", Random_Datas.Number[randomValue]); Uri uri_ = getContentResolver().insert(Uri.parse(uri), values);// Now // add // the // content // values // to // content // provider Toast.makeText(MainActivity.this, "Data inserted.", Toast.LENGTH_LONG).show(); } else { Toast.makeText(MainActivity.this, "May be there is no app corresponding to your provider.", Toast.LENGTH_LONG).show(); } } @Override public void onDestroy() { super.onDestroy(); } } |
6. Finally you are done with this example also.
Now you can use both example and run the app and you will get the output as shown in the video.
Thanks.
Subscribe to us and get the latest news.
1 Comment
james
Sunday, October 8th, 2023i like your beard – git hub prof pic