这里我使用Assets将数据插入数据库。从数据库添加到列表视图中。我想在列表视图中搜索数据。这里我使用过滤器在列表视图中搜索数据。如何在列表视图中搜索数据。在这里,我附上代码。请帮助一些。 这里的数据显示在列表视图中。但是,在列表视图中搜索数据不起作用。
//这里使用资产将数据插入数据库。
public class CurrencyDataBase extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 2;
public static final String DATABASE_NAME = "currencyconverter.sqlite";
public static final String DB_PATH = "/databases/";
static Context context;
public CurrencyDataBase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
public void CopyDataBaseFromAsset() throws IOException {
InputStream myInput = context.getAssets().open(DATABASE_NAME);
// Path to the just created empty db
String outFileName = getDatabasePath();
// if the path doesn't exist first, create it
File f = new File(context.getApplicationInfo().dataDir + DB_PATH);
if (!f.exists())
f.mkdir();
Log.d("DATABASE", "THIS NAME DATABASE IS NOT EXISTS");
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
private static String getDatabasePath() {
return context.getApplicationInfo().dataDir + DB_PATH + DATABASE_NAME;
}
public SQLiteDatabase openDataBase() throws SQLException {
File dbFile = context.getDatabasePath(DATABASE_NAME);
if (!dbFile.exists()) {
try {
Log.d("DATABASE", "NOT-EXISTS");
CopyDataBaseFromAsset();
Log.d("DATABASE", "COPYING THE CONTENT DATA");
System.out.println("Copying sucess from Assets folder");
} catch (IOException e) {
throw new RuntimeException("Error creating source database", e);
}
}
return SQLiteDatabase.openDatabase(dbFile.getPath(), null,
SQLiteDatabase.NO_LOCALIZED_COLLATORS
| SQLiteDatabase.CREATE_IF_NECESSARY);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
public ArrayList<CountryArrList> getCountyNames() {
ArrayList<CountryArrList> arrayList = new ArrayList<CountryArrList>();
String s = "SELECT * FROM currencytable";
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(s, null);
if (c.moveToFirst()) {
do {
CountryArrList cntryList = new CountryArrList();
cntryList.setCountryName(c.getString(1));
Log.e("CNRY NAME", "NAME " + c.getString(1));
cntryList.setCountryCode(c.getString(2));
Log.e("CNRY CODE", "CODE " + c.getString(2));
arrayList.add(cntryList);
} while (c.moveToNext());
}
return arrayList;
}
}
//这里是mainActivity
public class HomeActivity extends ActionBarActivity
{
CurrencyDataBase dataBase;
ArrayList<CountryArrList> cntryList;
CountryDetailsAdapter adapter;
ListView listView;
private SearchView search_view;
EditText textWatcher;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
listView = (ListView) findViewById(R.id.Cntry_Listview);
//autoComplete = (AutoCompleteTextView) findViewById(R.id.autoComplete);
// search_view = (SearchView) findViewById(R.id.cntry_listview_search);
textWatcher = (EditText) findViewById(R.id.TextWatcher);
dataBase = new CurrencyDataBase(getApplicationContext());
dataBase.openDataBase();
cntryList = dataBase.getCountyNames();
adapter = new CountryDetailsAdapter(this,
android.R.layout.simple_list_item_1, cntryList);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
//autoComple=(CustomAutoCompleteView)findViewById(R.id.myautocomplete);
//autoComple.addTextChangedListener(new CustomAutoCompleteTextChangedListener(this));
textWatcher.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
Log.e("onTextChanged", "onTextChanged"+s);
//String string=textWatcher.getText().toString().toLowerCase(Locale.getDefault());
adapter.getFilter().filter(s.toString());
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
Log.e("beforeTextChanged", "beforeTextChanged"+s);
}
@Override
public void afterTextChanged(Editable s) {
Log.e("afterTextChanged", "afterTextChanged"+s);
}
});
}
}
// CountryDetailsAdapter Adapter
public class CountryDetailsAdapter extends ArrayAdapter<CountryArrList> implements Filterable {
ArrayList<CountryArrList> cntryList;
ArrayList<CountryArrList> serachList;
Context context;
public CountryDetailsAdapter(Context activity, int simpleListItem1,
ArrayList<CountryArrList> cntryList) {
super(activity, simpleListItem1, cntryList);
this.serachList=cntryList;
this.cntryList = cntryList;
this.context = activity;
}
public class ViewHolder {
TextView cntry_name, cntry_code;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
CountryArrList cntryList1 = getItem(position);
LayoutInflater inflator = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
holder = new ViewHolder();
convertView = inflator.inflate(R.layout.activity_cntry_adapter,
parent, false);
holder.cntry_name = (TextView) convertView
.findViewById(R.id.adapter_cntry_name);
holder.cntry_code = (TextView) convertView
.findViewById(R.id.adapter_cntry_code);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
for (int i = 0; i < cntryList1.countryCode.length(); i++) {
if (position % 2 == 0) {
convertView.setBackgroundColor(Color.parseColor("#2691D7"));
} else {
convertView.setBackgroundColor(Color.parseColor("#005D9A"));
}
holder.cntry_name.setText(cntryList1.getCountryName());
holder.cntry_code.setText(cntryList1.getCountryCode());
}
return convertView;
}
public Filter geFilter()
{
Filter f=new Filter()
{
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results=new FilterResults();
ArrayList<CountryArrList> filterdArrList=new ArrayList<CountryArrList>();
if(serachList==null)
{
serachList=new ArrayList<CountryArrList>(cntryList);
}
if(constraint == null||constraint.length()==0)
{
results.count=serachList.size();
results.values=serachList;
}
else
{
constraint=constraint.toString().toLowerCase();
for(int i=0;i<serachList.size();i++)
{
String data=serachList.get(i).countryName;
if(data.toLowerCase().startsWith(constraint.toString()))
{
filterdArrList.add(new CountryArrList(serachList.get(i).countryName, serachList.get(i).countryCode));
}
}
results.count=filterdArrList.size();
results.values=filterdArrList;
}
return results;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
serachList=(ArrayList<CountryArrList>)results.values;
notifyDataSetChanged();
}
};
return f;
}
//国家/地区类 package com.example.currencyconverter;
public class CountryArrList {
String countryName;
String countryCode;
public CountryArrList(String name, String code) {
this.countryName = name;
this.countryCode = code;
}
public CountryArrList() {
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
}
答案 0 :(得分:0)
要实现搜索功能,您需要更改适配器。 将以下ArrayList对象添加到适配器,并在构造函数中初始化它,如下所示。
private ArrayList<CountryArrList> arraylist;
public CountryDetailsAdapter(Context activity, int simpleListItem1, ArrayList<CountryArrList> cntryList) {
super(activity, simpleListItem1,cntryList);
...
arraylist=new ArrayList<>();
arraylist.addAll(cntryList);
}
现在将以下过滤器方法添加到Adapter类中。
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
cntryList.clear();
if (charText.length() == 0) {
cntryList.addAll(arraylist);
} else {
for (CountryArrList countryArrItem : cntryList) {
if (countryArrItem.getCountryName().toLowerCase(Locale.getDefault())
.contains(charText)) {
cntryList.add(countryArrItem);
}
}
}
notifyDataSetChanged();
}
要从列表视图中搜索它,请在视图中添加EditText。并将以下代码应用于EditText以从ListView中搜索,并在ListView中显示搜索结果。
etSearch.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
String text = etSearch.getText().toString().toLowerCase(Locale.getDefault());
CountryDetailsAdapter.filter(text);
}
});