安卓学习-Loaders-加载器

原创
2016/04/05 10:50
阅读数 95

image

image

image

image

image

image

image

image

image

image

image

image实时加载数据

数据使用SQLite数据库保存,而使用ContentProvider进行数据的请求与访问

Person.java

package com.example.administrator.loaders;

/**
 * Created by Administrator on 2016/4/4.
 */
public class Person {
    private int id;
    private String name;
    private int age;
public Person()
{

}

    public Person(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                ", id=" + id +
                ", name='" + name + '\'' +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

PersonMetadata.java

package com.example.administrator.loaders;

import android.provider.BaseColumns;

/**
 * Created by Administrator on 2016/4/4.
 */
//finale 不让继承
public final class PersonMetadata {
    public static abstract class Person implements BaseColumns {
        public static final String TABLE_NAME="person";
        public static final String NAME="name";
        public static final String AGE="age";
    }
}

DatabaseAdapter.java

package com.example.administrator.loaders;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;

/**
 * Created by Administrator on 2016/4/4.
 */
public class DatabaseAdapter {
    private DatabaseHelper dbHelper;

    public DatabaseAdapter(Context context) {
        dbHelper = new DatabaseHelper(context);
    }

    public void save(Person person) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(PersonMetadata.Person.NAME, person.getName());
        values.put(PersonMetadata.Person.AGE, person.getAge());
        db.insert(PersonMetadata.Person.TABLE_NAME, null, values);
        db.close();
    }

    public Cursor list()
    {
        SQLiteDatabase db= dbHelper.getReadableDatabase();
        Cursor c=db.query(PersonMetadata.Person.TABLE_NAME, null, null, null, null, null, null);
        return c;
    }
    public void delete(int id) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        String whereClause = PersonMetadata.Person._ID + "=?";
        String[] whereArgs = {String.valueOf(id)};
        db.delete(PersonMetadata.Person.TABLE_NAME, whereClause, whereArgs);
        db.close();
    }

    public void update(Person person) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(PersonMetadata.Person.NAME, person.getName());
        values.put(PersonMetadata.Person.AGE, person.getAge());
        String whereClause = PersonMetadata.Person._ID + "=?";
        String[] whereArgs = {String.valueOf(person.getId())};
        db.update(PersonMetadata.Person.TABLE_NAME, values, whereClause, whereArgs);
        db.close();
    }
    public ArrayList<Person> findAll()
    {
       SQLiteDatabase db= dbHelper.getReadableDatabase();
        Cursor c=db.query(PersonMetadata.Person.TABLE_NAME, null, null, null, null, null, null);
        ArrayList<Person> list=new ArrayList<Person>();
        Person person=null;
        while (c.moveToNext())
        {
            person=new Person();
            person.setId(c.getInt(c.getColumnIndexOrThrow(PersonMetadata.Person._ID)));
            person.setName(c.getString(c.getColumnIndexOrThrow(PersonMetadata.Person.NAME)));
            person.setAge(c.getInt(c.getColumnIndexOrThrow(PersonMetadata.Person.AGE)));
            list.add(person);
        }
        c.close();
        db.close();
        return list;
    }
    public Person findById(int id)
    {
        SQLiteDatabase db= dbHelper.getReadableDatabase();
        Cursor c=db.query(PersonMetadata.Person.TABLE_NAME, null, PersonMetadata.Person._ID+"=?", new String[]{String.valueOf(id)}, null, null, null);

        Person person=null;
       if (c.moveToNext())
        {
            person=new Person();
            person.setId(c.getInt(c.getColumnIndexOrThrow(PersonMetadata.Person._ID)));
            person.setName(c.getString(c.getColumnIndexOrThrow(PersonMetadata.Person.NAME)));
            person.setAge(c.getInt(c.getColumnIndexOrThrow(PersonMetadata.Person.AGE)));

        }
        c.close();
        db.close();
        return person;
    }


   public static class DatabaseHelper extends SQLiteOpenHelper {
        private static final String DB_NAME = "cp.db";
        private static final int VERSION = 1;
        private static final String CREATE_TABLE = "CREATE TABLE person(_id INTEGER PRIMARY KEY AUTOINCREMENT," +
                "name TEXT,age INT)";
        private static final String DROP_TABLE = "DROP TABLE IF EXISTS person";

        public DatabaseHelper(Context context) {
            super(context, DB_NAME, null, VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(CREATE_TABLE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL(DROP_TABLE);
            db.execSQL(CREATE_TABLE);
        }
    }

}

PersonContentProvider.java

<provider
    android:authorities="com.example.administrator.personcontentprovider"
    android:name=".PersonContentProvider"></provider>
-------------------------------------------------------------------
package com.example.administrator.loaders;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

/**
 * 自定义内容提供者
 * Created by Administrator on 2016/4/4.
 */
public class PersonContentProvider extends ContentProvider {
    private static final String AUTHORITY = "com.example.administrator.personcontentprovider";
    //创建一个URI的匹配器
    private static UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    private static final int SINGLE_CODE = 2;//返回单个记录的匹配码
    private static final int MUTIPLE_CODE = 1;//标识返回多个记录的匹配码
    //text/plain  image/jpg
    private static final String SINGLE_TYPE = "vnd.android.cursor.item/person";
    private static final String MUTIPLE_TYPE = "vnd.android.cursor.dir/person";

    static {

        uriMatcher.addURI(AUTHORITY, "person", MUTIPLE_CODE);
        uriMatcher.addURI(AUTHORITY, "person/#", SINGLE_CODE);
    }

    private DatabaseAdapter.DatabaseHelper dbHelper;

    @Override
    public boolean onCreate() {
        dbHelper = new DatabaseAdapter.DatabaseHelper(getContext());
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        switch (uriMatcher.match(uri)) {
            case SINGLE_CODE:
                SQLiteDatabase db = dbHelper.getReadableDatabase();
                long id = ContentUris.parseId(uri);
                selection = PersonMetadata.Person._ID + "=?";
                selectionArgs = new String[]{String.valueOf(id)};
                return db.query(PersonMetadata.Person.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);

            case MUTIPLE_CODE:
                db = dbHelper.getReadableDatabase();

                return db.query(PersonMetadata.Person.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);

        }
        return null;
    }

    @Override
    public String getType(Uri uri) {
        switch (uriMatcher.match(uri)) {
            case SINGLE_CODE:
                return SINGLE_TYPE;
            case MUTIPLE_CODE:
                return MUTIPLE_TYPE;
        }
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        switch (uriMatcher.match(uri)) {
            case MUTIPLE_CODE:
                SQLiteDatabase db = dbHelper.getWritableDatabase();
                long id = db.insert(PersonMetadata.Person.TABLE_NAME, null, values);
                uri = ContentUris.withAppendedId(uri, id);
                db.close();
                break;
        }
        return uri;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        switch (uriMatcher.match(uri))
        {
            case SINGLE_CODE:
                SQLiteDatabase db = dbHelper.getWritableDatabase();
                long id = ContentUris.parseId(uri);
                selection = PersonMetadata.Person._ID + "=?";
                selectionArgs = new String[]{String.valueOf(id)};
                int row = db.delete(PersonMetadata.Person.TABLE_NAME, selection, selectionArgs);
                db.close();
                return row;
            case MUTIPLE_CODE:
                db = dbHelper.getWritableDatabase();
                row = db.delete(PersonMetadata.Person.TABLE_NAME, selection, selectionArgs);
                db.close();
                return row;
        }
        return 0;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        switch (uriMatcher.match(uri))
        {
            case SINGLE_CODE:
                SQLiteDatabase db = dbHelper.getWritableDatabase();
                long id = ContentUris.parseId(uri);
                selection = PersonMetadata.Person._ID + "=?";
                selectionArgs = new String[]{String.valueOf(id)};
                int row = db.update(PersonMetadata.Person.TABLE_NAME, values, selection, selectionArgs);
                db.close();
                return row;
            case MUTIPLE_CODE:
                db = dbHelper.getWritableDatabase();
                row = db.update(PersonMetadata.Person.TABLE_NAME, values, selection, selectionArgs);
                db.close();
                return row;
        }
        return 0;
    }
}

MainActivity.java

package com.example.administrator.loaders;

import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class MainActivity extends ActionBarActivity implements LoaderManager.LoaderCallbacks<Cursor> {

    private DatabaseAdapter dbAdapter;
    SimpleCursorAdapter dataAdapter;
    CursorLoader loader;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dbAdapter = new DatabaseAdapter(this);
        ListView lv = (ListView) findViewById(R.id.listView);
         dataAdapter =
                new SimpleCursorAdapter(this, R.layout.list_item, dbAdapter.list(),
                        new String[]{PersonMetadata.Person._ID, PersonMetadata.Person.NAME,
                                PersonMetadata.Person.AGE},
                        new int[]{R.id.textView_id, R.id.textView_name,
                                R.id.textView_age}, SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        lv.setAdapter(dataAdapter);

        //初始化一个loader(id,bundler参数,回调接口)
        getLoaderManager().initLoader(0, null, this);
    }

    public void addClick(View view) {
         dbAdapter.save(new Person("xiaofei",18));
        //重启加载器
   //  getLoaderManager().restartLoader(0,null,this);
        //loader.commitContentChanged();API 18可用
        loader.onContentChanged();//内容发生了变化,通知加载器

    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        System.out.println("onCreateLoader");
        Uri uri=Uri.parse("content://com.example.administrator.personcontentprovider/person");
       //创建一个游标加载器(上下文,CP的URI,要查询的列数组,查询条件,查询条件的值,排序条件)
         loader=new CursorLoader(this,uri,null,null,null,null);
        return loader;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        System.out.println("onLoadFinished");
        dataAdapter.swapCursor(data);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        System.out.println("onLoaderReset");
        dataAdapter.swapCursor(null);
    }
}

activity_main.xml

<?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.administrator.loaders.MainActivity">


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=" 添加"
        android:onClick="addClick"
        android:id="@+id/button"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView"
        android:layout_below="@+id/button"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="@dimen/activity_vertical_margin"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text" />

    <TextView
        android:id="@+id/textView_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text" />

    <TextView
        android:id="@+id/textView_age"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text" />
</LinearLayout>

 

image

activity_main2.xml

<?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.administrator.loaders.MainActivity2">


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="add"
        android:onClick="addClick"
        android:id="@+id/button2"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView2"
        android:layout_below="@+id/button2"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

MainActivity2.java

package com.example.administrator.loaders;

import android.app.LoaderManager;
import android.content.AsyncTaskLoader;
import android.content.Context;
import android.content.Loader;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class MainActivity2 extends ActionBarActivity implements LoaderManager.LoaderCallbacks<ArrayList<Person>> {

    private MyAdapter myAdapter;
    private DatabaseAdapter dbAdapter;
    private DataAsyncTaskLoader loader;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        ListView lv = (ListView) findViewById(R.id.listView2);
        dbAdapter = new DatabaseAdapter(this);
        myAdapter = new MyAdapter(this, dbAdapter.findAll());
        lv.setAdapter(myAdapter);

        getLoaderManager().initLoader(0, null, this);

    }

    public void addClick(View view) {
      dbAdapter.save(new Person("小龙",18));
        loader.onContentChanged();
    }

    @Override
    public Loader<ArrayList<Person>> onCreateLoader(int id, Bundle args) {
        loader = new DataAsyncTaskLoader(this, dbAdapter);
        return loader;
    }

    @Override
    public void onLoadFinished(Loader<ArrayList<Person>> loader, ArrayList<Person> data) {
        myAdapter.setPersons(data);
        myAdapter.notifyDataSetChanged();
    }

    @Override
    public void onLoaderReset(Loader<ArrayList<Person>> loader) {
        myAdapter.setPersons(null);
    }

    //自定义的loader   泛型
    private static class DataAsyncTaskLoader extends AsyncTaskLoader<ArrayList<Person>> {
        private DatabaseAdapter dbAdapter;
        private ArrayList<Person> data;

        public DataAsyncTaskLoader(Context context, DatabaseAdapter dbAdapter) {
            super(context);
            this.dbAdapter = dbAdapter;
        }

        //该方法在后台线程中执行,用来加载数据
        @Override
        public ArrayList<Person> loadInBackground() {
            System.out.println("loadInBackground");
            data = dbAdapter.findAll();
            return data;
        }

        //用于发送结果
        @Override
        public void deliverResult(ArrayList<Person> data) {
            if (isReset()) {
                return;
            }
            if (isStarted()) {
                super.deliverResult(data);
            }
        }

        //正在加载中
        @Override
        protected void onStartLoading() {
            if (data != null) {
                deliverResult(data);
            }
            if (takeContentChanged()) {
                forceLoad();//强制加载数据
            }
            super.onStartLoading();
        }
    }

    private static class MyAdapter extends BaseAdapter {
        private ArrayList<Person> persons;
        private Context context;

        public void setPersons(ArrayList<Person> persons) {
            this.persons = persons;
        }

        public MyAdapter(Context context, ArrayList<Person> persons) {
            this.context = context;
            this.persons = persons;
        }

        @Override
        public int getCount() {
            return persons.size();
        }

        @Override
        public Object getItem(int position) {
            return persons.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder vh = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.list_item, null);
                vh = new ViewHolder();
                vh.tv_id = (TextView) convertView.findViewById(R.id.textView_id);
                vh.tv_name = (TextView) convertView.findViewById(R.id.textView_name);
                vh.tv_age = (TextView) convertView.findViewById(R.id.textView_age);
                convertView.setTag(vh);
            } else {
                vh = (ViewHolder) convertView.getTag();
            }
            Person p = persons.get(position);
            vh.tv_id.setText(String.valueOf(p.getId()));
            vh.tv_name.setText(p.getName());
            vh.tv_age.setText(String.valueOf(p.getAge()));
            return convertView;
        }

        private static class ViewHolder {
            TextView tv_id;
            TextView tv_name;
            TextView tv_age;
        }

    }
}
展开阅读全文
打赏
1
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
1
分享
返回顶部
顶部