Skip to main content

How to use Cursor Loader? Example



Why we need it?
Answer is simple, because it is a background thread. Cursor Loader doesn’t block UI thread like the it’s old way; Activity.managerQuery.
Where we use it?
            It is effective tool when we have a large number of items in SQlite tables.
How we use?
            Setup;
We need a content provider to use Cursor Loader. Let’s write simple method for query database. Assume that database has some android phone. And in order to make it slow for take advange of Cursor Loader it will sleep 5 seconds in query.

    public static CursorLoader getCursorLoader(Context paramContext) {
        Log.i(TAG,"try to block query");
        Thread.sleep(5000); //miliseconds

        String[] a = { Boolean.toString(false) };
        return new CursorLoader(paramContext, Your.URI, ColumnNamesYouWantToQuery, null, null, "_id ASC ");
    }
            This simple query return a cursor with list of element.
String[]{"Samsung Galaxy S6","HTC One M9","Sony Xperia Z5","LG G4", "Nexus 5X", "Nexus 6P"}
Other than this database can be filled from WEB or just pulling from existing content provider.
            Usage;
Let’s create a class with CursorLoader implementation.
CursorLoaderActivity.java
package com.kozaxinan.sekreter;

import android.app.ListActivity;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;

public class  CursorLoaderActivity extends ListActivity implements LoaderManager.LoaderCallbacks<Cursor> {

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

    @Override
    protected void onResume() {               
// if you want to restart loader
        getLoaderManager().restartLoader(0, null, this);
        super.onResume();
    }


    @Override
    public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
       //this is where we create background thread for cursor
        CursorLoader localCursorLoader = getCursorLoader(this);
        return localCursorLoader;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> arg0, Cursor localCursor) {
        //make something with cursor and close it

        localCursor.close();
    }

    @Override                 
    public void onLoaderReset(Loader<Cursor> arg0) {
    }
}

It is new API!!!
            CursorLoader is available before API level 11. But Android team add this good feature in the Compatibility Library Package.
            This API works in Fragment with Compatibility Library. Therefor we need a init method to call CursorLoader;
        getSupportLoaderManager().initLoader(LOADER_ID, null, this);

For this method we need a loader_id which we can select randomly.
This is a basic way to use CursorLoader. Use this API in your project to avoid blocked UI.

Comments

Post a Comment

Popular posts from this blog

Using Accelerometer when Screen Off

Introduction Android Phones have a lot of built-in sensor such as gyro, proximity and accelerometer. Using Accelerometer in Android is a known thing. For listening sensors, class or service needs a SensorEventListener implementation. An Activity is only exists when you are seeing it. When phone enters standby mode, activity which was recently active frozen and restored whenever needed. While this frozen time, activity doesn’t run. Because of that it doesn’t need sensor updates. And Android stop to listen some sensors for power management. Services have this condition like classes (activity). In contrast to class, a service run every time, even when phone is in standby mode. Therefore Services needs sensor updates for some situations. But android stop to listen some sensor(accelerometer) in some different phones. There is a solution for that. This is not an exact solution but it work with a lot of phones. With a BroadcastReceiver listen   Intent. ACTION_SCREEN_O

Eclipse'te Android Sanal Makinesi oluşturma

Eclipse'te oluşturduğumuz projeleri denemek için Eclipse'te Android Sanal makinesı oluşturabiliriz. Bu yaptığımız programları önce bilgisayar üzerinde denememiz ve ilk izlenimlerimizi oluşturmamız için önemlidir. Her android sürümü için farklı sanal makine oluşturabileceğimiz için yazdığımız programın farklı sürümlerde nasıl çalıştığını görmemize yardımcı olur. Bu sanal makineyi önceki yazılarda anlattığımız şekilde kurduğumuz Eclipse'te  bir kaç adımda oluşturabiliriz. Bunun içim aşağıdaki adımları izlememiz yeterli olucaktır. Windows-> AVD Manager a tıklayalım. Açılan pencerede sağ üstten "New"e basarak yeni sanal makine oluşturacağımız ekrana gelelim. Burda "Name" kısmına istediğimiz ismi yazabiliriz. Ama tavsiyem oluşturacağınız android sürümü ile alakalı isimler verin. örn: Android 2.1 sürümü için Andro_2.1 şeklinde isim verebilirsiniz. "Target" kısmında oluşturacağınız sanal makinenin API sini seçmelisiniz. SD kart kısmına

How to change position of MyLocationButton on new Map API v2? Explained

When an app use map and design some layout on this map (TextView, Button or image), developer needs to change position of default buttons of map view. (MyLocationButton, ZoomControl or compass...) As far as i know, there are two possible way for changing position of myLocationButton's position. 1- * - Disable it     * - Create new button programmatically     * - Add animateCamera(toCurrentLocation) to onClickListener of this button     * - And place it wherever you want But if you don't want to write all that there is a hack for that. 2 - * - findViewById() of hardcoded button with; ZoomControl id = 0x1 MyLocation button id = 0x2      * - And do whatever you want: // Find map fragment SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); // Find myLocationButton view View myLocationButton = mapFragment.getView().findViewById(0x2); if (myLocationButton != null && myLocationButton.get