在Android中实现数据库搜索

时间:2016-07-10 11:35:34

标签: android database android-studio android-search

我使用数据库创建了一个简单的列表应用程序。我想在此添加搜索功能。我能够实现搜索,但是当我单击搜索列表中的项目时,它始终会打开列表中第一个项目的屏幕。我希望能够在搜索列表中单击并查看任何人的详细信息。请帮忙......

主要活动

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.*;
import android.widget.*;
import java.util.ArrayList;


public class MainActivity extends AppCompatActivity {

public static ArrayList<String> Array_Names= new ArrayList<String>();

MyDBHandler dbHandler;
MyDBHandler d1;
EditText searchtext;
ListView mylist;
ArrayAdapter<String> myAdapter;


private android.support.v7.widget.Toolbar toolbar;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    dbHandler = new MyDBHandler(this, null, null, 1);
    d1= new MyDBHandler(this,null,null,1);
    searchtext=(EditText)findViewById(R.id.searchtext);
    /*dbHandler.addProduct(new Product("Mike", "222222222"));
    dbHandler.addProduct(new Product("Ashley", "333333333"));
    dbHandler.addProduct(new Product("Kevin", "444444444"));
    dbHandler.addProduct(new Product("Nathan", "555555555"));*/
    /*toolbar=(Toolbar)findViewById(R.id.tool_bar);
    setSupportActionBar(toolbar);*/
    ScreenDetails();



}

public void ScreenDetails(){
    dbHandler.getAllContacts();

    mylist= (ListView)findViewById(R.id.mylist);
    myAdapter= new CustomAdapter(this,Array_Names);
    mylist.setAdapter(myAdapter);
    searchtext.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
            // When user changed the Text
            myAdapter.getFilter().filter(cs);

        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub
        }
    });

    final Intent intent=new Intent(this,Display.class);
    mylist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            d1.addSortedProduct();
            int pass_id=position+1;
            Bundle data_bundle= new Bundle();
            data_bundle.putInt("id",pass_id);
            intent.putExtras(data_bundle);
            startActivity(intent);

        }
    });
}
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);

    return super.onCreateOptionsMenu(menu);

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    switch (item.getItemId()) {


        default:
            return super.onOptionsItemSelected(item);
    }
}

产品类

public class Product {

private int _id;
private String _CName;
private String _phno;

public Product(){

}
public Product(String _CName, int _id, String _phno) {
this._CName = _CName;
this._id = _id;
this._phno = _phno;
}

public Product(String _CName, String _phno) {
this._CName = _CName;
this._phno = _phno;
}

public String get_CName() {
return _CName;
}

public void set_CName(String _CName) {
this._CName = _CName;
}

public int get_id() {
return _id;
}

public void set_id(int _id) {
this._id = _id;
}

public String get_phno() {
return _phno;
}

public void set_phno(String _phno) {
this._phno = _phno;
}
}

数据库处理程序

import android.database.sqlite.*;
import android.content.*;
import android.database.Cursor;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;

public class MyDBHandler extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1; //Change whenever db is modified.
private static final String DATABASE_NAME = "List.db";    //Db name
public static final String TABLE_NAME = "CustomerList";       //Table Name
public static final String COLUMN_ID = "Id";                  //Column Name
public static final String COLUMN_CNAME = "Name";
public static final String COLUMN_PHNO= "PhoneNumber";

public MyDBHandler(Context context, String name,SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);     //Context is always background info.
}


@Override
public void onCreate(SQLiteDatabase db) {
String query = " CREATE TABLE " + TABLE_NAME + " ( " +

        COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT " + " , " +
        COLUMN_CNAME + " TEXT, " +
        COLUMN_PHNO + " TEXT " +
        " ); ";
db.execSQL(query);



}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(" DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}

public void addProduct(Product product) {
ContentValues values = new ContentValues();
values.put(COLUMN_CNAME, product.get_CName());
values.put(COLUMN_PHNO,product.get_phno());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_NAME, null, values);
db.close();
}

public void removeProduct(String name) {
SQLiteDatabase db = getWritableDatabase();
db.execSQL(" DELETE FROM " + TABLE_NAME + " WHERE " + COLUMN_CNAME + " =\" " + name + " \"; ");
}


public List<Product> getAllContacts(){
List<Product> contactList=new ArrayList<Product>();
SQLiteDatabase db= this.getWritableDatabase();
String Select_query= " SELECT * FROM " + TABLE_NAME + " ORDER BY " + COLUMN_CNAME;
Cursor cursor= db.rawQuery(Select_query,null);

if(cursor.moveToFirst()){
    do {
        Product contact= new Product();
        contact.set_id(Integer.parseInt(cursor.getString(0)));
        contact.set_CName(cursor.getString(1));
        contact.set_phno(cursor.getString(2));
        String name=cursor.getString(1) + "\n";
        MainActivity.Array_Names.add(name);
        contactList.add(contact);
    }while (cursor.moveToNext());
}

return contactList;
}
public Product getProduct(String name){
SQLiteDatabase db=this.getWritableDatabase();
String query= "SELECT * FROM " + TABLE_NAME + " WHERE " + COLUMN_CNAME + "=\""+ name+"\"";
Cursor cursor=db.rawQuery(query,null);
Log.d("This is the Name",name);
Product product= new Product();
if(cursor.moveToFirst()){
    cursor.moveToFirst();
    product.set_id(Integer.parseInt(cursor.getString(0)));
    product.set_CName((cursor.getString(1)));
    product.set_phno(cursor.getString(2));
    cursor.close();
}
db.close();
return product;


}
}

展示班级

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class Display extends AppCompatActivity {

TextView pname;
TextView pno;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);

Bundle main_data=getIntent().getExtras();
String message= main_data.getString("Name");
pname=(TextView)findViewById(R.id.pname);
pno=(TextView)findViewById(R.id.pno);


pname.setText(message);
MyDBHandler db=new MyDBHandler(this,null,null,1);
Product product= db.getProduct(pname.getText().toString());
pno.setText(product.get_phno());


}
}

自定义适配器

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
public class CustomAdapter extends ArrayAdapter<String> {

public CustomAdapter(Context context, ArrayList<String> names) {
super(context, R.layout.custom_list, names);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater myinflater= LayoutInflater.from(getContext());
View customView= convertView;
if(customView==null){
    customView=myinflater.inflate(R.layout.custom_list,parent,false);

}
String singleItem=getItem(position);
TextView mytext=(TextView) customView.findViewById(R.id.name);
ImageView defimage=(ImageView) customView.findViewById(R.id.myimage);

mytext.setText(singleItem);
defimage.setImageResource(R.mipmap.contacts_default);
return customView;


}

}

2 个答案:

答案 0 :(得分:0)

在我看来,你的显示类:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);

Bundle main_data=getIntent().getExtras();
String message= main_data.getString("Name");
...
...

在这里,您可以通过键&#34; Name&#34;来获取额外内容。但是在你的听众中:

 mylist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            d1.addSortedProduct();
            int pass_id=position+1;
            Bundle data_bundle= new Bundle();
            data_bundle.putInt("id",pass_id);
            intent.putExtras(data_bundle);

您正在传递ID,我不会在显示活动中看到它被使用。 您必须使用ID来了解您刚刚点按的列表中的哪个项目,这样您就可以针对不同的项目获得不同的结果。

如果我错了,请纠正我。

编辑

我认为你应该覆盖getItemid()中的Custom adapter方法,这样你就可以把额外的东西作为你的itemId不使用id_ = position +1交易。

答案 1 :(得分:0)

我会在OnItemClick上使用listview方法,根据个人详细信息为您选择打开新意图或新片段。