我有一个列表,我想使用搜索视图添加搜索功能。我有sqlite数据库和两个片段,我在其中添加产品,在另一个我在列表视图中显示产品。我想过滤此列表。我怎么能实现这个目标?我搜索了很多链接,但通过搜索所有我有困惑..我是新来的android所以PLZ任何人都可以帮助?你的帮助会很有意义..你... ..
这是我的主要活动
public class MainActivity extends AppCompatActivity implements android.support.v7.widget.SearchView.OnQueryTextListener{
Toolbar mToolbar;
public DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FrameLayout mContentFrame;
FragmentManager fragmentManager;
private static final String PREFERENCES_FILE = "mymaterialapp_settings";
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
private int mCurrentSelectedPosition;
public ArrayList<Item> arrayList;
public DBHandler db;
ArrayList<Item> array_data;
public SearchView searchView;
ListView listview;
public ArrayAdapter<Item> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav_drawer);
setUpToolbar();
arrayList=new ArrayList<Item>();
array_data=new ArrayList<Item>();
db = new DBHandler(this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.nav_drawer);
mUserLearnedDrawer = Boolean.valueOf(readSharedSetting(this, PREF_USER_LEARNED_DRAWER, "false"));
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
firstTimeFrag();
setUpNavDrawer();
mNavigationView = (NavigationView) findViewById(R.id.nav_view);
mContentFrame = (FrameLayout) findViewById(R.id.nav_contentframe);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
Fragment newFragment;
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
menuItem.setChecked(true);
switch (menuItem.getItemId()) {
case R.id.navigation_item_1:
newFragment = new AddStock();
transaction.replace(R.id.nav_contentframe, newFragment);
// transaction.addToBackStack(null);
transaction.commit();
mCurrentSelectedPosition = 0;
mDrawerLayout.closeDrawers();
return true;
case R.id.navigation_item_2:
newFragment = new ViewStock();
transaction.replace(R.id.nav_contentframe, newFragment);
// transaction.addToBackStack(null);
transaction.commit();
mCurrentSelectedPosition = 1;
mDrawerLayout.closeDrawers();
return true;
default:
return true;
}
}
});
//fragmentManager.beginTransaction().replace(R.id.nav_contentframe, fragment).commit();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION, 0);
Menu menu = mNavigationView.getMenu();
menu.getItem(mCurrentSelectedPosition).setChecked(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(this,R.menu.menu_main);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
case R.id.search_view:
return true;
}
return super.onOptionsItemSelected(item);
}
private void setUpToolbar() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
}
}
private void setUpNavDrawer() {
if (mToolbar != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mToolbar.setNavigationIcon(R.drawable.ic_drawer);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDrawerLayout.openDrawer(GravityCompat.START);
}
});
}
if (!mUserLearnedDrawer) {
mDrawerLayout.openDrawer(GravityCompat.START);
mUserLearnedDrawer = true;
saveSharedSetting(this, PREF_USER_LEARNED_DRAWER, "true");
}
}
public static void saveSharedSetting(Context ctx, String settingName, String settingValue) {
SharedPreferences sharedPref = ctx.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(settingName, settingValue);
editor.apply();
}
public static String readSharedSetting(Context ctx, String settingName, String defaultValue) {
SharedPreferences sharedPref = ctx.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE);
return sharedPref.getString(settingName, defaultValue);
}
private void firstTimeFrag(){
Fragment fr = new ViewStock();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.nav_contentframe, fr);
fragmentTransaction.commit();
}
}
this is my item class
public class Item {
public int id;
public String item_name;
public String item_desc;
public String item_qty;
public Item(){}
public Item(int id ,String item_name,String item_desc,String item_qty) {
super();
this.item_name = item_name;
this.item_desc = item_desc;
this.item_qty = item_qty;
}
public Item(String item_name,String item_desc, String item_qty){
this.item_name = item_name;
this.item_desc=item_desc;
this.item_qty = item_qty;
}
public int getID(){
return id;
}
public void setID(int id){
this.id= id;
}
public String getItem_name(){
return item_name;
}
public void setItem_name(String item_name)
{
this.item_name=item_name;
}
public String getItem_desc()
{
return item_desc;
}
public void setItem_desc(String item_desc)
{
this.item_desc=item_desc;
}
public String getItem_qty()
{
return item_qty;
}
public void setItem_qty(String item_qty) {
this.item_qty = item_qty;
}
}
this is my ItemAdapter
public class ItemAdapter extends ArrayAdapter<Item> implements Filterable {
Context context;
// ValueFilter valueFilter;
ArrayList<Item> mStringFilterList;
ArrayList<Item> items;
public ItemAdapter(Context context, int resourceId,
ArrayList<Item> items) {
super(context, resourceId, items);
this.context = context;
this.items=items;
mStringFilterList=items;
}
public int getCount() {
return items.size();
}
public Item getItem(int position) {
return items.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
Item rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.list_item, null);
holder.txtItemName = (TextView) convertView.findViewById(R.id.txt_item_name);
holder.txtItemDesc = (TextView) convertView.findViewById(R.id.txt_item_desc);
holder.txtItemQty = (TextView) convertView.findViewById(R.id.txt_item_qty);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtItemName.setText(rowItem.getItem_name());
holder.txtItemDesc.setText(rowItem.getItem_desc());
holder.txtItemQty.setText(rowItem.getItem_qty());
return convertView;
}
private class ViewHolder {
TextView txtItemName;
TextView txtItemDesc;
TextView txtItemQty;
}
}
this is my view stock fragment
public class ViewStock extends Fragment {
public ViewStock() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview = inflater.inflate(R.layout.fragment_view_stock, container, false);
MainActivity act = (MainActivity) this.getActivity();
act.listview = (ListView)rootview.findViewById(R.id.list);
act.listview.setTextFilterEnabled(true);
act.array_data = new ArrayList<Item>();
// Context mCtx = getActivity().getApplicationContext();
// ItemAdapter adapter = new ItemAdapter(getActivity(), R.layout.list_item, act.arrayList);
// listview.setAdapter(adapter);
act.db = new DBHandler(getActivity());
ArrayList<Item> item_array_from_db = act.db.Get_items();
for (int i = 0; i < item_array_from_db.size(); i++) {
int idno = item_array_from_db.get(i).getID();
String name = item_array_from_db.get(i).getItem_name();
String desc = item_array_from_db.get(i).getItem_desc();
String qty = item_array_from_db.get(i).getItem_qty();
Item cnt = new Item();
cnt.setID(idno);
cnt.setItem_name(name);
cnt.setItem_desc(desc);
cnt.setItem_qty(qty);
act.array_data.add(cnt);
}
act.db.close();
act.adapter = new ItemAdapter(getActivity(), R.layout.list_item,
act.array_data);
act.listview.setAdapter(act.adapter);
act.adapter.notifyDataSetChanged();
return rootview;
}
}
this is my database
public class DBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "stock";
private static final String TABLE_ITEMS = "items";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "itemname";
private static final String KEY_DESC = "itemdesc";
private static final String KEY_QTY = "itemqty";
private final ArrayList<Item> array_list = new ArrayList<Item>();
public DBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_ITEMS_TABLE = "CREATE TABLE " + TABLE_ITEMS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_DESC + " TEXT," + KEY_QTY + " INTEGER" + ")";
db.execSQL(CREATE_ITEMS_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ITEMS);
onCreate(db);
}
public void Add_Item(Item item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, item.getItem_name());
values.put(KEY_DESC, item.getItem_desc());
values.put(KEY_QTY, item.getItem_qty());
db.insert(TABLE_ITEMS, null, values);
db.close();
}
Item Get_Item(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_ITEMS, new String[] { KEY_ID,
KEY_NAME, KEY_DESC, KEY_QTY }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Item item = new Item(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3));
cursor.close();
db.close();
return item;
}
public ArrayList<Item> Get_items() {
try {
array_list.clear();
String selectQuery = "SELECT * FROM " + TABLE_ITEMS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Item item = new Item();
item.setID(Integer.parseInt(cursor.getString(0)));
item.setItem_name(cursor.getString(1));
item.setItem_desc(cursor.getString(2));
item.setItem_qty(cursor.getString(3));
array_list.add(item);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return array_list;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_contact", "" + e);
}
return array_list;
}
}
this is my view stock layout
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context="com.example.owner.stock.ViewStock">
<!-- TODO: Update blank fragment layout -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:id="@+id/header"
android:weightSum="1"
android:background="#ff45f3ff">
<TextView
android:id="@+id/lbl_item_name"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="@string/txt_item_name"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textStyle="bold"
android:layout_weight="0.33" />
<TextView
android:id="@+id/lbl_item_desc"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="@string/txt_item_desc"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textStyle="bold"
android:layout_weight="0.33" />
<TextView
android:id="@+id/lbl_item_qty"
android:layout_width="100dp"
android:layout_height="match_parent"
android:text="@string/txt_item_qty"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textStyle="bold"
android:layout_weight="0.33" />
</LinearLayout>
<ListView
android:layout_width="wrap_content"
android:layout_height="462dp"
android:id="@+id/list"
android:layout_gravity="center"
android:background="@android:color/background_light"
/>
</FrameLayout>
是的,任何人都可以帮我解决这个问题吗?我需要知道我们可以为sqlite使用过滤器类吗?我有一个片段,我有我的列表所以如何调用搜索活动?
答案 0 :(得分:0)
您可以使用ArrayAdapter
中的过滤器实例来过滤项目。
你的代码可以是这样的 -
mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;
mAdapter.getFilter().filter(mCurFilter);
可以从
中解雇public boolean onQueryTextChange(String newText)
实施方法SerachView
。
有关详细信息,您可以查看API Demo。
答案 1 :(得分:0)
public Filter getFilter() {
if (valueFilter == null) {
valueFilter = new ValueFilter();
}
return valueFilter;
}
private class ValueFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
ArrayList<Item> filterList = new ArrayList<Item>();
for (int i = 0; i < mStringFilterList.size(); i++) {
if ( (mStringFilterList.get(i).getItem_name())
.contains(constraint.toString())) {
Item item = new Item(mStringFilterList.get(i)
.getItem_name() , mStringFilterList.get(i)
.getItem_desc() , mStringFilterList.get(i)
.getItem_qty());
filterList.add(item);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = mStringFilterList.size();
results.values = mStringFilterList;
}
return results;
}
@Override
public void publishResults(CharSequence constraint,
FilterResults results) {
items = (ArrayList<Item>) results.values;
notifyDataSetChanged();
}
}
这是我的过滤器