Content Provider(一) basics

本文详细介绍了如何使用Android Content Provider实现数据的查询和插入操作。通过定义Uri、ContentValues以及选择合适的查询条件,实现了与用户字典的交互,展示了如何在Android应用中灵活地管理和访问数据。
package com.example.drawernavigation.fragment;

import com.example.drawernavigation.MainActivity;
import com.example.drawernavigation.R;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.UserDictionary;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SimpleCursorAdapter;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;


public class BFragmentDrawer extends Fragment {

	MainActivity.MyOnTouchListener myOnTouchListener;
	private static final String TAG = "BFragmentDrawer";

	private Button content_provider_bt, content_provider_insertbt;
	private EditText content_provider_edt;

	ListView mWordList;

	String mSearchString;
	SimpleCursorAdapter mCursorAdapter;
	Cursor mCursor;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.fragment_b, container, false);

		content_provider_edt = (EditText) view
				.findViewById(R.id.content_provider_edt);
		content_provider_bt = (Button) view
				.findViewById(R.id.content_provider_bt);

		content_provider_bt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				querySearch();
			}
		});

		content_provider_insertbt = (Button) view
				.findViewById(R.id.content_provider_insertbt);
		content_provider_insertbt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				insertSearch();
			}
		});

		mWordList = (ListView) view.findViewById(R.id.mWordList);

		return view;
	}

	public void insertSearch() {
		// Defines a new Uri object that receives the result of the insertion
		Uri mNewUri;
		// Defines an object to contain the new values to insert
		ContentValues mNewValues = new ContentValues();

		/*
		 * Sets the values of each column and inserts the word. The arguments to
		 * the "put" method are "column name" and "value"
		 */
		mNewValues.put(UserDictionary.Words.APP_ID, "example.user2");
		mNewValues.put(UserDictionary.Words.LOCALE, "en_US");
		mNewValues.put(UserDictionary.Words.WORD, "insert2");
		mNewValues.put(UserDictionary.Words.FREQUENCY, "100");

		mNewUri = getActivity().getContentResolver().insert(
				UserDictionary.Words.CONTENT_URI, // the user dictionary content
													// URI
				mNewValues // the values to insert
				);
	}

	public void querySearch() {

		// a "projection" 定义了要返回的行的columns
		String[] mProjection = { UserDictionary.Words._ID,
				UserDictionary.Words.WORD, UserDictionary.Words.LOCALE };

		// 定义一个string 来包含 要选择的分句
		String mSelectionClause = null;
		// 初始化一个array 来包含 要选择的参数
		String[] mSelectionArgs = { "" };

		// 从UI线程获得一个单词
		mSearchString = content_provider_edt.getText().toString();

		// 插入代码,检查 输入的有效性和安全性

		/**
		 * 如果是空,返回所有值
		 */
		if (TextUtils.isEmpty(mSearchString)) {
			Log.e(TAG, "输入为空");
			mSelectionClause = null;
			mSelectionArgs[0] = "";
		} else {
			Log.e(TAG, "输入不为空");
			// 构造一个选择分句来匹配用户输入的单词
			mSelectionClause = UserDictionary.Words.WORD + " = ? ";
			// 将用户的输入string 来作为选择参数
			mSelectionArgs[0] = mSearchString;
		}

		String mSortOrder = " word ASC";

		/**
		 * 对这个 table 进行查询,返回一个cursor对象
		 */
		mCursor = getActivity().getContentResolver().query(
				UserDictionary.Words.CONTENT_URI, mProjection,
				mSelectionClause, mSelectionArgs, null);

		Log.i(TAG, UserDictionary.Words.CONTENT_URI.toString());

		/**
		 * 处理返回结果,null, empty,...
		 */
		if (null == mCursor) {
			Log.e(TAG, "结果为null");
			/*
			 * Insert code here to handle the error. Be sure not to use the
			 * cursor! You may want to call android.util.Log.e() to log this
			 * error.
			 */
		} else if (mCursor.getCount() < 1) {
			/*
			 * Insert code here to notify the user that the search was
			 * unsuccessful. This isn't necessarily an error. You may want to
			 * offer the user the option to insert a new row, or re-type the
			 * search term.
			 */

			Log.i(TAG, "结果" + mCursor.getCount());

		} else {
			/**
			 * 定义simpleCursorAdapter,展示数据
			 */
			String[] mWordListColumns = { UserDictionary.Words.WORD,
					UserDictionary.Words.LOCALE };

			int[] mWordListItems = { R.id.dictWord, R.id.locale };

			mCursorAdapter = new SimpleCursorAdapter(getActivity(),
					R.layout.wordlistrow, mCursor, mWordListColumns,
					mWordListItems, 0);

			mWordList.setAdapter(mCursorAdapter);

		}

		/**
		 * 从查询结果中获得数据
		 */
		// 找到列“word”的索引
		int index = mCursor.getColumnIndex(UserDictionary.Words.WORD);

		Log.i(TAG, "word的位置" + index);

		// 仅当cursor有效时执行
		String newWord;
		if (mCursor != null) {
			Log.e(TAG, "mCursor不为空");

			/*
			 * Moves to the next row in the cursor. Before the first movement in
			 * the cursor, the "row pointer" is -1, and if you try to retrieve
			 * data at that position you will get an exception.
			 */
			while (mCursor.moveToNext()) {
				// Gets the value from the column.
				newWord = mCursor.getString(index);
				// Insert code here to process the retrieved word.
				Log.i(TAG, newWord);
				// end of while loop
			}
		} else {
			// Insert code here to report an error if the cursor is null or the
			// provider threw an exception.
			Log.e(TAG, "没有找到word列");
		}

	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		Log.e(TAG, "onAttach");
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.e(TAG, "onCreate");

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		Log.e(TAG, "onActivityCreated");
	}

	@Override
	public void onStart() {
		super.onStart();
		Log.e(TAG, "onStart");
	}

	@Override
	public void onResume() {
		Log.e(TAG, "onResume");
		super.onResume();
	}

	@Override
	public void onPause() {
		Log.e(TAG, "onPause");
		super.onPause();
	}

	@Override
	public void onStop() {
		Log.e(TAG, "onStop");
		super.onStop();
	}

	@Override
	public void onDestroyView() {
		Log.e(TAG, "onDestroyView");
		super.onDestroyView();
	}

	@Override
	public void onDestroy() {
		Log.e(TAG, "onDestroy");
		super.onDestroy();
	}

	@Override
	public void onDetach() {
		Log.e(TAG, "onDetach");
		super.onDetach();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值