Laire
Laire

Reputation: 1330

Android ListView with dynamic search result shows wrong results

It's very difficult to explain my problem in English, but I will try.

I have a ListView which should show live the results from a search. When I type "d" in the searchfield it should me show all results that begin with a "d".

The problem is, that it doesn't show me the right results. It shows me the first entry from the original list and not the target entry, but it shows the right numbers entries.

When I have this entries in my ArrayList:

Anti Beta Delta Dirty Echo Eleven Earth

and type "d" in the searchfield, it shows me 2 Hits (which is right), but it shows me Anti and Beta. When I type "e", it shows me 3 Hits (which is right) but it shows me Anti, Beta and Delta.

This is the MainActivity:

package de.resper.pzcrettungsdienstkassel;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {
  ArrayList<HashMap<String, Object>> haupt;
  ArrayList<HashMap<String, Object>> code;
  ArrayList<HashMap<String, Object>> codeResult;
  ListView codeListView;
  LayoutInflater inflater;

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

        codeListView = (ListView) findViewById(R.id.listsearch);

        inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        final EditText searchBox=(EditText) findViewById(R.id.searchBox);

        sql_helper db = new sql_helper(getApplicationContext());

        code = new ArrayList<HashMap<String,Object>>();
      code = db.getAllCode();

      codeResult = new ArrayList<HashMap<String,Object>>();

      final CustomAdapterCode adapter_code = new CustomAdapterCode(this, R.layout.activity_main, codeResult);
      codeListView.setAdapter(adapter_code);

      searchBox.addTextChangedListener(new TextWatcher() {
        public void onTextChanged(CharSequence s, int start, int before, int count) {
          //get the text in the EditText
          String searchString=searchBox.getText().toString();
          int textLength=searchString.length();

          codeResult.clear();

          for(int i=0;i<code.size();i++){
            String name=code.get(i).get("name").toString();
            if(textLength<=name.length()){
              if(searchString.equalsIgnoreCase(name.substring(0,textLength))){
                codeResult.add(code.get(i));
                    Log.d("Suchfeld", String.valueOf(i));
                    Log.d("Suchfeld", code.get(i).get("name").toString());
              }
            }
          }

          adapter_code.notifyDataSetChanged();
        }
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
        public void afterTextChanged(Editable s) {}
      });
    }

  private class CustomAdapterCode extends ArrayAdapter<HashMap<String, Object>> {
    public CustomAdapterCode(Context context, int textViewResourceId, ArrayList<HashMap<String, Object>> Strings) {
      super(context, textViewResourceId, Strings);
    }
    private class ViewHolder{
      TextView code_id, code_layout, name_layout, prio1, prio2, prio3;
    }

    ViewHolder viewHolder;

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      if(convertView==null){
        convertView=inflater.inflate(R.layout.code_list_item, null);
        viewHolder=new ViewHolder();

        viewHolder.code_id=(TextView) convertView.findViewById(R.id.code_id);
        viewHolder.code_layout=(TextView) convertView.findViewById(R.id.code_layout);
        viewHolder.name_layout=(TextView) convertView.findViewById(R.id.name_layout);
        viewHolder.prio1=(TextView) convertView.findViewById(R.id.prio1);
        viewHolder.prio2=(TextView) convertView.findViewById(R.id.prio2);
        viewHolder.prio3=(TextView) convertView.findViewById(R.id.prio3);

        convertView.setTag(viewHolder);

      } else {
        viewHolder=(ViewHolder) convertView.getTag();
      }

      viewHolder.code_id.setText(code.get(position).get("_id").toString());
      viewHolder.code_layout.setText(code.get(position).get("code").toString());
      viewHolder.name_layout.setText(code.get(position).get("name").toString());
      viewHolder.prio1.setText(code.get(position).get("prio1").toString());
      viewHolder.prio2.setText(code.get(position).get("prio2").toString());
      viewHolder.prio3.setText(code.get(position).get("prio3").toString());

      return convertView;
    }
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
  }
}

This is my sql_helper:

package de.resper.pzcrettungsdienstkassel;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;


public class sql_helper extends SQLiteOpenHelper {
  private static final String DATABASE_FILE_NAME="pzc";
  private static final int SCHEMA_VERSION=1;

  public sql_helper(Context context) {
    super(context, DATABASE_FILE_NAME, null, SCHEMA_VERSION);
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE pzc_haupt (_id INTEGER PRIMARY KEY, name TEXT, unter INTEGER);");
    db.execSQL("CREATE TABLE pzc_unter (_id INTEGER PRIMARY KEY, name TEXT, haupt INTEGER);");
    db.execSQL("CREATE TABLE pzc_code (_id INTEGER PRIMARY KEY,code INTEGER, name TEXT, unter INTEGER, haupt INTEGER, prio1 INTEGER, prio2 INTEGER, prio3 INTEGER);");
    db.execSQL("INSERT INTO pzc_code (_id,code,name,unter,haupt,prio1,prio2,prio3) VALUES ('1','124','Anti','0','1','1','0','0');");
    db.execSQL("INSERT INTO pzc_code (_id,code,name,unter,haupt,prio1,prio2,prio3) VALUES ('2','130','Beta','0','1','1','0','0');");
    db.execSQL("INSERT INTO pzc_code (_id,code,name,unter,haupt,prio1,prio2,prio3) VALUES ('3','201','Delta','1','0','1','1','0');");
    db.execSQL("INSERT INTO pzc_code (_id,code,name,unter,haupt,prio1,prio2,prio3) VALUES ('4','202','Dirty','1','0','1','1','0');");
    db.execSQL("INSERT INTO pzc_code (_id,code,name,unter,haupt,prio1,prio2,prio3) VALUES ('5','203','Echo','2','0','1','1','0');");
    db.execSQL("INSERT INTO pzc_code (_id,code,name,unter,haupt,prio1,prio2,prio3) VALUES ('6','204','Eleven','2','0','1','1','0');");
    db.execSQL("INSERT INTO pzc_code (_id,code,name,unter,haupt,prio1,prio2,prio3) VALUES ('7','205','Earth','3','0','1','1','0');");
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  }

  public ArrayList<HashMap<String,Object>> getAllHaupt() {
    ArrayList<HashMap<String,Object>> hauptList = new ArrayList<HashMap<String,Object>>();
    String selectQuery = "SELECT  * FROM pzc_haupt";
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    HashMap<String , Object> haupt;
    if (cursor.moveToFirst()) {
      do {
        haupt = new HashMap<String, Object>();
        haupt.put("_id", Integer.parseInt(cursor.getString(0)));
        haupt.put("name", cursor.getString(1));
        hauptList.add(haupt);
      } while (cursor.moveToNext());
    }
    return hauptList;
  }

  public ArrayList<HashMap<String,Object>> getAllCode() {
    ArrayList<HashMap<String,Object>> codeList = new ArrayList<HashMap<String,Object>>();
    String selectQuery = "SELECT  * FROM pzc_code ORDER BY _id ASC";
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    HashMap<String , Object> code;
    if (cursor.moveToFirst()) {
      do {
        code = new HashMap<String, Object>();
        code.put("_id", Integer.parseInt(cursor.getString(0)));
        code.put("code", Integer.parseInt(cursor.getString(1)));
        code.put("name", cursor.getString(2));
        if (Integer.parseInt(cursor.getString(5)) == 1) {
          code.put("prio1", "\u25CF");
        } else {
          code.put("prio1", "");
        }
        if (Integer.parseInt(cursor.getString(6)) == 1) {
          code.put("prio2", "\u25CF");
        }else{
          code.put("prio2", "");
        }
        if (Integer.parseInt(cursor.getString(7)) == 1) {
          code.put("prio3", "\u25CF");
        } else {
          code.put("prio3", "");
        }
        codeList.add(code);
      } while (cursor.moveToNext());
    }
    return codeList;
  }
}

The activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
  <LinearLayout
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical" >
       <EditText
           android:id="@+id/searchBox"
          android:layout_height="wrap_content"
          android:layout_width="fill_parent"
          android:layout_margin="10dp"
          android:hint="@string/suche">
    </EditText>
      <ListView
          android:id="@+id/listsearch"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content" >
      </ListView>
      <View
          android:layout_width="fill_parent"
          android:layout_height="2dp"
          android:background="#000000"
          android:layout_marginBottom="10dp" />
  </LinearLayout>
</LinearLayout>

The code_list_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="10dp" >

    <TextView android:id="@+id/code_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone" />
     <TextView
        android:id="@+id/prio1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="22sp"
        android:textColor="#FF0000" />
     <TextView
        android:id="@+id/prio2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="22sp"
        android:textColor="#FFFF00" />
     <TextView
        android:id="@+id/prio3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="22sp"
        android:textColor="#40FF00" />
     <TextView
        android:id="@+id/code_layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
      android:textSize="14sp"
      android:textColor="#000000" />
    <TextView
        android:id="@+id/name_layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="14sp"
        android:textColor="#000000"
        android:layout_marginLeft="5dp" />
</LinearLayout>

I don't use ListActivity beacause I want to build in one more ListView in this activity.

Upvotes: 1

Views: 1188

Answers (1)

Devrim
Devrim

Reputation: 15533

You are not using codeResult at getView method. You are using original code array. Change code with codeResult like below. Your problem will be solved.

        viewHolder.code_id.setText(codeResult.get(position).get("_id").toString());
        viewHolder.code_layout.setText(codeResult.get(position).get("code").toString());
        viewHolder.name_layout.setText(codeResult.get(position).get("name").toString());
        viewHolder.prio1.setText(codeResult.get(position).get("prio1").toString());
        viewHolder.prio2.setText(codeResult.get(position).get("prio2").toString());
        viewHolder.prio3.setText(codeResult.get(position).get("prio3").toString());

Upvotes: 3

Related Questions