Android SQLite与AutoCompleteTextView

读取SQLite中的数据显示在AutoCompleteTextView中,支持动态加入SQLite中不存在的数据.

package zhang.ya;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.TextView;

public class Test00 extends Activity implements TextWatcher, OnClickListener
{
    private final String DATABASE_PATH = android.os.Environment.getExternalStorageDirectory().getAbsolutePath()
            + "/course_name";
    private AutoCompleteTextView courseName;
    private final String DATABASE_FILENAME = "course_name.db3";
    private SQLiteDatabase database;
    private Button btnSelectWord;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);
        database = openDatabase();
        courseName = (AutoCompleteTextView) findViewById(R.id.courseName);
        courseName.setThreshold(1);
        courseName.addTextChangedListener(this);
        btnSelectWord = (Button) findViewById(R.id.buttonName);
        btnSelectWord.setOnClickListener(this);
    }

    public class CourseNameAdapter extends CursorAdapter
    {
        private LayoutInflater layoutInflater;

        @Override
        public CharSequence convertToString(Cursor cursor)
        {
            return cursor == null ? "" : cursor.getString(cursor.getColumnIndex("course_name"));
        }

        private void setView(View view, Cursor cursor)
        {
            TextView tvWordItem = (TextView) view;
            tvWordItem.setText(cursor.getString(cursor.getColumnIndex("course_name")));
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor)
        {
            setView(view, cursor);
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent)
        {
            View view = layoutInflater.inflate(R.layout.word_list_item, null);
            setView(view, cursor);
            return view;
        }

        public CourseNameAdapter(Context context, Cursor c, boolean autoRequery)
        {
            super(context, c, autoRequery);
            layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
    }

    //输入为空则使得确定按钮失效,只有输入了数据才使得按钮处于活动状态
    @Override
    public void afterTextChanged(Editable s)
    {
        Log.i("zhangya", "textchage");
        String contentStr = s.toString();
        
        if (contentStr == null || contentStr.length() <= 0)//判断contentStr是否为空,判断字符串是否为空典型写法
        {
            Log.i("zhangya", "afterTextChanged null");
            btnSelectWord.setEnabled(false);//为空则不是能按钮

        } else
        {
            Log.i("zhangya", "afterTextChanged not null");
            btnSelectWord.setEnabled(true);
            Cursor cursor = database.rawQuery("select * from course_name where course_name like ?", new String[]
            { contentStr + "%" });

            CourseNameAdapter dictionaryAdapter = new CourseNameAdapter(this, cursor, true);
            courseName.setAdapter(dictionaryAdapter);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after)
    {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count)
    {

    }

    private SQLiteDatabase openDatabase()
    {
        try
        {
            String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME;
            File dir = new File(DATABASE_PATH);
            if (!dir.exists())
                dir.mkdir();
            if (!(new File(databaseFilename)).exists())
            {
                InputStream is = getResources().openRawResource(R.raw.course_name);
                FileOutputStream fos = new FileOutputStream(databaseFilename);
                byte[] buffer = new byte[8192];
                int count = 0;
                while ((count = is.read(buffer)) > 0)
                {
                    fos.write(buffer, 0, count);
                }

                fos.close();
                is.close();
            }
            SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(databaseFilename, null);
            return database;
        } catch (Exception e)
        {
        }
        return null;
    }

    @Override
    public void onClick(View v)
    {
        String sql = "select * from course_name where course_name=?";
        Cursor cursor = database.rawQuery(sql, new String[]
        { courseName.getText().toString() });
        if (cursor.getCount() == 0)//没有同名记录,则插入数据
        {
            sql = "insert into course_name(course_name)values(?)";
            database.execSQL(sql, new Object[]
            { courseName.getText().toString() });
        } else
        {
            Log.i("zhangya", "else");
        }
        cursor.moveToFirst();

    }

}

效果图:

技术分享技术分享

技术分享技术分享技术分享

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。