如何启用搜索功能以从Listview中查找所有值?

时间:2018-08-24 11:15:01

标签: java sql loops listview search

我正在Android Studio中构建适用于Android的应用程序,并且试图在Listview中找到一个基于基于云的SQL Server填充的String值。我正在使用适用于Android 8.0的API 26。到目前为止,它正在起作用并找到了一些价值。

问题-当我在模拟器上进行最后(第三次)活动并将字符串值插入搜索字段时,它找不到所有内容和整个值。 例如,我有一个完整的值列表(Apple,Orange,Red Apple,Grapes等)。当搜索产品Apple时,会发生这样的情况,即在键入“ ap”后找到它并在键入“ app”后立即消失。另外,尝试查找Orange时,键入第一个字母o时不会显示任何内容。

这似乎无法在地图中找到所有值。

我尝试调试适配器中的Loop。似乎可以正确理解约束条件,获取正确的“ i”计数,并找到包含该约束条件的所有结果。

我的适配器:

package com.example.user.sortiment;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Created by User
 */

public class SortimentAdapter extends BaseAdapter {

LayoutInflater mInflator;
List<Sortiment> map;
List<Sortiment> filterMap;

    public void performFiltering(CharSequence constraint) {

        String filterString = constraint.toString().toLowerCase();
        if (Objects.equals(filterString, "")) {
            filterMap.clear();
            filterMap.addAll(map);
            notifyDataSetChanged();
            return;
        }

        int count = map.size();
        filterMap.clear();


        for (int i = 0; i < count; i++) {
            Sortiment filterableSortiment = map.get(i);
            if (filterableSortiment.name.toLowerCase().contains(filterString)) {
                filterMap.add(filterableSortiment);
            }
        }

        notifyDataSetChanged();

    }

public SortimentAdapter(Context c, List<Sortiment> inputMap) {
    mInflator = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    filterMap = new ArrayList<>();
    filterMap.addAll(inputMap);
    map = new ArrayList<>();
    map.addAll(inputMap);
}

@Override
public int getCount() {
    return filterMap.size();
}

@Override
public Object getItem(int position) {
    return filterMap.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    ViewHolder viewHolder;

    if (convertView == null) {
        convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
        viewHolder = new ViewHolder(convertView);
        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }

    Sortiment viewObject = filterMap.get(position);
    viewHolder.nameTextView.setText(viewObject.name);
    viewHolder.priceTextView.setText(viewObject.ean.toString());

    return convertView;
}
private class ViewHolder {
    TextView nameTextView;
    TextView priceTextView;

    public ViewHolder(View view) {
        nameTextView = (TextView)view.findViewById(R.id.nameTextView);
        priceTextView = (TextView) view.findViewById(R.id.priceTextView);
    }
}
}

和我的活动:

package com.example.user.sortiment;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SearchView;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class SortimentActivity extends AppCompatActivity {

List<Sortiment> sortimentMap = new ArrayList<>();
SortimentAdapter sortimentAdapter;
Context thisContext;
EditText edtSearch;
ListView myListView;

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

    Integer selectedStoreId = getIntent().getExtras().getInt("store_id");


    edtSearch = (EditText)findViewById(R.id.edtSearch);
    myListView = (ListView) findViewById(R.id.storesListView);
    thisContext = this;

    edtSearch.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if (sortimentAdapter != null){
                sortimentAdapter.performFiltering(charSequence);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    });


    GetSortimentForStore retrieveData = new GetSortimentForStore();
    retrieveData.execute(selectedStoreId);

}

public void performFiltering(CharSequence constraint) {

    List<Sortiment> filteredList = new ArrayList<>();

    String filterString = constraint.toString().toLowerCase();
    if (Objects.equals(filterString, "")) {
        filteredList.addAll(sortimentMap);
        sortimentAdapter.notifyDataSetChanged();
        return;
    }

    int count = sortimentMap.size();
    filteredList.clear();


    for (int i = 0; i < count; i++) {
        Sortiment filterableSortiment = sortimentMap.get(i);
        if (filterableSortiment.name.toLowerCase().contains(filterString)) {
            filteredList.add(filterableSortiment);
        }
    }

    sortimentAdapter = new SortimentAdapter(thisContext, filteredList);

    sortimentAdapter.notifyDataSetChanged();

}

private class GetSortimentForStore extends AsyncTask<Integer,String,String> {

    String msg = "";
    // JDBC Driver name and database URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    // Example 10.20.30.40:3306
    static final String DB_URL = "jdbc:mysql://" +
            DbStrings.DATABASE_URL + "/" +
            DbStrings.DATABASE_NAME;

    @Override
    protected void onPreExecute() {

        //progressTextView.setText("Connecting...");
    }

    @Override
    protected String doInBackground(Integer... selectedStores) {

        Connection conn = null;
        Statement stmt = null;

        try {
            Integer selectedStore = selectedStores[0];
            Class.forName(JDBC_DRIVER);
            conn = DriverManager.getConnection(DB_URL, DbStrings.USERNAME, DbStrings.PASSWORD);

            stmt = conn.createStatement();
            String sql = "select id, store_id, name, ean, description from myproject.sortiments WHERE store_id = " + selectedStore;
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                Sortiment newSortiment = new Sortiment();
                newSortiment.id = rs.getInt("id");
                newSortiment.name = rs.getString("name");
                newSortiment.store_id = rs.getInt("store_id");
                newSortiment.ean = rs.getString("ean");
                newSortiment.description = rs.getString("description");
                sortimentMap.add(newSortiment);
            }

            rs.close();
            stmt.close();
            conn.close();

        } catch (SQLException connError) {
            msg = "An exception was thrown for JDBC.";
            connError.printStackTrace();
        } catch (ClassNotFoundException e) {
            msg = "A class not found exception was thrown.";
            e.printStackTrace();
        } finally {

            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }

        return null;
    }

    @Override
    protected void onPostExecute(String msg) {
        sortimentAdapter = new SortimentAdapter(thisContext, sortimentMap);
        myListView.setAdapter(sortimentAdapter);

    }

}
}

和AndroidManifest的一部分:

    <activity android:name=".SortimentActivity"
        android:windowSoftInputMode="stateHidden">
    </activity>

关于如何更好地实现此搜索功能以使它搜索每个字符串的任何想法?

1 个答案:

答案 0 :(得分:0)

只要您没有在活动中使用 performFiltering 方法,到目前为止我就看不到任何问题(在您给定的示例中,您没有调用此方法,因此它是不必要的,可以将其删除) 。 performFiltering 方法的问题在于,您正在创建一个新适配器,但不要将其分配给您的列表视图,我想这是一种不好的做法。您应该一次初始化适配器,然后使用它来处理列表视图中的数据。

顺便说一句:请命名您的变量有意义。在适配器类中,有两个列表,称为列表。这很令人困惑。