2017-01-23 4 views
1

## hier ist mein Code. Ich habe gefilterte Listenansicht mit SQLite-Datenbank und JSON erstellt. Aber wenn ich nach Daten für z. B. Namen suche, ist Shreya Patil, dann zeigt es mir nur Ergebnis für Name Shreya nicht für ihren Nachnamen. Wenn ich Pastille tippe ist Ergebnis nichts. Bitte um Hilfe .. ##Gefilterte Listenansicht zeigt keine korrekten Daten

Hier ist der Ausschnitt aus der Aktivitätsklasse:

public class DirectoryActivity extends BaseActivity { 

    private SQLiteDbAdapter dbHelper; 
    private SimpleCursorAdapter dataAdapter; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_directory_home_profile); 

     dbHelper = new SQLiteDbAdapter(this); 

     dbHelper.open(); 
     //Clean all data 
     dbHelper.deleteAllData(); 
     displayListView(); 
     getPolicianInfo(); 


    } 

    private void displayListView() { 

     Cursor cursor = dbHelper.fetchAllData(); 
     Log.e("Getting all data", "data"); 

     // The desired columns to be bound 
     String[] columns = new String[] { 
       SQLiteDbAdapter.USER_ID, 
       SQLiteDbAdapter.POLITICIAN_FIRST_NAME, 
       SQLiteDbAdapter.POLITICIAN_DESIGNATION, 
       SQLiteDbAdapter.POLITICIAN_CONTACT, 
       SQLiteDbAdapter.POLITICIAN_IMAGE_URL, 
       SQLiteDbAdapter.POLITICIAN_CITY, 
       SQLiteDbAdapter.POLITICIAN_HOUSE, 
     }; 

     // the XML defined views which the data will be bound to 
     int[] to = new int[] { 
       R.id.directory_item_name_tv_name, 
       R.id.directory_item_name_tv_last_name, 
       /* R.id.directory_item_name_tv_last_Test,*/ 
       R.id.directory_item_name_tv_designation, 
       R.id.directory_item_name_tv_contact, 
       R.id.directory_item_iv_picture, 

     }; 

     // create the adapter using the cursor pointing to the desired data 
     //as well as the layout information 
     dataAdapter = new SimpleCursorAdapter(
       this, R.layout.list_item_directory_lv, cursor, columns,to, 0); 

     ListView listView = (ListView) findViewById(R.id.directory_search_lv); 
     listView.setTextFilterEnabled(true); 

     // Assign adapter to ListView 
     listView.setAdapter(dataAdapter); 

     dataAdapter.setFilterQueryProvider(new FilterQueryProvider() { 
      public Cursor runQuery(CharSequence constraint) { 
       return dbHelper.fetchPoliticansByName(constraint.toString()); 
      } 
     }); 


     EditText myFilter = (EditText) findViewById(R.id.myFilter); 
     myFilter.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) { 
       //dataAdapter.getFilter().filter(s.toString()); 
       DirectoryActivity.this.dataAdapter.getFilter().filter(s); 

      } 
     }); 

    } 




    private void getPolicianInfo() { 

     if (Util.isNetworkAvailable(this)) { 
      try { 
       API apis = RetrofitClient.getApiClient(Util.DOMAIN_NAME); 


       Callback<JsonElement> responseListner = new Callback<JsonElement>() { 
        @Override 
        public void success(JsonElement responseSuccess, Response response) { 
         Log.e("responseSuccess", responseSuccess.toString()); 

         if (responseSuccess != null) { 

          Log.e("responseSuccess success", responseSuccess.toString()); 
          Log.e("response in success", response.toString()); 


          try { 
           JSONObject object = new JSONObject(responseSuccess.toString()); 


           { 

            JSONArray jsonMainNode = object.getJSONArray("posts"); 
            int lengthJsonArr = jsonMainNode.length(); 

            for (int i = 0; i < lengthJsonArr; i++) { 
             /****** Get Object for each JSON node.***********/ 
             JSONObject jsonChildNode = jsonMainNode.getJSONObject(i); 



             String user_id = jsonChildNode.getString("id"); 
             String politician_first_name = jsonChildNode.getString("name"); 
             String politician_designation = jsonChildNode.getString("designation"); 
             String politician_contact = jsonChildNode.getString("contact"); 
             String politician_image_url = jsonChildNode.getString("img_url"); 
             String politician_city = jsonChildNode.getString("city"); 
             String politician_house = jsonChildNode.getString("house"); 

             if (politician_designation.isEmpty()) 
             { 
              politician_designation="NA"; 
              Log.e("Tag2",politician_designation); 
             } 

             if (politician_contact.isEmpty()) 
             { 
              politician_contact="NA"; 
              Log.e("Tag3",politician_contact); 
             } 

             dbHelper.createPoliticianInfoData(user_id, politician_first_name,politician_designation, 
               politician_contact, politician_image_url, politician_city, politician_house); 

            } 
           } 
          } catch (Exception e) { 
           e.printStackTrace(); 
          } 
         } else { 
          Toast.makeText(getApplicationContext(), "Network Connection Failed", Toast.LENGTH_SHORT).show(); 
          Log.e("response in success", response.toString()); 
         } 
        } 

        @Override 
        public void failure(RetrofitError error) { 
         Log.e("tag", error.toString()); 
         Toast.makeText(getApplicationContext(), "Network Connection Failed from failure method", Toast.LENGTH_SHORT).show(); 
        } 
       }; 
       apis.getPolicianInfo(responseListner); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } else { 
      Toast.makeText(getApplicationContext(), "Please Check Your Internet Connection", Toast.LENGTH_SHORT).show(); 
     } 


    } 
} 

// Hier ist Datenbank-Klasse

public class SQLiteDbAdapter { 

    public static final String KEY_ROWID = "_id"; 
    public static final String USER_ID = "id"; 
    public static final String POLITICIAN_FIRST_NAME = "name"; 
    public static final String POLITICIAN_DESIGNATION = "designation"; 
    public static String POLITICIAN_CONTACT = "contact"; 
    public static String POLITICIAN_IMAGE_URL = "img_url"; 
    public static String POLITICIAN_CITY = "city"; 
    public static String POLITICIAN_HOUSE = "house"; 
    private static final String TAG = "SQLiteDbAdapter"; 
    private DatabaseHelper mDbHelper; 
    private SQLiteDatabase mDb; 

    private static final String DATABASE_NAME = "World"; 
    private static final String SQLITE_TABLE = "Country"; 
    private static final int DATABASE_VERSION = 1; 

    private final Context mCtx; 

    private static final String DATABASE_CREATE = 
      "CREATE TABLE if not exists " + SQLITE_TABLE + " (" + 
        KEY_ROWID + " integer PRIMARY KEY autoincrement," + 
        USER_ID + "," + 
        POLITICIAN_FIRST_NAME + "," + 
        POLITICIAN_DESIGNATION + "," + 
        POLITICIAN_CONTACT + "," + 
        POLITICIAN_IMAGE_URL + "," + 
        POLITICIAN_CITY + "," + 
        POLITICIAN_HOUSE + "," + 
        " UNIQUE (" + KEY_ROWID +"));"; 

    private static class DatabaseHelper extends SQLiteOpenHelper { 

     DatabaseHelper(Context context) { 
      super(context, DATABASE_NAME, null, DATABASE_VERSION); 
     } 


     @Override 
     public void onCreate(SQLiteDatabase db) { 
      Log.w(TAG, DATABASE_CREATE); 
      db.execSQL(DATABASE_CREATE); 
     } 

     @Override 
     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
      Log.w(TAG, "Upgrading database from version " + oldVersion + " to " 
        + newVersion + ", which will destroy all old data"); 
      db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE); 
      onCreate(db); 
     } 
    } 

    public SQLiteDbAdapter(Context ctx) { 
     this.mCtx = ctx; 
    } 

    public SQLiteDbAdapter open() throws SQLException { 
     mDbHelper = new DatabaseHelper(mCtx); 
     mDb = mDbHelper.getWritableDatabase(); 
     return this; 
    } 

    public void close() { 
     if (mDbHelper != null) { 
      mDbHelper.close(); 
     } 
    } 

    public long createPoliticianInfoData(String user_id, String politician_first_name, 
           String politician_designation, String politician_contact, 
           String politician_image_url, String politician_city, String politician_house) { 


     ContentValues initialValues = new ContentValues(); 
     initialValues.put(USER_ID, user_id); 
     initialValues.put(POLITICIAN_FIRST_NAME, politician_first_name); 
     initialValues.put(POLITICIAN_DESIGNATION, politician_designation); 
     initialValues.put(POLITICIAN_CONTACT, politician_contact); 
     initialValues.put(POLITICIAN_IMAGE_URL, politician_image_url); 
     initialValues.put(POLITICIAN_CITY, politician_city); 
     initialValues.put(POLITICIAN_HOUSE, politician_house); 
     int cc=(int) mDb.insert(SQLITE_TABLE, null, initialValues); 
     //Log.e("insert ", ""+cc); 

     return cc; 
    } 

    public boolean deleteAllData() { 

     int doneDelete = 0; 
     doneDelete = mDb.delete(SQLITE_TABLE, null , null); 
     Log.w(TAG, Integer.toString(doneDelete)); 
     return doneDelete > 0; 

    } 


    public Cursor fetchPoliticansByName(String inputText) throws SQLException { 
     Log.w(TAG, inputText); 
     Cursor mCursor = null; 
     if (inputText == null || inputText.length() == 0) { 
      mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID, 
          USER_ID, POLITICIAN_FIRST_NAME,POLITICIAN_DESIGNATION, 
        POLITICIAN_CONTACT,POLITICIAN_IMAGE_URL,POLITICIAN_CITY,POLITICIAN_HOUSE}, 
        null, null, null, null, null); 
     } 
     else { 
      mCursor = mDb.query(true, SQLITE_TABLE, new String[] {KEY_ROWID, 
          USER_ID, POLITICIAN_FIRST_NAME,POLITICIAN_DESIGNATION, 
        POLITICIAN_CONTACT,POLITICIAN_IMAGE_URL,POLITICIAN_CITY,POLITICIAN_HOUSE}, 
        POLITICIAN_FIRST_NAME + " like '" + inputText + "%' OR " 
          /* + POLITICIAN_LAST_NAME + " like '"+inputText+"%' OR "*/ 
          + POLITICIAN_DESIGNATION + " like '"+inputText+"%' OR " 
          + POLITICIAN_CITY + " like '"+inputText+"%' OR " 
          + POLITICIAN_HOUSE + " like '"+inputText+"%'", 
        null, null, null, null, null); 

     } 

     if (mCursor != null) { 
      mCursor.moveToFirst(); 
     } 
     return mCursor; 

    } 



    public Cursor fetchAllData() { 

     Cursor mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID, 
         USER_ID, POLITICIAN_FIRST_NAME,POLITICIAN_DESIGNATION, 
       POLITICIAN_CONTACT,POLITICIAN_IMAGE_URL,POLITICIAN_CITY,POLITICIAN_HOUSE}, 
       null, null, null, null, null); 
     Log.e("Cursor vallue display", "data"+mCursor); 
     if (mCursor != null) { 
      mCursor.moveToFirst(); 
      Log.e("Cursor vallue display", "datafgdfxg" +mCursor.getCount()); 
     } 
     return mCursor; 
    } 

} 
+0

reduzieren Sie Ihr Beispiel, sehen Sie auch http://stackoverflow.com/help/mcve – hering

Antwort

0

Ja. Fügen Sie einen EditText über Ihrer ListView in der AML-Layoutdatei hinzu. Und in Ihrer Aktivität/Fragmente ..

lv = (ListView) findViewById(R.id.list_view); 
    inputSearch = (EditText) findViewById(R.id.inputSearch); 

// Adding items to listview 
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products); 
lv.setAdapter(adapter);  
inputSearch.addTextChangedListener(new TextWatcher() { 

@Override 
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) { 
    // When user changed the Text 
    MainActivity.this.adapter.getFilter().filter(cs); 
} 

@Override 
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } 

@Override 
public void afterTextChanged(Editable arg0) {} 
}); 

Der Grund hier ist eine OnTextChangeListener zu Ihrem Text bearbeiten und innerhalb seiner Callback-Methode hinzuzufügen, Filter anwenden, um Ihre Listenansicht des Adapters.

Um Filter zu Ihrer benutzerdefinierten erhalten BaseAdapter Sie "Filterbare Schnittstelle implementieren müssen ll.

class CustomAdapter extends BaseAdapter implements Filterable { 

    public View getView(){ 
    ... 
    } 
    public Integer getCount() 
    { 
    ... 
    } 

    @Override 
    public Filter getFilter() { 

     Filter filter = new Filter() { 

      @SuppressWarnings("unchecked") 
      @Override 
      protected void publishResults(CharSequence constraint, FilterResults results) { 

       arrayListNames = (List<String>) results.values; 
       notifyDataSetChanged(); 
      } 

      @Override 
      protected FilterResults performFiltering(CharSequence constraint) { 

       FilterResults results = new FilterResults(); 
       ArrayList<String> FilteredArrayNames = new ArrayList<String>(); 

       // perform your search here using the searchConstraint String. 

       constraint = constraint.toString().toLowerCase(); 
       for (int i = 0; i < mDatabaseOfNames.size(); i++) { 
        String dataNames = mDatabaseOfNames.get(i); 
        if (dataNames.toLowerCase().startsWith(constraint.toString())) { 
         FilteredArrayNames.add(dataNames); 
        } 
       } 

       results.count = FilteredArrayNames.size(); 
       results.values = FilteredArrayNames; 
       Log.e("VALUES", results.values.toString()); 

       return results; 
      } 
     }; 

     return filter; 
    } 
} 

Innen perfromFiltering() Sie Ist-Vergleich der Suchabfrage auf Werte in der Datenbank tun müssen. Es wird passieren sein Ergebnis zu publishResults() Methode

Verwandte Themen