ZOFTINO.COM android and web dev tutorials

Android MatrixCursor Example

Android MatrixCursor can be used to create cursor by adding column names and data rows. This will be helpful when you have few records of two dimensional data and want to display them in ListView using SimpleCursorAdapter or create a content provider for other apps.

I’ll show how to use MatrixCursor with an example. The example contains a content provider which creates and provides matrix cursor to content provider client which displays the cursor in the list view using SimpleCursorAdapter.

android matrixcursor example

Using MatrixCursor

You can instantiate MatrixCursor specifying column names using constructor. To add data to MatrixCursor, you can use addRow method which takes array of objects as input and adds those objects to columns in the order columns are specified when MatrixCursor is instantiated.

To add rows by specifying column name for each column data, you have to use MatrixCursor.RowBuilder. MatrixCursor.RowBuilder has an add method which take column name and value. To add a row to MatrixCursor using MatrixCursor.RowBuilder, first get MatrixCursor.RowBuilder object by calling newRow on MatrixCursor object and then use the MatrixCursor.RowBuilder object returned by newRow to add data to columns.

Content Provider

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;


public class CategoryContentProvider extends ContentProvider {

    private static final String CATEGORIES = "categories";

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

    static {
        uriMatcher.addURI("com.zoftino.categories", CATEGORIES, 1);
    }

    private static String[] matrixColumns = {"_id", "category"};

    @Override
    public boolean onCreate() {
        return true;
    }

    @Nullable
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
                        String sortOrder) {
        switch(uriMatcher.match(uri)){
            case 1 :
                return getCategories();
            default:
                return null;
        }
    }
    @Nullable
    @Override
    public String getType(Uri uri) {
        return null;
    }

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) {
        return null;
    }

    @Override
    public int delete(@NonNull Uri uri, @Nullable String s, @Nullable String[] strings) {
        return 0;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues contentValues,
                      @Nullable String s, @Nullable String[] strings) {
        return 0;
    }

    private MatrixCursor getCategories() {
        MatrixCursor categories = new MatrixCursor(matrixColumns);
        Object[] mRow = new Object[2];
        int rowId = 0;
        for (String rec : CategoryInfo.getCategories()) {

            mRow[0] = "" + rowId++;
            mRow[1] = rec;
            categories.addRow(mRow);

        }
        return categories;
    }
}

Activity

import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class CategoryInfoActivity extends AppCompatActivity {

    private final Uri categoryContentProvider =
            Uri.parse("content://com.zoftino.categories/categories");

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.categories_layout);

        ListView lv = findViewById(R.id.listView);

        Cursor categoriesCursor = getContentResolver().query(categoryContentProvider,null,
                null,null,null );

        String[] cursorColumns = { "category" };
        int[] viewIds = {android.R.id.text1};

        SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(
                getApplicationContext(),
                android.R.layout.simple_dropdown_item_1line,
                categoriesCursor,
                cursorColumns,
                viewIds,
                0);

        lv.setAdapter(simpleCursorAdapter);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override public void onItemClick(AdapterView<?> parent, View view,
                                              int position, long id) {
                Toast.makeText(CategoryInfoActivity.this,
                        "selected category is "+((TextView)view).getText(),
                                                            Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Activity Layout

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    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=".CategoryInfoActivity">
    <ListView android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:layout_marginTop="16dp"
        android:padding="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="zoftino.com.matrixcursor">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/zoftino"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/zoftino"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".CategoryInfoActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <provider
            android:authorities="com.zoftino.categories"
            android:name=".CategoryContentProvider"></provider>
    </application>
</manifest>

Data

 import java.util.ArrayList;
import java.util.List;

public class CategoryInfo {
    private static List<String> categories ;
    static {
        categories =  new ArrayList<String>();
        categories.add("Clothing");
        categories.add("Footwear");
        categories.add("Jewellery");
        categories.add("Baby");
        categories.add("Toys");
        categories.add("Luggage");
        categories.add("Home");
        categories.add("Appliances");
        categories.add("Mobiles");
        categories.add("Laptops");
        categories.add("Electronics");
        categories.add("Kitchen");
    }

    public static List<String> getCategories(){
        return categories;
    }

}