2013-10-24 3 views
1

Очень сложно объяснить мою проблему на английском языке, но я попробую.Android ListView с динамическим результатом поиска показывает неправильные результаты

У меня есть ListView, который должен показывать результаты поиска. Когда я набираю «d» в поле поиска, мне следует показать все результаты, начинающиеся с «d».

Проблема в том, что она не показывает мне правильные результаты. Он показывает мне первую запись из исходного списка, а не целевую запись, но показывает правильные номера.

Когда у меня есть эти записи в моей ArrayList:

Анти Бета Дельта Грязный Echo Одиннадцать Earth

и типа "D" в searchfield, он показывает мне 2 Hits (который правильно), но он показывает мне Anti и Beta. Когда я набираю «e», он показывает мне 3 Hits (это правильно), но он показывает мне Anti, Beta и Delta.

Это 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; 
    } 
} 

Это мой 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; 
    } 
} 

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> 

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> 

Я не использую ListActivity beacause Я хочу создать еще один ListView в этом действии.

+0

Простой тест. Добавьте notifyDataSetChanged в свой onResume(). (объединить его с if (adapter! = null) {adapter.notifyDataSetChanged();}, после того, как вы выполнили поиск, приостановите и возобновите свою деятельность (перейдя в HOME и вернувшись, например). Обновлен ли адаптер? –

ответ

3

Вы не используете codeResult по методу getView. Вы используете оригинальный массив code. Поменять code на codeResult, как показано ниже. Ваша проблема будет решена.

 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()); 
+0

^:) –

+0

Большое спасибо, я редактирую это вчера для теста и забыл. Иногда я слепой ... – Laire

Смежные вопросы