使用ContentResolver添加数据、查询数据

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.os.Bundle;
import android.provider.UserDictionary.Words;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class DictResolver extends Activity {
  ContentResolver contentResolver;
  Button insert;
  Button search;

  @Override
  protected void onCreateBundle savedInstanceState) {
    super.onCreatesavedInstanceState);
    setContentViewR.layout.activity_dict_resolver);
    //获取系统的ContentResolver对象
    contentResolver = getContentResolver);
    insert = Button) findViewByIdR.id.insert);
    search = Button) findViewByIdR.id.search);
    //为insert按钮的单击事件绑定事件监听器
    insert.setOnClickListenernew OnClickListener) {

      @Override
      public void onClickView v) {
        // 获取用户输入
        String word = EditText)findViewByIdR.id.word)).getText).toString);
        String detail = EditText)findViewByIdR.id.detail)).getText).toString);
        //插入生词记录
        ContentValues values = new ContentValues);
        values.putmediaprovidertest.Words.Word.WORD, word);
        values.putmediaprovidertest.Words.Word.DETAIL, detail);
        contentResolver.insertmediaprovidertest.Words.Word.DICT_CONTENT_URI, values);
        //显示提示信息
        Toast.makeTextDictResolver.this, “添加单词成功!”, 8000).show);
      }
    });
    //为search按钮的单击事件绑定事件监听器
    search.setOnClickListenernew OnClickListener) {

      @Override
      public void onClickView v) {
        // 获取用户输入
        String key = EditText)findViewByIdR.id.key)).getText).toString);
        //执行查询
        Cursor cursor = contentResolver.query
            mediaprovidertest.Words.Word.DICT_CONTENT_URI,
            null, “word like ? or detail like ?”,
            new String[]{“%”+key+”%”,”%”+key+”%”}, null);
        //创建一个Bundle
        Bundle data = new Bundle);
        data.putSerializable”data”, converCursorToListcursor));
        //创建一个Intent
        Intent intent = new IntentDictResolver.this, ResultActivity.class);
        intent.putExtrasdata);
        //启动Activity
        startActivityintent);
      }
    });
  }
  private ArrayList<Map<String, String>> converCursorToListCursor cursor){
  ArrayList<Map<String, String>> result = new ArrayList<Map<String,String>>);
  //遍历Cursor结果集
  whilecursor.moveToNext)){
    //将结果集中的数据存入ArrayList中
    Map<String, String> map = new HashMap<String, String>);
    //取出查询记录中第2列、第3列的值
    map.putmediaprovidertest.Words.Word.WORD, cursor.getString1));
    map.putmediaprovidertest.Words.Word.DETAIL, cursor.getString2));
    result.addmap);
  }
  return result;
  }

}

Published by

风君子

独自遨游何稽首 揭天掀地慰生平

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注