当我尝试搜索HashMap时没有任何反应

时间:2016-01-27 03:31:56

标签: java android listview hashmap

我正在尝试实现一项功能,允许我搜索我的所有歌曲,这些歌曲存储在名为songsList的HashMap中。我已成功实现songsList HashMap。我尝试使用用户点击搜索图标时输入的用户输入的字符串来过滤结果,但没有任何反应。

为什么没有过滤songsList HashMap的任何想法?

我尝试过区分大小写&不区分大小写的搜索。我试着搜索几首歌曲的完整而准确的歌曲标题。因此,我不认为我正在测试的搜索字符串是一个问题,而是我的代码中的某些内容。

playlist.xml layout

PlaylistActivity.java

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;

public class PlayListActivity extends ListActivity {

    private EditText editSearch;
    private ImageView searchIcon;
    private ListAdapter adapter;
    private ArrayList<HashMap<String, String>> songsListData;
    private boolean userEnteredSearchString = false;

    // Songs playlist_item
    public ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
    public ArrayList<HashMap<String, String>> filteredSongsList = new ArrayList<HashMap<String, String>>();

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

        songsListData = new ArrayList<HashMap<String, String>>();

        final SongsManager songsManager = new SongsManager();
        // get all songs from SD card
        this.songsList = songsManager.getPlayList();

        createListViewUsingSongs();


        // Set up the layout elements for this activity
        editSearch = (EditText) findViewById(R.id.search);
        searchIcon = (ImageView) findViewById(R.id.search_icon);

        // Capture Text in EditText when user clicks search icon
        searchIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                String text = editSearch.getText().toString().toLowerCase(Locale.getDefault());
                filteredSongsList = songsManager.filter(text);
                userEnteredSearchString = true;
                createListViewUsingSongs();
            }
        });

        // selecting single ListView item
        ListView listView = getListView();
        // listening to single playlist_item item click
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                                            @Override
                                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                                // getting list item index
                                                int songIndex = position;

                                                // Starting new intent
                                                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                                                // Sending songIndex to PlayerActivity
                                                intent.putExtra("songIndex", songIndex);
                                                setResult(100, intent);
                                                // Closing PlayListView
                                                finish();
                                            }
                                        }

        );
    }

    private void createListViewUsingSongs() {

        if (userEnteredSearchString) {
            // looping through playlist
            for (int i = 0; i < filteredSongsList.size(); i++){
                // creating new HashMap
                HashMap<String, String> song = songsList.get(i);
                // adding HashList to ArrayList
                songsListData.add(song);
            }
        } else {
            // looping through playlist
            for (int i = 0; i < songsList.size(); i++){
                // creating new HashMap
                HashMap<String, String> song = songsList.get(i);
                // adding HashList to ArrayList
                songsListData.add(song);
            }
        }

        // Adding menuItems to ListView
        adapter = new SimpleAdapter(this, songsListData,
                R.layout.playlist_item, new String[]{"songTitle"}, new int[]{
                R.id.songTitle});

        setListAdapter(adapter);
    }
}

SongsManager.java

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;

public class SongsManager {

    private HashMap<String, String> song;
    private String songString;

    // SDCard Path
    final String MEDIA_PATH = "/storage/extSdCard/music";
    private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
    private ArrayList<HashMap<String, String>> filteredSongsList = new ArrayList<HashMap<String, String>>();


    // Constructors
    public SongsManager(String song) {
        this.songString = songString;
    }

    public SongsManager() {
    }

    /**
     * Function to read all mp3 files from sdcard
     * and store the details in ArrayList
     */
    public ArrayList<HashMap<String, String>> getPlayList() {
        File home = new File(MEDIA_PATH);

        if (home.listFiles(new FileExtensionFilter()).length > 0) {
            for (File file : home.listFiles(new FileExtensionFilter())) {
                HashMap<String, String> song = new HashMap<String, String>();
                song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
                song.put("songPath", file.getPath());

                // Adding each song to SongList
                songsList.add(song);
            }
        }
        // return songs playlist_item array
        return songsList;
    }

    public String getSong() {
        return this.songString;
    }

    /**
     * Class to filter files which are having .mp3 extension
     */
    class FileExtensionFilter implements FilenameFilter {
        public boolean accept(File dir, String name) {
            return (name.endsWith(".mp3") || name.endsWith(".MP3") || name.endsWith(".wma"));
        }
    }

    // Filter Class
    public ArrayList<HashMap<String, String>> filter(String searchString) {
        searchString = searchString.toLowerCase(Locale.getDefault());

        songsList.clear();
        songsList = getPlayList();

        //searchString is empty, so show all songs in results
        if (searchString.length() == 0) {

            if (filteredSongsList != null){
                filteredSongsList.clear();
            }
            filteredSongsList = songsList;
        }

        //only return songs that match the search string
        else {

            if (filteredSongsList != null){
                filteredSongsList.clear();
            }

            for (HashMap<String, String> song : songsList) {
                if (song != null) {
                    String songTitle = song.get("songTitle");
                    if (songTitle.toLowerCase().contains(searchString)) {
                        filteredSongsList.add(song);
                    }
                }
            }
        }

        return filteredSongsList;
    }
}

playList.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="match_parent"
        android:layout_height="wrap_content">

    <EditText
        android:id="@+id/search"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="4"
        android:hint="Type song &amp; click search icon"
        android:inputType="text"
        android:maxLength="40">
        <requestFocus />
    </EditText>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/search_icon"
        android:layout_weight="1"
        android:src="@drawable/ic_search"/>

    </LinearLayout>

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:divider="#242424"
        android:dividerHeight="1dp"
        android:listSelector="@drawable/list_selector" />

</LinearLayout>

Github上提供完整的代码下载:https://github.com/jogold9/Simple_Music_Player

1 个答案:

答案 0 :(得分:0)

决议:搜索一直都很好,但我忽略了http://www.example.com/?name=amca&PID=143&PageID=abc

因此,在刷新适配器时,会显示完整的数据集而不是过滤的数据集。

不要害怕每个人都使用调试器。如果我遵循这个简单的建议,我本可以节省时间。

songsListData.clear();