android - 这个java文件中的差异docid(SELECT docid as _id)

时间:2016-05-12 11:21:43

标签: android sqlite select search

我正在搜索关键字使用" SELECT docid as _id(blabla)" .. 使用第一个DBAdapter,我可以搜索关键字我输入..但第二个... 为什么??

DBAdapter(docid works)

package inklinked.tessearchtambahfitur;

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

public class DBAdapter {

public static final String KEY_ROWID = "rowid";
public static final String KEY_CUSTOMER = "customer";
public static final String KEY_NAME = "name";
public static final String KEY_ADDRESS = "address";
public static final String KEY_ADDRESS1 = "address1";
public static final String KEY_ADDRESS2 = "address2";
public static final String KEY_CITY = "city";
public static final String KEY_STATE = "state";
public static final String KEY_ZIP = "zipCode";
public static final String KEY_SEARCH = "searchData";

private static final String TAG = "CusomersDBAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;

private static final String DATABASE_NAME = "CustomerData";
private static final String FTS_VIRTUAL_TABLE = "CustomerInfo";
private static final int DATABASE_VERSION = 1;

//Create a FTS3 Virtual Table for fast searches
private static final String DATABASE_CREATE =
        "CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE + " USING fts3(" +
            KEY_NAME + "," +
                " UNIQUE (" + KEY_NAME + "));";


private final Context mCtx;

private static class DatabaseHelper extends SQLiteOpenHelper {

    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.w(TAG, DATABASE_CREATE);
        db.execSQL(DATABASE_CREATE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS " + FTS_VIRTUAL_TABLE);
        onCreate(db);
    }
}

public DBAdapter(Context ctx) {
    this.mCtx = ctx;
}

public DBAdapter open() throws SQLException {
    mDbHelper = new DatabaseHelper(mCtx);
    mDb = mDbHelper.getWritableDatabase();
    return this;
}

public void close() {
    if (mDbHelper != null) {
        mDbHelper.close();
    }
}


public long createCustomer( String name) {

    ContentValues initialValues = new ContentValues();
    String searchValue =    name ;
    initialValues.put(KEY_NAME, name);
    //initialValues.put(KEY_SEARCH, searchValue);

    return mDb.insert(FTS_VIRTUAL_TABLE, null, initialValues);
}


public Cursor searchCustomer(String inputText) throws SQLException {
    Log.w(TAG, inputText);
    String query = "SELECT docid as _id," +
            KEY_NAME +
            " from " + FTS_VIRTUAL_TABLE +
            " where " +  KEY_NAME + " MATCH '" + inputText + "';";
    Log.w(TAG, query);
    Cursor mCursor = mDb.rawQuery(query,null);

    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;

}


public boolean deleteAllCustomers() {

    int doneDelete = 0;
    doneDelete = mDb.delete(FTS_VIRTUAL_TABLE, null , null);
    Log.w(TAG, Integer.toString(doneDelete));
    return doneDelete > 0;

   }

}

DBAdapter(docid fail)#i已经改为SELECT _id,(blabla),没有错误,并连接到我的MainDIY(搜索活动),但它无法显示搜索结果

    package inklinked.tessearchtambahfitur;

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

    import java.util.ArrayList;
    import java.util.List;

import timber.log.Timber;

public class DBAdapter
{
    private static final String DB_NAME     = "contact_db";
    private static final int    DB_VER      = 1;

    public static final String  FTS_VIRTUAL_TABLE   = "contact";
    public static final String  COL_ID      = "_id";
    public static final String  COL_NAME    = "name";
    public static final String  COL_SEARCH  = "searchData";
    public static final String  COL_TELP    = "telp";

    private static final String TAG         = "ContactDBAdapter";
    private DatabaseHelper      dbHelper;
    private SQLiteDatabase db;

    private static final String DB_CREATE   = "CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE + " USING fts3(" +
            COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_NAME + "TEXT NOT NULL," +
            " UNIQUE (" + COL_NAME + "));";

    private final Context context;

    private static class DatabaseHelper extends SQLiteOpenHelper
    {

        public DatabaseHelper(Context context)
        {
            // TODO Auto-generated constructor stub
            super(context, DB_NAME, null, DB_VER);
        }

        @Override
        public void onCreate(SQLiteDatabase db)
        {
            // TODO Auto-generated method stub
            db.execSQL(DB_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
        {
            // TODO Auto-generated method stub
            Log.d(TAG, "upgrade DB");
            db.execSQL("DROP TABLE IF EXISTS " + FTS_VIRTUAL_TABLE);
            onCreate(db);

        }

    }

    public DBAdapter(Context context)
    {
        this.context = context;
        // TODO Auto-generated constructor stub
    }

    public DBAdapter open() throws SQLException
    {
        dbHelper = new DatabaseHelper(context);
        db = dbHelper.getWritableDatabase();
        return this;
    }

    public void close()
    {
        if (dbHelper != null) {
            dbHelper.close();
        }
    }

    public void createContact(DataDIY contact)
    {
        ContentValues val = new ContentValues();
        //String searchValue = name;
        val.put(COL_NAME, contact.getName());
        //val.put(COL_TELP, contact.getTelp());
        db.insert(FTS_VIRTUAL_TABLE, null, val);
    }

    public boolean deleteContact(int id)
    {
        return db.delete(FTS_VIRTUAL_TABLE, COL_ID + "=" + id, null) > 0;
    }

    public Cursor getAllContact()
    {
        return db.query(FTS_VIRTUAL_TABLE, new String[]
                {
                        COL_ID, COL_NAME
                }, null, null, null, null, null);
    }

    public Cursor getSingleContact(int id)
    {
        Cursor cursor = db.query(FTS_VIRTUAL_TABLE, new String[]
                {
                        COL_ID, COL_NAME
                }, COL_ID + "=" + id, null, null, null, null);

        if (cursor != null)
            cursor.moveToFirst();

        return cursor;
    }

    public boolean updateContact(DataDIY contact)
    {
        ContentValues val = new ContentValues();
        val.put(COL_NAME, contact.getName());
        //val.put(COL_TELP, contact.getTelp());

        return db.update(FTS_VIRTUAL_TABLE, val, COL_ID + "=" + contact.getId(), null) > 0;
    }

    public Cursor searchByInputText(String inputText) throws SQLException {

        Log.w(TAG, inputText);
        String query = "SELECT docid as _id," +
                COL_NAME +
                " from " + FTS_VIRTUAL_TABLE +
                " where " +  COL_NAME + " LIKE '%" + inputText + "%'";
        Log.w(TAG, query);
        Cursor mCursor = db.rawQuery(query,null);

        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;


    }

}

我的MainDIY.java

import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.content.Intent;
import android.database.Cursor;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.support.v7.widget.SearchView;
//search


import timber.log.Timber;


public class MainDIY extends ActionBarActivity implements OnItemClickListener, SearchView.OnQueryTextListener, SearchView.OnCloseListener
{
    public static final String  KEY_ID      = "_id";

    private static final int    INSERT_ID   = Menu.FIRST;

    private DBAdapter           db;

    ImageView btnCari,btnAdd;
    FloatingActionButton fab;

    private static final String TAG = "DIY";

    ListView listview;
    //private ArrayList<String> arraylist=new ArrayList<String>();
    private SQLiteDatabase MYdatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diy);
        Timber.d("line 37, content activity_diy");
        db = new DBAdapter(this);
        db.open();

        listview = (ListView) findViewById(R.id.list);

        listview.setEmptyView(findViewById(R.id.empty));

/*
        db.createCustomer("PIZZA1");
        db.createCustomer("PIZZA2");
        db.createCustomer("PIZZA3");

*/

        // float button
        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainDIY.this, AddDIY.class);
                startActivity(intent);
            }
        });


        listview.setOnItemClickListener(this);

    }

    // menampilkan apa yang dicari dan ada di database
    private void hasilPencarian(String query) {
        /** menampilkan apa yang dicari dan ada di database */

        Cursor cursor = db.searchByInputText((query != null ? query.toString() : "@@@@"));

        if (cursor == null) {
            //
        } else {
            // Specify the columns we want to display in the result
            String[] from = new String[] {

                    DBAdapter.COL_NAME};
            // Specify the Corresponding layout elements where we want the columns to go
            int[] to = new int[] {
                    R.id.search_text_view}; Log.d("MainDIY","r.id.searchtextview");


            // Create a simple cursor adapter for the definitions and apply them to the ListView
            android.widget.SimpleCursorAdapter customers = new android.widget.SimpleCursorAdapter(this,R.layout.search_item, cursor, from, to);
            Log.d("MainDIY",query);
            listview.setAdapter(customers);
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        // Inflate menu to add items to action bar if it is present.
        inflater.inflate(R.menu.menu_main, menu);
        // Associate searchable configuration with the SearchView
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();

        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        searchView.setIconifiedByDefault(false);

        SearchView.OnQueryTextListener textChangeListener = new SearchView.OnQueryTextListener() {
            @Override

            public boolean onQueryTextChange(String newText) {

            if (!newText.isEmpty()){
            hasilPencarian(newText + "*");
            Timber.i("text berubah "+newText.toString());
            } else {

                Timber.i("searchview kosong");
            }
                return false;
            }

            public boolean onQueryTextSubmit(String query) {
                hasilPencarian(query + "*");
                return false;
            }

        };
        searchView.setOnQueryTextListener(textChangeListener);

        return super.onCreateOptionsMenu(menu);
    }






   @Override
    public void onItemClick(AdapterView<?> arg0, View v, int pos, long id)
    {
        // TODO Auto-generated method stub
        Bundle bundle = new Bundle();
        bundle.putLong(KEY_ID, id);
        Intent intent = new Intent(MainDIY.this, EditDIY.class);
        intent.putExtras(bundle);
        db.close();
        startActivity(intent);

    }

    @Override
    public boolean onClose() {
        Timber.d("onclose");
        hasilPencarian("");
        return false;

    }


    public boolean onQueryTextChange(String newText) {
        hasilPencarian(newText + "*");
        return false;
    }

    public boolean onQueryTextSubmit(String query) {
        hasilPencarian(query + "*");
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (db  != null) {
            db.close();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        handleIntent(intent);
    }

    private void handleIntent(Intent intent) {

        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            String query = intent.getStringExtra(SearchManager.QUERY);
            //use the query to search
        }
    }


}

1 个答案:

答案 0 :(得分:0)

它可以显示它的工作 对于新手想要学习CRUD和搜索SQLite本地数据库,请查看my github