gpt4 book ai didi

java - 用于过滤自定义 ListView 元素的搜索过滤器

转载 作者:行者123 更新时间:2023-12-01 23:19:51 25 4
gpt4 key购买 nike

我做了什么::

  • 我能够通过 webservice 中的 JSON 实现数据显示并将其填充到 listview
  • 我已经实现了 search-filter 来根据文本搜索元素查看

我遇到的问题::我将发布一系列快照来解释我的问题

<小时/>
  1. Snapshot1::我有 listview 显示列表中的一系列元素

enter image description here

  • Snapshot2::现在,当我输入 carl 时,我的姓名会被过滤,并且仅显示匹配的结果
  • enter image description here

  • Snapshot3::现在删除搜索栏中的所有内容 ..... 我应该得到如 snapshot1 中所示的显示,但没有发生
  • enter image description here

    总体::发生的情况是,一旦过滤,我就无法再使用它进行另一次尝试...我必须再次重新编译整个项目

    <小时/>

    ListOfContacts.java

    public class ListOfContacts extends Activity {
    // Declare Variables
    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView listview;
    ListViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    static String NAME = "rank";
    static String FLAG = "flag";
    EditText mEditText;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from listview_main.xml
    setContentView(R.layout.listview_main);


    // Locate the listview in listview_main.xml
    listview = (ListView) findViewById(R.id.listview);
    mEditText = (EditText) findViewById(R.id.inputSearch);
    // Execute DownloadJSON AsyncTask
    new DownloadJSON().execute();


    }

    // DownloadJSON AsyncTask
    class DownloadJSON extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
    super.onPreExecute();
    // Create a progressdialog
    mProgressDialog = new ProgressDialog(ListOfContacts.this);
    // Set progressdialog title
    //mProgressDialog.setTitle("Fetching the information");
    // Set progressdialog message
    mProgressDialog.setMessage("Loading...");
    mProgressDialog.setIndeterminate(false);
    // Show progressdialog
    mProgressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
    // Create an array
    arraylist = new ArrayList<HashMap<String, String>>();
    // Retrieve JSON Objects from the given URL address
    jsonobject = JSONfunctions.getJSONfromURL("http://URL");

    try {
    // Locate the array name in JSON
    jsonarray = jsonobject.getJSONArray("restaurants");

    for (int i = 0; i < jsonarray.length(); i++) {
    HashMap<String, String> map = new HashMap<String, String>();
    jsonobject = jsonarray.getJSONObject(i);
    // Retrive JSON Objects
    map.put(ListOfContacts.NAME, jsonobject.getString("Person_Name"));
    map.put(ListOfContacts.FLAG, "http://54.218.73.244:7004/"+jsonobject.getString("Image_Name"));



    // Set the JSON Objects into the array
    arraylist.add(map);
    }
    } catch (JSONException e) {
    Log.e("Error", e.getMessage());
    e.printStackTrace();
    }
    return null;
    }

    @Override
    protected void onPostExecute(Void args) {
    // Pass the results into ListViewAdapter.java
    adapter = new ListViewAdapter(ListOfContacts.this, arraylist);
    // Set the adapter to the ListView
    listview.setAdapter(adapter);
    // Close the progressdialog

    mEditText = (EditText) findViewById(R.id.inputSearch);
    mEditText.addTextChangedListener(new TextWatcher()
    {

    public void afterTextChanged(Editable s)
    {

    }

    public void beforeTextChanged(CharSequence s, int start,int count, int after)
    {

    }

    public void onTextChanged(CharSequence s, int start,int before, int count)
    {

    ArrayList<HashMap<String, String>> arrayTemplist= new ArrayList<HashMap<String,String>>();
    String searchString =mEditText.getText().toString();
    for (int i = 0; i < arraylist.size(); i++)
    {
    String currentString =arraylist.get(i).get(ListOfContacts.NAME);
    if (searchString.equalsIgnoreCase(currentString))
    {
    arrayTemplist.add(arraylist.get(i));
    }
    }
    adapter = new ListViewAdapter(ListOfContacts.this, arrayTemplist);
    listview.setAdapter(adapter);
    }
    });
    mProgressDialog.dismiss();
    }
    }
    }

    DataAcceptActivity.java

    public class DataAcceptActivity extends Activity {

    Button submit;
    Button display;
    ProgressDialog pDialog;
    InputStream is;
    EditText name;
    ImageView imageView;
    EditText search;

    private static final int SELECT_PICTURE = 1;
    private String selectedImagePath;

    int[] image_array={R.drawable.index,R.drawable.image1,R.drawable.image5,R.drawable.image6,R.drawable.image7,R.drawable.image8,R.drawable.image9,R.drawable.image10};

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

    submit = (Button) findViewById(R.id.SUBMIT_BUTTON_ID);
    name = (EditText) findViewById(R.id.editText1);
    imageView = (ImageView) findViewById(R.id.imageView1);
    display=(Button) findViewById(R.id.DISPLAY_BUTTON_ID);

    search=(EditText) findViewById(R.id.inputSearch);

    display.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {
    // TODO Auto-generated method stub
    Intent searchIntent=new Intent(DataAcceptActivity.this,ListOfContacts.class);
    startActivity(searchIntent);

    }
    });


    submit.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub
    new MainTest().execute();


    }
    });


    imageView.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {
    // TODO Auto-generated method stub

    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
    }
    });




    }


    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
    if (requestCode == SELECT_PICTURE) {
    Uri selectedImageUri = data.getData();
    selectedImagePath = getPath(selectedImageUri);
    System.out.println("Image Path : " + selectedImagePath);
    imageView.setImageURI(selectedImageUri);
    }
    }
    }

    public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
    }



    /**
    * Method to post the image to the server.
    * U will have to change the url which will accept the image data.
    * @throws IOException
    */
    public void postImageData() {


    try
    {

    Bitmap bitmapOrg = ((BitmapDrawable)imageView.getDrawable()).getBitmap();

    HttpClient httpClient = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost("http://URL");
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    try{
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bitmapOrg.compress(CompressFormat.JPEG, 75, bos);
    byte[] data = bos.toByteArray();
    ByteArrayBody bab = new ByteArrayBody(data, "image.jpg");
    reqEntity.addPart("key", bab);
    reqEntity.addPart("key1", new StringBody(name.getText().toString()));
    }
    catch(Exception e){
    //Log.v("Exception in Image", ""+e);
    reqEntity.addPart("picture", new StringBody(""));
    }
    postRequest.setEntity(reqEntity);
    HttpResponse response = httpClient.execute(postRequest);
    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
    String sResponse;
    StringBuilder s = new StringBuilder();
    while ((sResponse = reader.readLine()) != null) {
    s = s.append(sResponse);
    }
    }catch(Exception e){
    e.getStackTrace();
    }


    }
    public class MainTest extends AsyncTask<String, Integer, String> {

    @Override
    protected void onPreExecute() {
    pDialog = new ProgressDialog(DataAcceptActivity.this);
    pDialog.setMessage("Loading..");
    pDialog.setIndeterminate(true);
    pDialog.setCancelable(false);
    pDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {

    postImageData();

    return null;
    }

    @Override
    protected void onPostExecute(String result) {
    // TODO Auto-generated method stub

    super.onPostExecute(result);
    // data=jobj.toString();
    pDialog.dismiss();
    Toast.makeText(getApplicationContext(), "File Uploaded", Toast.LENGTH_SHORT).show();
    }

    }


    class ImageAdapter extends BaseAdapter{

    Context cxt;
    public ImageAdapter(DataAcceptActivity dataAcceptActivity) {
    // TODO Auto-generated constructor stub
    this.cxt=dataAcceptActivity;
    }

    @Override
    public int getCount() {
    // TODO Auto-generated method stub
    return image_array.length;
    }

    @Override
    public Object getItem(int position) {
    // TODO Auto-generated method stub
    return position;
    }

    @Override
    public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub

    ImageView imageView ;
    if(convertView==null){
    imageView=new ImageView(cxt);
    imageView.setLayoutParams(new GridView.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    imageView.setPadding(15, 15, 15, 15);
    }else{
    imageView=(ImageView) convertView;
    }

    imageView.setImageResource(image_array[position]);
    return imageView;
    }

    }

    }

    MainActivity.java

    public class MainActivity extends Activity {
    // Declare Variables
    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView listview;
    ListViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;

    static String NAME = "rank";
    static String FLAG = "flag";

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from listview_main.xml
    setContentView(R.layout.listview_main);


    // Locate the listview in listview_main.xml
    listview = (ListView) findViewById(R.id.listview);

    // Execute DownloadJSON AsyncTask
    new DownloadJSON().execute();
    }

    // DownloadJSON AsyncTask
    private class DownloadJSON extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
    super.onPreExecute();
    // Create a progressdialog
    mProgressDialog = new ProgressDialog(MainActivity.this);
    // Set progressdialog title
    //mProgressDialog.setTitle("Fetching the information");
    // Set progressdialog message
    mProgressDialog.setMessage("Loading...");
    mProgressDialog.setIndeterminate(false);
    // Show progressdialog
    mProgressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
    // Create an array
    arraylist = new ArrayList<HashMap<String, String>>();
    // Retrieve JSON Objects from the given URL address
    jsonobject = JSONfunctions.getJSONfromURL("http://URL");

    try {
    // Locate the array name in JSON
    jsonarray = jsonobject.getJSONArray("restaurants");

    for (int i = 0; i < jsonarray.length(); i++) {
    HashMap<String, String> map = new HashMap<String, String>();
    jsonobject = jsonarray.getJSONObject(i);
    // Retrive JSON Objects
    map.put(MainActivity.NAME, jsonobject.getString("restaurantNAME"));;
    map.put(MainActivity.FLAG, "http://url"+jsonobject.getString("restaurantIMAGE"));


    // Set the JSON Objects into the array
    arraylist.add(map);
    }
    } catch (JSONException e) {
    Log.e("Error", e.getMessage());
    e.printStackTrace();
    }
    return null;
    }

    @Override
    protected void onPostExecute(Void args) {
    // Pass the results into ListViewAdapter.java
    adapter = new ListViewAdapter(MainActivity.this, arraylist);
    // Set the adapter to the ListView
    listview.setAdapter(adapter);
    // Close the progressdialog
    mProgressDialog.dismiss();
    }
    }
    }
    <小时/>

    任何解决此问题的想法谢谢

    最佳答案

    只需输入搜索字符串长度的条件即可。

    mEditText.addTextChangedListener(new TextWatcher()
    {

    public void afterTextChanged(Editable s)
    {

    }

    public void beforeTextChanged(CharSequence s, int start,int count, int after)
    {

    }

    public void onTextChanged(CharSequence s, int start,int before, int count)
    {

    ArrayList<HashMap<String, String>> arrayTemplist= new ArrayList<HashMap<String,String>>();
    String searchString =mEditText.getText().toString().trim();
    if(searchString.length()>0)
    {
    for (int i = 0; i < arraylist.size(); i++)
    {
    String currentString =arraylist.get(i).get(ListOfContacts.NAME);
    if (searchString.equalsIgnoreCase(currentString))
    {
    arrayTemplist.add(arraylist.get(i));
    }
    }
    adapter = new ListViewAdapter(ListOfContacts.this, arrayTemplist);
    listview.setAdapter(adapter);
    }
    else
    {
    adapter = new ListViewAdapter(ListOfContacts.this, arraylist);
    listview.setAdapter(adapter);
    }
    }
    });

    关于java - 用于过滤自定义 ListView 元素的搜索过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20756137/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com