0

Sorry for my bad english.I am new to android and i parsed json data into listview,now i want to put on him a search functionality,but i have a problem,when i entered a words in edittext,then in the listview my items are duplicated,and items has been increases,look my code and screen shots.Thanks in advance and any help will be much appreciated.

My Artist Activity:

    public class Artists extends Activity {

// Connection detector
        ConnectionDetector cd;

        // Alert dialog manager
        AlertDialogManager alert = new AlertDialogManager();

        // Progress Dialog
        private ProgressDialog pDialog;

        // Creating JSON Parser object
        JSONParser jsonParser = new JSONParser();
        // This is not using now if you want you can remove its all references :)
        ArrayList<HashMap<String, String>> albumsList;

        ArrayList<AdapterDTOArtist> mAdapterDTOs = null;
        private LazyAdapterArtist mLazyAdatper = null;

        private ArrayList<String> array_sort = new ArrayList<String>();
        int textlength = 0;

        // albums JSONArray
        JSONArray albums = null;

LinearLayout ll_artists_chart;
LinearLayout ll_artists_newrelease;
private EditText etSearch;

   private static String URL_ALBUMS = "http://triplevmusic.com/dev/webservice/index.php?op=fetch_artists.json";

// JSON Node names
private static final String TAG_CONTACTS = "data";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";

private ListView lv = null;
EditText et_artists_searchWord;
// contacts JSONArray
JSONArray contacts = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.artists);

    lv = (ListView) findViewById(R.id.artist_main_list_id);

    cd = new ConnectionDetector(getApplicationContext());

    // Check for internet connection
    if (!cd.isConnectingToInternet()) {
        // Internet Connection is not present
        alert.showAlertDialog(Artists.this,
                "Internet Connection Error",
                "Please connect to working Internet connection", false);
        // stop executing code by return
        return;
    }

    // Hashmap for ListView
            albumsList = new ArrayList<HashMap<String, String>>();
            mAdapterDTOs = new ArrayList<AdapterDTOArtist>();

            // Loading Albums JSON in Background Thread
            new LoadAlbums().execute();

            // get listview

            /**
             * Listview item click listener TrackListActivity will be lauched by
             * passing album id
             * */
            lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> arg0, View view, int arg2,
                        long arg3) {
                    // on selecting a single album

                }
            });


    ll_artists_chart = (LinearLayout) findViewById(R.id.ll_artists_chart);
    ll_artists_newrelease = (LinearLayout) findViewById(R.id.ll_artists_newrelease);
    et_artists_searchWord = (EditText) findViewById(R.id.et_artists_searchWord);

    et_artists_searchWord.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub
        //  ((Filterable) Artists.this.mAdapterDTOs).getFilter().filter(s);
            List<AdapterDTOArtist> list = filter(s.toString(),mAdapterDTOs, true);
            mAdapterDTOs.addAll(list);
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

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

        }
    });

    ll_artists_chart.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(getBaseContext(), ChartActivity.class);
            startActivity(intent);
        //  finish();
        }
    });

    ll_artists_newrelease.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(getBaseContext(), NewReleases.class);
            startActivity(intent);
            //finish();
        }
    });



}

/**
 * Background Async Task to Load all Albums by making http request
 * */
class LoadAlbums extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Artists.this);
        pDialog.setMessage("Listing Artists ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting Albums JSON
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        //List<NameValuePair> params = new ArrayList<NameValuePair>();
        ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();

        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        JSONObject json = jParser.getJSONFromUrl(URL_ALBUMS);

        // getting JSON string from URL
        //String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET", params);

        // Check your log cat for JSON reponse
        Log.i("Albums JSON: ", "> " + json);

        try {
            //albums = new JSONArray(json);
            albums = json.getJSONArray(TAG_CONTACTS);

            if (albums != null) {
                // looping through All albums
                for (int i = 0; i < albums.length(); i++) {
                    JSONObject c = albums.getJSONObject(i);

                    // Storing each json item values in variable
                    String id = c.getString(TAG_ID);
                    String name = c.getString(TAG_NAME);

                    /*String EateryThmbnailUrl = c
                            .getString(TAG_THMBNAIL_URL);*/
                    // ~\/Uploads\/EateryImages\/\/7\/41283f1f-8e6f-42d4-b3c1-01f990efb428.gif
                    /*EateryThmbnailUrl = HOST_URL
                            + EateryThmbnailUrl.replace("~", "");*/

                    AdapterDTOArtist adapterDTO = new AdapterDTOArtist();

                    adapterDTO.setmTag_Id(id);
                    adapterDTO.setmTag_Name(name);


                //  adapterDTO.setmImage_URL(EateryThmbnailUrl);

                    mAdapterDTOs.add(adapterDTO);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();
                    HashMap<String, Integer> map1 = new HashMap<String, Integer>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_ID, id);
                    map.put(TAG_NAME, name);


                    // adding HashList to ArrayList
                    albumsList.add(map);
                }
            } else {
                Log.d("Albums: ", "null");
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all albums
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                // updating listview
                mLazyAdatper = new LazyAdapterArtist(Artists.this,
                        mAdapterDTOs);
                lv.setAdapter(mLazyAdatper);

                // mLazyAdatper.setDataSet(mAdapterDTOs);

            }
        });

    }

}

public static List<AdapterDTOArtist> filter(String string,
        Iterable<AdapterDTOArtist> iterable, boolean byName) {
    if (iterable == null)
        return new LinkedList<AdapterDTOArtist>();
    else {
        List<AdapterDTOArtist> collected = new LinkedList<AdapterDTOArtist>();
        Iterator<AdapterDTOArtist> iterator = iterable.iterator();
        if (iterator == null)
            return collected;
        while (iterator.hasNext()) {
            AdapterDTOArtist item = iterator.next();
            collected.add(item);
        }
        return collected;
    }
}

}

My AdapterDTOArtist class :

   public class AdapterDTOArtist {

private String mTag_Id;
private String mTag_Name;

public String getmTag_Name() {
    return mTag_Name;
}

public void setmTag_Name(String mTag_Name) {
    this.mTag_Name = mTag_Name;
}

public String getmTag_Id() {
    return mTag_Id;
}

public void setmTag_Id(String mTag_Id) {
    this.mTag_Id = mTag_Id;
}

}

My LazyAdapterArtist class:

   public class LazyAdapterArtist extends BaseAdapter {

private Context mContext = null;
private ArrayList<AdapterDTOArtist> mAdapterDTOs = null;

public LazyAdapterArtist(Context context,
        ArrayList<AdapterDTOArtist> mAdapterDTOs2) {
    // TODO Auto-generated constructor stub
    this.mContext = context;
    this.mAdapterDTOs = mAdapterDTOs2;
}

public void setDataSet(ArrayList<AdapterDTOArtist> adapterDTOs) {
    this.mAdapterDTOs = adapterDTOs;
    notifyDataSetChanged();
}

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

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

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    View row = convertView;
    ViewHolder mHolder = new ViewHolder();

    if (row == null) {
        // Cell is inflating for first time
        row = LayoutInflater.from(mContext)
                .inflate(com.whizpool.triplevmusic.R.layout.row_artists,
                        null, false);

        mHolder.mNameTxt = (TextView) row
                .findViewById(com.whizpool.triplevmusic.R.id.tv_row_artists);

        row.setTag(mHolder);

    } else {
        // recycling of cells
        mHolder = (ViewHolder) row.getTag();
    }

    mHolder.mNameTxt.setText(mAdapterDTOs.get(position).getmTag_Name());

    return row;
}

static class ViewHolder {

    TextView mNameTxt = null;

}
}

when parsed json data into listview my app look like this:

enter image description here

when enter word in edittext field then my app look like this:

enter image description here

I just want,when i entered the word for example i enter "D" then in a listview only those words were display which have starting word is "D".Thanks Alot and again sorry for my english.

Farhan Shah
  • 2,344
  • 7
  • 28
  • 54

1 Answers1

1

The problem is that when you filter the data you add again to mAdapterDTOs list the results you need to clear the list before adding the results. To avoid losing your data you have to keep them in a separate list and when user times nothing show them.

Step 1: Use a field for keeping a backup of your data (just as mAdapterDTOs):

    ArrayList<AdapterDTOArtist> mAdapterDTOs = null;
    ArrayList<AdapterDTOArtist> mAdapterDTOsBackup= null;

Step 2: initialize that field:

        mAdapterDTOs = new ArrayList<AdapterDTOArtist>();
        mAdapterDTOsBackup = new ArrayList<AdapterDTOArtist>();

Step 3: Fill in all your data to the backup set just after parsing:

 /**
 * getting Albums JSON
 * */
protected String doInBackground(String... args) {

        // HERE all your code as it is!!!

    // Just before return add a set keeping the backup of your data...
    // initialize the set just as mAdapterDTOs
    mAdapterDTOsBackup.addAll(mAdapterDTOs);
    return null;
}

Step 4: When searching filter data from backup set and then add them on the mAdapterDTOs do not forget to clear it before.

et_artists_searchWord.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // TODO Auto-generated method stub
    //  ((Filterable) Artists.this.mAdapterDTOs).getFilter().filter(s);
        List<AdapterDTOArtist> list = filter(s.toString(),mAdapterDTOsBackup, true);
        mAdapterDTOs.clear(); // <--- clear the list before add
        mAdapterDTOs.addAll(list); // <--- here is the double add if you do not clear before
        mLazyAdatper.setDataSet(mAdapterDTOs);// update the adapter data (edit 2)
    }

Edit: split answer in steps in order to be more clear the process also added at least one of your line to show where to add each code snippet.

madlymad
  • 6,367
  • 6
  • 37
  • 68
  • dude it's not working..and mAdapterDTOsBackup.addAll(mAdapterDTOs); what is that mAdapterDTOsBackup ? it's again duplicate my items.. – Farhan Shah Jan 26 '14 at 19:30
  • yes bro i have readed again and try, it's not working,bro just tell me what is the mAdapterDTOsBackup?becoze i have no object of mAdapterDTOsBackup. – Farhan Shah Jan 26 '14 at 19:42
  • bro it's perfect now and so much clear,i have implemented successfully .but bro now when i entered a word in edittext then doesn't happen anything..any idea about that? – Farhan Shah Jan 26 '14 at 19:47
  • bro in the end of my Artist activity class,plz have a look my filter Method that it's Right or not. – Farhan Shah Jan 26 '14 at 19:51
  • not sure about it... but seems that there is missing the update of data inside the adapter `mLazyAdatper.setDataSet(mAdapterDTOs);` last line inside `onTextChanged` method (I cannot really understand why it is working before...) – madlymad Jan 26 '14 at 19:56
  • bro i am a bigenner level,now what i can do?have there is another way to resolve my issue.. – Farhan Shah Jan 26 '14 at 19:59
  • just add the line and test if it works see `(edit 2)` at my post – madlymad Jan 26 '14 at 20:02
  • i have add the line but nothing happen :( – Farhan Shah Jan 26 '14 at 20:05
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/46122/discussion-between-madlymad-and-farhan-shah) – madlymad Jan 26 '14 at 21:43