listview onClick返回错误的结果

时间:2017-10-02 07:31:09

标签: android sqlite listview search

我有来自SQLite数据库的数据的自定义列表视图。我可以添加和编辑项目。此外,我在工具栏中有SearchVIew按名称列出项目。

问题在于,当我想编辑项目并使用SearchView查找它时,onClick方法返回错误的id(列表中第一个项目)。 如果我不使用搜索,那么一切都很好。例如:no search

search

我的班级代码:

public class ProductCategoryActivity extends AppCompatActivity {

private ListView myProductsList;
private DataBaseHelper dataBaseHelper;
private SQLiteDatabase db;
private Cursor productCursor;
private ArrayList<Product> productList;
private int tableId;
private String dbName;

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    Intent idOfGroup = new Intent(getIntent());
    tableId = idOfGroup.getIntExtra("table_id", 0);

    myProductsList = (ListView) findViewById(R.id.lvMyProducts);

    switch (tableId) {
        case 1:
            dbName = DataBaseHelper.TABLE_MY_PRODUCTS;
            break;
    }

    //allow adding and editing products if tableId == 1
    if (tableId == 1) {
        myProductsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //get id by click on list view item
                String sql = "SELECT " + DataBaseHelper.COLUMN_ID + "  FROM " + dbName;
                productCursor = db.rawQuery(sql, null);
                ArrayList<Long> arrayList = new ArrayList<>();
                if (productCursor.moveToFirst()) {
                    do {
                        arrayList.add(Long.parseLong(productCursor.getString(0)));
                    } while (productCursor.moveToNext());
                } else {
                    throw new NullPointerException();
                }
                //sending id to another activity
                Intent intent = new Intent(ProductCategoryActivity.this, ProductAddEditActivity.class);
                intent.putExtra("id", arrayList.get(position));
                startActivity(intent);
            }
        });
    }
    dataBaseHelper = new DataBaseHelper(getApplicationContext());
    //creating db
    dataBaseHelper.create_db();

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.newProduct:
            Intent intent = new Intent(ProductCategoryActivity.this, ProductAddEditActivity.class);
            startActivity(intent);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

@Override
public void onResume() {
    super.onResume();
    productList = new ArrayList<>();
    productList.clear();
    db = dataBaseHelper.open();
    //get data from db
    productCursor = db.rawQuery("select * from " + dbName, null);
    setProduct();
}


//product search by name
public Cursor getProductListByKeyword(String search) {
    productList = new ArrayList<>();
    productList.clear();
    db = dataBaseHelper.open();
    //get data from db by word
    productCursor = db.rawQuery("SELECT * FROM " + dbName + " WHERE "
            + DataBaseHelper.COLUMN_NAME + "  LIKE  '%" + search + "%' ", null);
    setProduct();
    return productCursor;
}

private void setProduct() {
    //select  required columns
    if (productCursor != null && productCursor.getCount() != 0) {
        if (productCursor.moveToFirst()) {
            do {
                Product product = new Product();
                product.setProductName(productCursor.getString(productCursor.getColumnIndex(DataBaseHelper.COLUMN_NAME)));

                productList.add(product);
            } while (productCursor.moveToNext());
        }
    }
    productCursor.close();
    ProductListAdapter productListAdapter = new ProductListAdapter(this, productList);
    myProductsList.setAdapter(productListAdapter);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    //the add button is hidden if tableId != 1
    if (tableId != 1) {
        MenuItem menuItem = menu.findItem(R.id.newProduct);
        menuItem.setVisible(false);
    }
    SearchView searchView = (SearchView) menu.findItem(R.id.searchForSee).getActionView();
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String s) {
            productCursor = getProductListByKeyword(s);
            Toast.makeText(ProductCategoryActivity.this, productCursor.getCount() + " " +
                            getString(R.string.txt_products_found),
                    Toast.LENGTH_LONG)
                    .show();
            return false;
        }
        @Override
        public boolean onQueryTextChange(String s) {
            productCursor = getProductListByKeyword(s);
            return false;
        }
    });
    return true;

}
@Override
public void onDestroy() {
    super.onDestroy();
    db.close();
    productCursor.close();
}

2 个答案:

答案 0 :(得分:0)

我认为你的问题就是如何获得这个ID。首先从表中获取所有列ID,然后创建一个ID数组,然后根据位置从那里选择一个条目。

无论您的搜索结果如何,您的arrayList变量将始终包含表中的所有ID。因此,当您访问arrayList.get(position)时,它将返回表中该位置的对象,而不是列表中的对象。

您应该使用long id或更改SQL查询,以便只获得条目,以便在SQL结果中遵守您的搜索测试。

这样的某些人可能

String sql = "SELECT " + DataBaseHelper.COLUMN_ID + "  FROM " + dbName + " WHERE " + DataBaseHelper.COLUMN_NAME + "=" + searchText;

相应地更改变量。

比这更简单,你可以简单地使用传递的long id

答案 1 :(得分:0)

我在onClick方法中解决了我的问题:

 myProductsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //get id by click on list view item
                long productId;
                if (productCursor.moveToPosition(position)) {
                    productId = Long.parseLong(productCursor.getString(0));
                } else {
                    throw new NullPointerException();
                }
                //sending id to another activity
                Intent intent = new Intent(ProductCategoryActivity.this, ProductAddEditActivity.class);
                intent.putExtra("id", productId);
                startActivity(intent);
            }
        });