【问题标题】:Android parsed json data and add a search functionalityAndroid解析json数据并添加搜索功能
【发布时间】:2014-01-26 18:46:59
【问题描述】:

对不起,我的英语不好。我是 android 新手,我将 json 数据解析为 listview,现在我想给他一个搜索功能,但是我遇到了一个问题,当我在 edittext 中输入一个单词时,然后在listview 我的项目重复,项目已经增加,看看我的代码和屏幕截图。在此先感谢,任何帮助将不胜感激。

我的艺术家活动:

    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;
    }
}

}

我的 AdapterDTOArtist 类:

   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;
}

}

我的 LazyAdapterArtist 类:

   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;

}
}

当将 json 数据解析到 listview 中时,我的应用如下所示:

当在 edittext 字段中输入单词时,我的应用程序如下所示:

我只想,当我输入单词时,例如我输入“D”然后在列表视图中只显示那些以“D”开头的单词。非常感谢,再次为我的英语感到抱歉。

【问题讨论】:

    标签: android


    【解决方案1】:

    问题在于,当您过滤再次添加到mAdapterDTOs 列表的数据时,您需要在添加结果之前清除列表。为了避免丢失您的数据,您必须将它们保存在单独的列表中,并且当用户时间没有显示它们时。

    第 1 步:使用字段备份您的数据(就像 mAdapterDTOs):

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

    第 2 步:初始化该字段:

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

    第3步:解析后将所有数据填写到备份集中:

     /**
     * 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;
    }
    

    第4步:从备份集中搜索过滤数据然后将它们添加到mAdapterDTOs之前不要忘记清除它。

    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)
        }
    

    编辑: 分步拆分答案,以便更清晰,该过程还添加了至少一行,以显示在何处添加每个代码 sn-p。

    【讨论】:

    • 老兄它不工作..和 mAdapterDTOsBackup.addAll(mAdapterDTOs);那是什么 mAdapterDTOsBackup ?它再次重复了我的项目..
    • 是的,兄弟,我再次阅读并尝试,它不起作用,兄弟告诉我 mAdapterDTOsBackup 是什么?因为我没有 mAdapterDTOsBackup 的对象。
    • 兄弟,现在很完美,非常清楚,我已经成功实施了。但是现在当我在edittext中输入一个单词时,什么都没有发生。。对此有任何想法吗?
    • 兄弟在我的 Artist 活动课结束时,请看看我的过滤方法,它是否正确。
    • 不确定...但似乎缺少适配器内的数据更新mLazyAdatper.setDataSet(mAdapterDTOs); onTextChanged 方法内的最后一行(我无法真正理解为什么它之前工作.. .)
    猜你喜欢
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-15
    • 1970-01-01
    • 2015-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多