BCA / B.Tech 14 min read

Sharing Data with Content Providers in HIndi

RK

लेखक Ratan Kumawat · संस्थापक, NotesMedia

प्रकाशित:

त्वरित सारांश और मुख्य बिंदु

  • • विषय फोकस: Android Programming notes in Hindi | एंड्राइड प्रोग्रामिंग नोट्स हिंदी में (BCA / B.Tech Syllabus)
  • • मुख्य विषय: Sharing Data with Content Providers in HIndi - General Topics
  • • अवलोकन: Quick Answer: Android mein Content Provider ek standard component hai jo alag-alag applications ke beech structured data securely share karne ke liye us...
  • • मुख्य अवधारणाएं: Android ContentProvider, ContentResolver, share data between apps,Android ContentProvider, ContentResolver, share data between apps
Quick Answer: Android mein Content Provider ek standard component hai jo alag-alag applications ke beech structured data securely share karne ke liye use hota hai. Android ke security sandbox model ke karan ek application dusri application ke SQLite database ya files ko directly access nahi kar sakti. Content Provider ek abstraction layer provide karta hai jahan client application ContentResolver aur Content URI (jaise content://com.example.provider/users) ke zariye CRUD (Create, Read, Update, Delete) operations execute karti hai.

Android mein Content Provider ki Jarurat kyu hoti hai?

Android operating system security ke liye har application ko ek isolated Linux user ID aur sandbox environment deta hai. Iska matlab hai ki App-A ka private SQLite database App-B ke liye completely inaccessible hota hai. Agar aapne local storage ke baare mein padha hai (jaise hamara Data Persistence Preferences and Files note), toh aap jante honge ki internal files private hoti hain.

Lekin real-world scenarios mein apps ko aapas mein data share karna padta hai:

  • WhatsApp ya Truecaller ko system ke Contacts access karne hote hain.
  • Gallery app ko camera app ke photos access karne hote hain.
  • E-commerce apps ko device ke SMS ya media files access karne hote hain.

Android system is problem ko solve karne ke liye Content Provider provide karta hai. Yeh ek centralized interface banata hai jahan data owner app access rules define karti hai aur permission-controlled access allow karti hai.

Advertisement

Content Provider Architecture ke Core Components

Content Provider architecture teen main components par kaam karta hai:

  1. Content URI (Uniform Resource Identifier): Yah data ko uniquely identify karne wala address hota hai.
  2. ContentResolver: Client application direct provider se baat nahi karti; wah apne context se getContentResolver() call karke request dispatch karti hai.
  3. ContentProvider Class: Data owner app is class ko extend karti hai aur raw data source (SQLite database, network ya file) se interact karti hai.

Content URI ka Structure

Har content request ek specific URI format follow karti hai:

content://com.example.myapp.userprovider/users/5
\_____/   \____________________________/ \___/ \_/
   |                    |                  |    |
Scheme              Authority             Path RowId
  • Scheme: Hamesha content:// hota hai jo Android system ko batata hai ki yeh Content Provider request hai.
  • Authority: Unique string (usually package name + provider name) jo target provider ko identify karti hai.
  • Path: Table ya dataset ka naam (jaise users ya products).
  • RowId (Optional): Specific record number. Agar RowId na ho, toh yeh complete table ya collection ko target karta hai.

ContentProvider Class ke 6 Essential Methods

Jab aap custom Content Provider create karte hain, toh aapko android.content.ContentProvider ke 6 abstract methods implement karne padte hain:

Method Name Return Type Purpose
onCreate() boolean Provider initialize hota hai (jaise database helper object banana). Yah method fast hona chahiye, heavy database kaam yahan avoid karein. Success par true return karta hai.
query() Cursor Data read karta hai aur result set Cursor ke form mein client ko return karta hai.
insert() Uri Naya record insert karta hai aur newly created record ka complete URI return karta hai.
update() int Existing records ko modify karta hai aur affected rows ka count return karta hai.
delete() int Specified criteria ke records delete karta hai aur deleted count return karta hai.
getType() String URI ke corresponding MIME type return karta hai (single record ya directory/collection).

Custom Content Provider Create karne ke Step-by-Step Steps

Step 1: Contract Class Define karein

Contract class URI constants aur database columns ko ek clean place par organize karti hai:

public final class UserContract {
    private UserContract() {}

    public static final String AUTHORITY = "com.notesmedia.userprovider";
    public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + AUTHORITY);
    public static final String PATH_USERS = "users";

    public static final class UserEntry {
        public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_USERS).build();
        public static final String TABLE_NAME = "users_table";
        public static final String COL_ID = "_id";
        public static final String COL_NAME = "user_name";
        public static final String COL_EMAIL = "user_email";
    }
}

Step 2: ContentProvider Class Implement karein

Yahan hum UriMatcher ka use karke incoming URIs ko match karte hain:

public class CustomUserProvider extends ContentProvider {

    private static final int CODE_USERS = 100;
    private static final int CODE_USER_ITEM = 101;
    private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

    static {
        uriMatcher.addURI(UserContract.AUTHORITY, UserContract.PATH_USERS, CODE_USERS);
        uriMatcher.addURI(UserContract.AUTHORITY, UserContract.PATH_USERS + "/#", CODE_USER_ITEM);
    }

    private SQLiteDatabase dbHelper;

    @Override
    public boolean onCreate() {
        // Local SQLite helper instance create karna
        DatabaseOpenHelper helper = new DatabaseOpenHelper(getContext());
        dbHelper = helper.getWritableDatabase();
        return dbHelper != null;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        int matchCode = uriMatcher.match(uri);
        Cursor cursor;
        if (matchCode == CODE_USERS) {
            cursor = dbHelper.query(UserContract.UserEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
        } else if (matchCode == CODE_USER_ITEM) {
            String rowNum = uri.getLastPathSegment();
            cursor = dbHelper.query(UserContract.UserEntry.TABLE_NAME, projection, UserContract.UserEntry.COL_ID + "=?", new String[]{rowNum}, null, null, sortOrder);
        } else {
            throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        cursor.setNotificationUri(getContext().getContentResolver(), uri);
        return cursor;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        long newRecordId = dbHelper.insert(UserContract.UserEntry.TABLE_NAME, null, values);
        if (newRecordId > 0) {
            Uri returnUri = ContentUris.withAppendedId(UserContract.UserEntry.CONTENT_URI, newRecordId);
            getContext().getContentResolver().notifyChange(uri, null);
            return returnUri;
        }
        throw new SQLException("Failed to insert row into " + uri);
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        int rowsUpdated = dbHelper.update(UserContract.UserEntry.TABLE_NAME, values, selection, selectionArgs);
        if (rowsUpdated != 0) {
            getContext().getContentResolver().notifyChange(uri, null);
        }
        return rowsUpdated;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        int rowsDeleted = dbHelper.delete(UserContract.UserEntry.TABLE_NAME, selection, selectionArgs);
        if (rowsDeleted != 0) {
            getContext().getContentResolver().notifyChange(uri, null);
        }
        return rowsDeleted;
    }

    @Override
    public String getType(Uri uri) {
        int match = uriMatcher.match(uri);
        if (match == CODE_USERS) {
            return "vnd.android.cursor.dir/" + UserContract.AUTHORITY + "." + UserContract.PATH_USERS;
        } else if (match == CODE_USER_ITEM) {
            return "vnd.android.cursor.item/" + UserContract.AUTHORITY + "." + UserContract.PATH_USERS;
        }
        throw new IllegalArgumentException("Unsupported URI: " + uri);
    }
}
Advertisement

Step 3: AndroidManifest.xml mein Register karein

Content Provider ko Android system mein declare karna mandatory hota hai. Iske details ke liye hamara What is AndroidManifest.xml in Hindi guide padhein:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.notesmedia.userprovider">

    <application>
        <provider
            android:name=".CustomUserProvider"
            android:authorities="com.notesmedia.userprovider"
            android:exported="true" />
    </application>
</manifest>

Step 4: Client Application se Data Access karna

Dusri application se data query karne ke liye ContentResolver use kiya jata hai. Android 11 (API 30) ya usse upar target karne wali client app ko apne manifest mein <queries><provider android:authorities="com.notesmedia.userprovider" /></queries> declare karna padta hai (package visibility rule):

Uri targetUri = Uri.parse("content://com.notesmedia.userprovider/users");
Cursor cursor = getContentResolver().query(targetUri, null, null, null, null);

if (cursor != null) {
    while (cursor.moveToNext()) {
        int nameIndex = cursor.getColumnIndex("user_name");
        String name = cursor.getString(nameIndex);
        Log.d("ClientApp", "User Name: " + name);
    }
    cursor.close();
}

Android Data Storage Mechanisms ka Comparison

Storage Mechanism Data Type Cross-App Sharing Primary Use Case
SharedPreferences Key-Value pairs (primitive types) No (Private to App) User settings, UI theme, auth tokens
SQLite / Room Database Structured relational tables No (Sandbox isolated) Complex app-specific offline data
Internal Storage Files Raw bytes, images, text files No Private cached files, downloads
Content Provider Structured relational / Streams Yes (Secure IPC sharing) Contacts, media files, inter-app data sharing

Content Provider Security Best Practices

  • Set android:exported="false" by Default: Agar aapka provider sirf aapki apni app ke multiple processes ke beech use ho raha hai, toh external apps ke liye access band rakhein.
  • Permissions Enforce karein: Custom permissions (jaise readPermission aur writePermission) declare karein taaki sirf authorized apps hi sensitive data read ya write kar sakein.
  • SQL Injection se Bachen: Direct string concatenation ki jagah parameterized queries (jaise selectionArgs) ka use karein.

Exam के लिए Important Questions

Short Questions

  1. Android mein ContentResolver ka kya kaam hota hai?
    ContentResolver client application ko ContentProvider ke saath communicate karne ke liye standardized API methods (query, insert, update, delete) provide karta hai.
  2. Content URI ke main parts kaunse hote hain?
    Scheme (content://), Authority (provider identifier), Path (data entity) aur Optional ID (specific row identifier).
  3. UriMatcher class ka purpose kya hai?
    UriMatcher incoming URI patterns ko predefined integer codes se match karke identify karta hai ki client single row demand kar raha hai ya poori table.
  4. getType() method kya return karta hai?
    Yah given URI ke data ka MIME type return karta hai, jaise cursor directory (multiple rows) ya cursor item (single row).

Long Questions

  1. Content Provider kya hai? Android application security sandbox aur inter-app communication mein iske role ko detail mein explain karein.
  2. Ek custom Content Provider create karne ke complete lifecycle steps ko suitable Java code aur manifest configuration ke saath samjhaiye.
  3. Android mein local data storage mechanisms (SharedPreferences, SQLite aur Content Providers) ke beech practical comparison draw karein.

Frequently Asked Questions (FAQs)

Q1: Kya hum bina SQLite ke Content Provider bana sakte hain?
Ans: Ha, Content Provider ek abstraction layer hai. Iske peeche data source SQLite, local files, JSON cache ya remote cloud server bhi ho sakta hai.

Q2: Kya ek app dusri app ka database bina permission read kar sakti hai?
Ans: Nahi, Android sandbox model direct access block karta hai. External app sirf tabhi data access kar sakti hai jab target app ka Content Provider exported ho aur required permissions granted hon.

Q3: Content Provider main thread par run hota hai ya background thread par?
Ans: Agar client aur provider same process mein hain, toh provider ke methods calling thread par hi chalte hain. Doosri app (alag process) se call aane par yah provider app ke binder thread pool par chalte hain, lekin client ka thread result aane tak block rehta hai. Isliye client UI thread se heavy query na kare, warna ANR (Application Not Responding) aa sakta hai; queries background thread (jaise Coroutines ya Executor) se karni chahiye.

Q4: notifyChange() method kyu call kiya jata hai?
Ans: Data change hone par notifyChange() registered observers (jaise UI loaders ya live data listeners) ko alert karta hai taaki UI automatically update ho sake.

अक्सर पूछे जाने वाले प्रश्न (FAQs)

Quick Answer: Android mein Content Provider ek standard component hai jo alag-alag applications ke beech structured data securely share karne ke liye use hota hai.
Android Programming notes in Hindi | एंड्राइड प्रोग्रामिंग नोट्स हिंदी में के पाठ्यक्रम में Sharing Data with Content Providers in HIndi एक महत्वपूर्ण अध्याय है। यह मुख्य सिद्धांतों, परीक्षा प्रश्नों और सूत्रों को समझने के लिए अत्यधिक आवश्यक है।
हाँ, NotesMedia पर आपको Sharing Data with Content Providers in HIndi के महत्वपूर्ण प्रश्नोत्तर, हल किए गए उदाहरण और नोट्स बिल्कुल मुफ्त मिलेंगे। अधिक अभ्यास के लिए आप हमारा ऐप भी डाउनलोड कर सकते हैं।
Advertisement