Persistence and Data Storage - IndianTechnoEra
Latest update Android YouTube

Persistence and Data Storage

Android App Development | IndianTechnoEra

Agenda:

- Using SQLite database for data storage

- Content providers and URI handling

- Shared preferences and file storage

This section covers persistence and data storage in Android, including using SQLite database for data storage, content providers and URI handling, and shared preferences and file storage.

Chapter Y: Persistence and Data Storage in Android App Development


Introduction

Persistence and data storage are essential components of Android app development, allowing apps to store and retrieve data to be used across different sessions. 

In this chapter, we will cover the key concepts related to persistence and data storage in Android app development, including using SQLite database for data storage, content providers and URI handling, and shared preferences and file storage.


Using SQLite Database for Data Storage

SQLite is a lightweight and efficient relational database management system that is widely used in Android app development. 

SQLite stores data in a structured format, allowing apps to retrieve and manipulate data quickly and efficiently.


To use SQLite in an Android app, a developer must create a database helper class that extends the SQLiteOpenHelper class and defines the database schema and table structure. 

The helper class is then used to create and manage the database, including inserting, updating, and deleting data.


For example, the following code shows how to create a simple SQLite database that stores user information:

```

public class UserDatabaseHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;

    private static final String DATABASE_NAME = "UserDatabase";


    private static final String TABLE_USERS = "users";

    private static final String COLUMN_ID = "id";

    private static final String COLUMN_NAME = "name";

    private static final String COLUMN_EMAIL = "email";


    public UserDatabaseHelper(Context context) {

        super(context, DATABASE_NAME, null, DATABASE_VERSION);

    }


@Override

    public void onCreate(SQLiteDatabase db) {

        String CREATE_USERS_TABLE = "CREATE TABLE " + TABLE_USERS + "("

                + COLUMN_ID + " INTEGER PRIMARY KEY,"

                + COLUMN_NAME + " TEXT,"

                + COLUMN_EMAIL + " TEXT" + ")";

        db.execSQL(CREATE_USERS_TABLE);

    }


    @Override

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);

        onCreate(db);

    }


    public void addUser(User user) {

        SQLiteDatabase db = this.getWritableDatabase();


        ContentValues values = new ContentValues();

        values.put(COLUMN_NAME, user.getName());

        values.put(COLUMN_EMAIL, user.getEmail());


        db.insert(TABLE_USERS, null, values);

        db.close();

    }


    public List<User> getAllUsers() {

        List<User> userList = new ArrayList<>();

        String selectQuery = "SELECT * FROM " + TABLE_USERS;


        SQLiteDatabase db = this.getWritableDatabase();

        Cursor cursor = db.rawQuery(selectQuery, null);


        if (cursor.moveToFirst()) {

            do {

                User user = new User();

                user.setId(Integer.parseInt(cursor.getString(0)));

                user.setName(cursor.getString(1));

                user.setEmail(cursor.getString(2));

                userList.add(user);

            } while (cursor.moveToNext());

        }


        cursor.close();

        db.close();


        return userList;

    }

}

```


This code defines a database helper class called "UserDatabaseHelper" that extends the SQLiteOpenHelper class. 

The class defines the database schema and table structure, including columns for id, name, and email. 

The helper class also includes methods for creating the database, adding and retrieving data, and upgrading the database version.


Content Providers and URI Handling

Content providers are a way to share data between different apps in Android. 

A content provider exposes a set of data to other apps using a content URI, which is a unique identifier that specifies the data to be accessed.


To create a content provider in an Android app, a developer must create a class that extends the ContentProvider class and defines the data to be exposed. 

The class must also define a set of URIs that specify the data to be accessed, and implement methods for querying, inserting, updating, and deleting data.


For example, the following code shows how to create a simple content provider that exposes a list of contacts:

```

public class MyContentProvider extends ContentProvider {

    private static final String AUTHORITY = "com.example.provider.contacts";

    private static final String BASE_PATH = "contacts";

    public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH);


    private static final int CONTACTS = 1;

    private static final int CONTACT_ID = 2;


    private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

    static {

        uriMatcher.addURI(AUTHORITY, BASE_PATH, CONTACTS);

        uriMatcher.addURI(AUTHORITY, BASE_PATH + "/#", CONTACT_ID);

    }


    private MyDatabaseHelper dbHelper;


    @Override

    public boolean onCreate() {

        dbHelper = new MyDatabaseHelper(getContext());

        return true;

    }


    @Nullable

    @Override

    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {

        SQLiteDatabase db = dbHelper.getWritableDatabase();


        int match = uriMatcher.match(uri);

        switch (match) {

            case CONTACTS:

                return db.query("contacts", projection, selection, selectionArgs, null, null, sortOrder);

            case CONTACT_ID:

                selection = "_id = ?";

                selectionArgs = new String[]{uri.getLastPathSegment()};

                return db.query("contacts", projection, selection, selectionArgs, null, null, sortOrder);

            default:

                throw new IllegalArgumentException("Unknown URI: " + uri);

        }

    }


    @Nullable

    @Override

    public String getType(@NonNull Uri uri) {

        int match = uriMatcher.match(uri);

        switch (match) {

            case CONTACTS:

                return "vnd.android.cursor.dir/contacts";

            case CONTACT_ID:

                return "vnd.android.cursor.item/contacts";

            default:

                throw new IllegalArgumentException("Unknown URI: " + uri);

        }

    }


    @Nullable

    @Override

    public Uri insert(@NonNull Uri uri,@Nullable ContentValues values) {

        SQLiteDatabase db = dbHelper.getWritableDatabase();


        int match = uriMatcher.match(uri);

        switch (match) {

            case CONTACTS:

                long id = db.insert("contacts", null, values);

                return ContentUris.withAppendedId(CONTENT_URI, id);

            default:

                throw new IllegalArgumentException("Unknown URI: " + uri);

        }

    }


    @Override

    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {

        SQLiteDatabase db = dbHelper.getWritableDatabase();


        int match = uriMatcher.match(uri);

        switch (match) {

            case CONTACTS:

                return db.delete("contacts", selection, selectionArgs);

            case CONTACT_ID:

                selection = "_id = ?";

                selectionArgs = new String[]{uri.getLastPathSegment()};

                return db.delete("contacts", selection, selectionArgs);

            default:

                throw new IllegalArgumentException("Unknown URI: " + uri);

        }

    }


    @Override

    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {

        SQLiteDatabase db = dbHelper.getWritableDatabase();


        int match = uriMatcher.match(uri);

        switch (match) {

            case CONTACTS:

                return db.update("contacts", values, selection, selectionArgs);

            case CONTACT_ID:

                selection = "_id = ?";

                selectionArgs = new String[]{uri.getLastPathSegment()};

                return db.update("contacts", values, selection, selectionArgs);

            default:

                throw new IllegalArgumentException("Unknown URI: " + uri);

        }

    }

}

```

This code defines a content provider class called "MyContentProvider" that extends the ContentProvider class. 

The class defines a set of URIs that specify the data to be accessed, including a base path of "contacts" and a content URI of "content://com.example.provider.contacts/contacts". 

The class also includes methods for querying, inserting, updating, and deleting data.


Shared Preferences and File Storage

Shared preferences and file storage are two other methods for storing data in Android apps. 

Shared preferences are used to store small amounts of data, such as user preferences, as key-value pairs. 

File storage is used to store larger amounts of data, such as images, audio files, and video files.


To use shared preferences in an Android app, a developer must create an instance of the SharedPreferences class and call methods to add, retrieve, and remove key-value pairs. 

To use file storage, a developer must create and manage files using the Java File API or Android-specific APIs, such as the Context.getFilesDir() and Context.openFileOutput() methods.


For example, the following code shows how to use shared preferences to store a user's name:

```

SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);

SharedPreferences.Editor editor = sharedPreferences.edit();

editor.putString("name", "John");

editor.apply();


String name = sharedPreferences.getString("name", "defaultName");

```

This code creates an instance of the SharedPreferences class with a name of "MyPrefs" and a mode of private, which means that only the app can access the shared preferences. 

The code then creates an editor object and adds a key-value pair with a key of "name" and a value of "John". 

The apply() method is called to save the changes to the shared preferences. 

The code then retrieves the value of the "name" key using the getString() method, with a default value of "defaultName" if the key does not exist.

إرسال تعليق

Feel free to ask your query...
Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.