0

I'm doing the listview search of a recipe app. I was going to use getfilter at first but failed and can't fix. Is there any other method to implement this feature. here is my Search.java:

public class Search extends Base{
ArrayList<Recipe> recipes;
ListView recipeListView;
RecipesAdapter adapter;
Context context;
int clickedrecipe;
EditText searchField;

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

    context = getApplicationContext();

    recipes = new ArrayList<Recipe>();
    adapter = new RecipesAdapter();
    recipeListView = (ListView) findViewById(R.id.RecipeListView);
    searchField = (EditText) findViewById(R.id.SearchField);

    new GetRecipe(context).execute();

    recipeListView.setOnItemClickListener(new OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Recipe recipe = recipes.get(position);

            Intent i = new Intent(context, Show.class);
            i.putExtra("name", recipe.name);
            i.putExtra("style_of_cooking", recipe.style_of_cooking);
            i.putExtra("ingredient", recipe.ingredient);
            i.putExtra("step", recipe.step);
            i.putExtra("image", recipe.image);
            i.putExtra("cost", recipe.cost);
            startActivity(i);
        }
    });


searchField.addTextChangedListener(new TextWatcher() {

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

        for(int i=0; i<recipes.size(); i++) {
            if (!recipes.get(i).name.contains(cs)) {
                recipes.remove(i);
                adapter.notifyDataSetChanged();
            }
        } 

    }


    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
            int arg3) {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterTextChanged(Editable arg0) {
        // TODO Auto-generated method stub                          
    }
});

}


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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menuLogout:
            logout();
            break;
    }
    return true;
}   

public class GetRecipe extends AsyncTask<String, Void, String> {

    private Context context;

    public GetRecipe(Context c){
        this.context = c;
    }

    protected void onPreExecute(){
        super.onPreExecute();
    }

    protected String doInBackground(String... params) {
        String result = "";
        try{
            result = BaseRest.serverGet("api/v1/recipes");
        } catch(Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    protected void onPostExecute(String result){
        super.onPostExecute(result);

        JSONArray jsonResult;

        try{
            jsonResult = new JSONArray(result);
            if(jsonResult != null){
                for(int i = 0; i < jsonResult.length(); i++){
                    JSONObject element = jsonResult.getJSONObject(i);{
                        if(element != null){
                            addEventToList(element);
                        }
                    }
                }
                recipeListView.setAdapter(adapter);
            }
        } catch (JSONException e){
            e.printStackTrace();
        }
    }

    private void addEventToList(JSONObject element) {
        try {
            Recipe recipe = new Recipe(
                    element.getString("id"),
                    element.getString("name"),
                    element.getString("user_id"),
                    element.getString("style_of_cooking"),
                    element.getString("ingredient"),
                    element.getString("step"),
                    element.getJSONObject("image").getString("url"),
                    element.getString("cost"),
                    element.getString("created_at"));
            recipes.add(recipe);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}


 class RecipesAdapter extends ArrayAdapter<Recipe> {
        public RecipesAdapter() {
            super(context, R.layout.row_recipe, recipes);
        }

        public View getView(final int position, View convertView, ViewGroup parent) {
            View itemView = convertView;
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            if(itemView == null) {
                itemView = inflater.inflate(R.layout.row_recipe, parent, false);
            }

            final Recipe currentEvent = recipes.get(position);

            TextView recipeName = (TextView) itemView.findViewById(R.id.recipename);
            recipeName.setText(currentEvent.name);

            TextView time = (TextView) itemView.findViewById(R.id.timeContent);
            time.setText(currentEvent.created_at);


            return itemView;
        }

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

}

I use a for loop in onTextChanged method and it can remove the items that are not relevant when you input something in the edittext, but when you delete your input, the listview can't back to the initial state. how should I write the method? the following is my Recipe.java:

public class Recipe {

public String id;
public String name;
public String user_id;
public String style_of_cooking;
public String ingredient;
public String step; 
public String image; 
public String cost;
public String created_at;


/** Returned from server */
public Recipe(String id, String name, String user_id, String style_of_cooking, String ingredient, String step, String image, String cost, String created_at) {
    this.id = id;
    this.name = name;
    this.user_id = user_id;
    this.style_of_cooking = style_of_cooking;
    this.ingredient = ingredient;
    this.step = step;
    this.image = "http://192.168.0.17:3000" + image;
    this.cost = cost;
    this.created_at = created_at;
}

public void setId(String id) {
    this.id = id;
}

public String getName() {
    return name;
}
}
Stu
  • 3
  • 3
  • See this [Tutorial](http://www.androidhive.info/2012/09/android-adding-search-functionality-to-listview/) to show filtered data from search text. – Harin Apr 08 '15 at 09:56
  • I have seen this tutorial but it uses an arrayadapter which is built-in. I used recipesadapter which is a subclass of arrayadapter and I don't know how to write getfilter() in this class. – Stu Apr 08 '15 at 14:05
  • see [Answer](http://stackoverflow.com/questions/24769257/custom-listview-adapter-with-filter-android) given here. – Harin Apr 09 '15 at 05:26
  • it is similar to the filter I used earlier. see here:http://stackoverflow.com/questions/29542153/use-filter-to-do-a-listview-search – Stu Apr 09 '15 at 15:05

0 Answers0