Blog

Android – Kontent-provayderlar

Uncategorized @uz

Android – Kontent-provayderlar

Kontent-provayder komponenti so’rov bo’yicha bitta dasturdan boshqalarga ma’lumotlarni etkazib beradi. Bunday so’rovlar ContentResolver sinfining usullari bilan ishlaydi. Kontent-provayder o’z ma’lumotlarini saqlash uchun turli xil usullardan foydalanishi mumkin va ma’lumotlar ma’lumotlar bazasida, fayllarda yoki hatto tarmoq orqali saqlanishi mumkin.

kontent-provayder

ContentProvider

ba’zida dasturlar bo’yicha ma’lumotlarni almashish talab etiladi. Bu erda kontent-provayderlar juda foydali bo’ladi.

Kontent-provayderlar tarkibni bir joyda markazlashtirishga imkon beradi va kerak bo’lganda turli xil dasturlardan foydalanishga imkon beradi. Kontent-provayder ma’lumotlar bazasi kabi ishlaydi, bu erda siz uni so’rashingiz, tarkibini tahrirlashingiz, shuningdek insert (), update (), delete () va query () usullaridan foydalanib tarkib qo’shishingiz yoki o’chirishingiz mumkin. Ko’pgina hollarda ushbu ma’lumotlar SQlite-da saqlanadi

Kontent-provayder ContentProvider sinfining subklassi sifatida amalga oshiriladi va boshqa dasturlarga tranzaktsiyalarni amalga oshirishga imkon beradigan standart API to’plamini amalga oshirishi kerak.

public class My Application extends  ContentProvider {
}

Kontent URI-lari

Kontent-provayderga murojaat qilish uchun siz so’rovlar satrini URI shaklida ko’rsatasiz, u quyidagi formatga ega –

<prefix>://<authority>/<data_type>/<id>

URI ning turli qismlari haqida batafsil ma’lumot –

N.Qism va tavsif
1prefiks

Bu har doim tarkibga o’rnatiladi: //

2authority

Bu kontent provayderining nomini belgilaydi, masalan, kontaktlar , brauzer va boshqalar. Uchinchi tomon kontent provayderlari uchun bu to’liq malakali ism bo’lishi mumkin, masalan com.tutorialspoint.statusprovider

3data_type

Bu aniq provayder taqdim etadigan ma’lumotlar turini ko’rsatadi. Masalan, siz Kontaktlar kontent-provayderidan barcha kontaktlarni olayotgan bo’lsangiz , ma’lumotlar yo’li odamlar bo’lishi mumkin va URI quyidagi tarkibga o’xshaydi : // contacts / people

4id

Bu so’ralgan maxsus yozuvni belgilaydi. Masalan, Kontaktlar provayderidan 5-raqamni qidirsangiz, URI quyidagi tarkibga o’xshaydi : // contacts / people / 5 .

Tarkibni etkazib beruvchini yarating

Bu o’zingizning kontent-provayderingizni yaratish uchun bir qator oddiy qadamlarni o’z ichiga oladi.

  • Avvalo ContentProviderbaseclass-ni kengaytiradigan Content Provider sinfini yaratishingiz kerak .
  • Ikkinchidan, tarkibga kirish uchun ishlatiladigan kontent-provayderingizning URI manzilini belgilashingiz kerak.
  • Keyin tarkibni saqlash uchun o’zingizning ma’lumotlar bazangizni yaratishingiz kerak bo’ladi. Odatda, Android SQLite ma’lumotlar bazasidan foydalanadi va uning asosi provayder ma’lumotlar bazasini yaratish yoki ochish uchun SQLite Open Helper usulidan foydalanadigan onCreate () usulini bekor qilishi kerak . Sizning arizangiz ishga tushirilganda, uning tarkibidagi har bir provayderning onCreate () ishlovchisi asosiy dastur satrida chaqiriladi.
  • Keyinchalik, ma’lumotlar bazasiga oid turli xil operatsiyalarni bajarish uchun Kontent-provayder so’rovlarini bajarishingiz kerak bo’ladi.
  • Va nihoyat <provider> yorlig’i yordamida Kontent-provayderingizni faoliyat faylingizga ro’yxatdan o’tkazing.

Tarkibni etkazib beruvchini ishlashi uchun Kontent Provayderi sinfida bekor qilishingiz kerak bo’lgan usullar ro’yxati –

kontent-provayder

ContentProvider

  • onCreate () Ushbu usul provayder ishga tushirilganda chaqiriladi.
  • query () Ushbu usul mijozdan so’rov qabul qiladi. Natija Kursor ob’ekti sifatida qaytariladi.
  • insert () Ushbu usul tarkibni etkazib beruvchiga yangi yozuv kiritadi.
  • delete () Ushbu usul kontent provayderidan mavjud bo’lgan yozuvni o’chiradi.
  • update () Ushbu usul tarkibni etkazib beruvchidan mavjud bo’lgan yozuvni yangilaydi.
  • getType () Ushbu usul berilgan URI da ma’lumotlarning MIME turini qaytaradi.

Misol

Ushbu misol sizga o’zingizning ContentProvider-ni qanday yaratishni tushuntiradi . Shunday qilib, keling, Hello World Example-ni yaratishda qanday amal qilganimizga o’xshash quyidagi amallarni bajaring –

QadamTavsif
1Siz Android dasturini yaratishda va » com.example.MyApplication» to’plami ostida » Faolliksiz» to’plam ostida » Mening ilovam» deb nomlashda Android StudioIDE-dan foydalanasiz .
2Asosiy faoliyati fayl o’zgartirish MainActivity.java ikki yangi usullarini kiritish uchun onClickAddName () va onClickRetrieveStudents () .
3Deb nomlangan yangi java fayl yaratish StudentsProvider.java paketi ostida com.example.MyApplication sizning haqiqiy provayderga va bog’liq usullarini aniqlash uchun.
4<Provayder … /> yorlig’i yordamida AndroidManifest.xml faylida kontent provayderingizni ro’yxatdan o’tkazing
5Res / layout / activity_main.xml faylining standart tarkibini talabalar yozuvlarini qo’shish uchun kichik GUI-ni kiritish uchun o’zgartiring.
6String.xml-ni o’zgartirishga hojat yo’q. Android studiyasi string.xml faylini parvarish qiladi.
7Run the application to launch Android emulator and verify the result of the changes done in the application.

Quyida src / com.example.MyApplication / MainActivity.java o’zgartirilgan asosiy faoliyat faylining mazmuni keltirilgan . Ushbu fayl hayot tsiklining asosiy usullaridan har birini o’z ichiga olishi mumkin. Foydalanuvchilarning dastur bilan o’zaro ta’sirini boshqarish uchun onClickAddName () va onClickRetrieveStudents () ikkita yangi usulni qo’shdik .

package com.example.MyApplication;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;

import android.content.ContentValues;
import android.content.CursorLoader;

import android.database.Cursor;

import android.view.Menu;
import android.view.View;

import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
   public void onClickAddName(View view) {
      // Add a new student record
      ContentValues values = new ContentValues();
      values.put(StudentsProvider.NAME,
         ((EditText)findViewById(R.id.editText2)).getText().toString());

      values.put(StudentsProvider.GRADE,
         ((EditText)findViewById(R.id.editText3)).getText().toString());

      Uri uri = getContentResolver().insert(
         StudentsProvider.CONTENT_URI, values);

      Toast.makeText(getBaseContext(),
         uri.toString(), Toast.LENGTH_LONG).show();
   }
   public void onClickRetrieveStudents(View view) {
      // Retrieve student records
      String URL = "content://com.example.MyApplication.StudentsProvider";

      Uri students = Uri.parse(URL);
      Cursor c = managedQuery(students, null, null, null, "name");

      if (c.moveToFirst()) {
         do{
            Toast.makeText(this,
               c.getString(c.getColumnIndex(StudentsProvider._ID)) +
                  ", " +  c.getString(c.getColumnIndex( StudentsProvider.NAME)) +
                     ", " + c.getString(c.getColumnIndex( StudentsProvider.GRADE)),
            Toast.LENGTH_SHORT).show();
         } while (c.moveToNext());
      }
   }
}

Com.example.MyApplication to’plami ostida StudentProvider.java yangi fayl yarating va quyidagi src / com.example.MyApplication / StudentsProvider.java

package com.example.MyApplication;

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;
import android.text.TextUtils;

public class StudentsProvider extends ContentProvider {
   static final String PROVIDER_NAME = "com.example.MyApplication.StudentsProvider";
   static final String URL = "content://" + PROVIDER_NAME + "/students";
   static final Uri CONTENT_URI = Uri.parse(URL);

   static final String _ID = "_id";
   static final String NAME = "name";
   static final String GRADE = "grade";

   private static HashMap<String, String> STUDENTS_PROJECTION_MAP;

   static final int STUDENTS = 1;
   static final int STUDENT_ID = 2;

   static final UriMatcher uriMatcher;
   static{
      uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
      uriMatcher.addURI(PROVIDER_NAME, "students", STUDENTS);
      uriMatcher.addURI(PROVIDER_NAME, "students/#", STUDENT_ID);
   }

   /**
      * Database specific constant declarations
   */
   
   private SQLiteDatabase db;
   static final String DATABASE_NAME = "College";
   static final String STUDENTS_TABLE_NAME = "students";
   static final int DATABASE_VERSION = 1;
   static final String CREATE_DB_TABLE =
      " CREATE TABLE " + STUDENTS_TABLE_NAME +
         " (_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
         " name TEXT NOT NULL, " +
         " grade TEXT NOT NULL);";

   /**
      * Helper class that actually creates and manages
      * the provider's underlying data repository.
   */
   
   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 " +  STUDENTS_TABLE_NAME);
         onCreate(db);
      }
   }

   @Override
   public boolean onCreate() {
      Context context = getContext();
      DatabaseHelper dbHelper = new DatabaseHelper(context);

      /**
         * Create a write able database which will trigger its
         * creation if it doesn't already exist.
      */
         
      db = dbHelper.getWritableDatabase();
      return (db == null)? false:true;
   }

   @Override
   public Uri insert(Uri uri, ContentValues values) {
      /**
         * Add a new student record
      */
      long rowID = db.insert(	STUDENTS_TABLE_NAME, "", values);

      /**
         * If record is added successfully
      */
      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 Cursor query(Uri uri, String[] projection, 
      String selection,String[] selectionArgs, String sortOrder) {
      SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
      qb.setTables(STUDENTS_TABLE_NAME);

      switch (uriMatcher.match(uri)) {
         case STUDENTS:
            qb.setProjectionMap(STUDENTS_PROJECTION_MAP);
         break;

         case STUDENT_ID:
            qb.appendWhere( _ID + "=" + uri.getPathSegments().get(1));
         break;
         
         default:   
      }

      if (sortOrder == null || sortOrder == ""){
         /**
            * By default sort on student names
         */
         sortOrder = NAME;
      }
      
      Cursor c = qb.query(db,	projection,	selection, 
         selectionArgs,null, null, sortOrder);
      /**
         * register to watch a content URI for changes
      */
      c.setNotificationUri(getContext().getContentResolver(), uri);
      return c;
   }

   @Override
   public int delete(Uri uri, String selection, String[] selectionArgs) {
      int count = 0;
      switch (uriMatcher.match(uri)){
         case STUDENTS:
            count = db.delete(STUDENTS_TABLE_NAME, selection, selectionArgs);
         break;

         case STUDENT_ID:
            String id = uri.getPathSegments().get(1);
            count = db.delete( STUDENTS_TABLE_NAME, _ID +  " = " + id +
               (!TextUtils.isEmpty(selection) ? " 
               AND (" + selection + ')' : ""), selectionArgs);
            break;
         default:
            throw new IllegalArgumentException("Unknown URI " + uri);
      }

      getContext().getContentResolver().notifyChange(uri, null);
      return count;
   }

   @Override
   public int update(Uri uri, ContentValues values, 
      String selection, String[] selectionArgs) {
      int count = 0;
      switch (uriMatcher.match(uri)) {
         case STUDENTS:
            count = db.update(STUDENTS_TABLE_NAME, values, selection, selectionArgs);
         break;

         case STUDENT_ID:
            count = db.update(STUDENTS_TABLE_NAME, values, 
               _ID + " = " + uri.getPathSegments().get(1) +
               (!TextUtils.isEmpty(selection) ? " 
               AND (" +selection + ')' : ""), selectionArgs);
            break;
         default:
            throw new IllegalArgumentException("Unknown URI " + uri );
      }
        
      getContext().getContentResolver().notifyChange(uri, null);
      return count;
   }

   @Override
   public String getType(Uri uri) {
      switch (uriMatcher.match(uri)){
         /**
            * Get all student records
         */
         case STUDENTS:
            return "vnd.android.cursor.dir/vnd.example.students";
         /**
            * Get a particular student
         */
         case STUDENT_ID:
            return "vnd.android.cursor.item/vnd.example.students";
         default:
            throw new IllegalArgumentException("Unsupported URI: " + uri);
      }
   }
}

Following will the modified content of AndroidManifest.xml file. Here we have added <provider…/> tag to include our content provider:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.MyApplication">

   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
         <activity android:name=".MainActivity">
            <intent-filter>
               <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
         </activity>
        
      <provider android:name="StudentsProvider"
         android:authorities="com.example.MyApplication.StudentsProvider"/>
   </application>
</manifest>

Res / layout / activity_main.xml faylining mazmuni quyidagicha bo’ladi

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context="com.example.MyApplication.MainActivity">

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Content provider"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:textSize="30dp" />

   <TextView
      android:id="@+id/textView2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point "
      android:textColor="#ff87ff09"
      android:textSize="30dp"
      android:layout_below="@+id/textView1"
      android:layout_centerHorizontal="true" />

   <ImageButton
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageButton"
      android:src="@drawable/abc"
      android:layout_below="@+id/textView2"
      android:layout_centerHorizontal="true" />

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/button2"
      android:text="Add Name"
      android:layout_below="@+id/editText3"
      android:layout_alignRight="@+id/textView2"
      android:layout_alignEnd="@+id/textView2"
      android:layout_alignLeft="@+id/textView2"
      android:layout_alignStart="@+id/textView2"
      android:onClick="onClickAddName"/>

   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText"
      android:layout_below="@+id/imageButton"
      android:layout_alignRight="@+id/imageButton"
      android:layout_alignEnd="@+id/imageButton" />

   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText2"
      android:layout_alignTop="@+id/editText"
      android:layout_alignLeft="@+id/textView1"
      android:layout_alignStart="@+id/textView1"
      android:layout_alignRight="@+id/textView1"
      android:layout_alignEnd="@+id/textView1"
      android:hint="Name"
      android:textColorHint="@android:color/holo_blue_light" />

   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText3"
      android:layout_below="@+id/editText"
      android:layout_alignLeft="@+id/editText2"
      android:layout_alignStart="@+id/editText2"
      android:layout_alignRight="@+id/editText2"
      android:layout_alignEnd="@+id/editText2"
      android:hint="Grade"
      android:textColorHint="@android:color/holo_blue_bright" />

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Retrive student"
      android:id="@+id/button"
      android:layout_below="@+id/button2"
      android:layout_alignRight="@+id/editText3"
      android:layout_alignEnd="@+id/editText3"
      android:layout_alignLeft="@+id/button2"
      android:layout_alignStart="@+id/button2"
      android:onClick="onClickRetrieveStudents"/>
</RelativeLayout>

Make sure you have following content of res/values/strings.xml file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">My Application</string>
</resources>;

O’zimiz yaratgan » O’zimning dasturim» dasturini ishga tushirishga harakat qilaylik . O’ylaymanki, siz o’zingizning AVD- ni atrof-muhitni sozlash paytida yaratgansiz . Ilovani Android Studio IDE- Android StudioRun belgisidan ishga tushirish uchun loyihangizning faollik fayllaridan birini oching va asboblar panelidan Ishga tushirish belgisini bosing . Android Studio dasturni AVD-ga o’rnatadi va ishga tushiradi va agar sozlamalaringiz va ilovangizda hamma narsa yaxshi bo’lsa, u quyidagi Emulator oynasini ko’rsatadi, sabr qiling, chunki bu sizning kompyuteringiz tezligiga qarab biroz vaqt talab qilishi mumkin –

Android Content Provider Demo

Endi o’quvchi nomi va sinfini kiritib, so’ngra » Ism qo’shish» tugmachasini bosing, bu ma’lumotlar bazasida talabalar yozuvlarini qo’shadi va pastki qismida ma’lumotlar bazasiga qo’shilgan yozuvlar soni bilan birga ContentProvider URI-ni ko’rsatadigan xabar yonadi. Ushbu operatsiya bizning insert () usulidan foydalanadi. Kontent-provayderimiz ma’lumotlar bazasiga yana bir nechta talabalarni qo’shish uchun ushbu jarayonni takrorlaymiz.

ContentProvider yordamida yozuvlarni qo'shing

Ma’lumotlar bazasiga yozuvlarni qo’shib bo’lgandan so’ng, endi ContentProvider-dan bizga ushbu yozuvlarni qaytarib berishini so’rash vaqti keldi, shuning uchun barcha yozuvlarni birma-bir olib keladigan va ko’rsatadigan Talabalarni qidirish tugmachasini bosamiz, bu bizning bajarilishimizga mos keladi. usuli () .

MainActivity.java-da qayta qo’ng’iroq qilish funktsiyalarini taqdim etish orqali operatsiyalarni yangilash va o’chirishga qarshi yozishingiz mumkin

Shu tarzda mavjud bo’lgan Kontent-provayderdan manzil kitobi kabi foydalanishingiz mumkin yoki yuqorida keltirilgan misolda aytib o’tilganidek o’qish, yozish, yangilash va o’chirish kabi barcha ma’lumotlar bazalari operatsiyalarini bajarishingiz mumkin bo’lgan ma’lumotlar bazasiga yo’naltirilgan dasturlarni ishlab chiqishda Content Provider kontseptsiyasidan foydalanishingiz mumkin.

Leave your thought here

Email manzilingiz chop etilmaydi. Majburiy bandlar * bilan belgilangan

Select the fields to be shown. Others will be hidden. Drag and drop to rearrange the order.
  • Image
  • SKU
  • Rating
  • Price
  • Stock
  • Availability
  • Add to cart
  • Description
  • Content
  • Weight
  • Dimensions
  • Additional information
  • Attributes
  • Custom attributes
  • Custom fields
Compare
Wishlist 0
Open wishlist page Continue shopping