首页 > 解决方案 > 如何从 assets 文件夹中读取数据并输入 listView 程序

问题描述

我有这个 ListView,我用它来列出歌曲的标题,当点击歌曲的标题时,它会打开一个新的 Activity 以显示完整的歌曲歌词/措辞。我的应用程序项目有超过 1500 首歌曲标题和歌词可供编程。但我的问题是我不想在 ListViewAdapter.java 中硬编码我的歌曲歌词/措辞。我想将资产文件夹中的歌曲读入 ListViewAdapter,但不知道该怎么做。如果您帮助我解决示例问题,我将不胜感激。谢谢以下是我的代码。

ListViewAdapter.java

public class ListViewAdapter extends BaseAdapter {

    //Variables
    Context mContext;
    LayoutInflater inflater;
    List<Model> modellist;
    ArrayList<Model> arrayList;
    int[] soundfile;

    //Constructor
    public ListViewAdapter(Context context, List<Model> modellist) {
        mContext = context;
        this.modellist = modellist;
        inflater = LayoutInflater.from(mContext);
        this.arrayList = new ArrayList<Model>();
        this.arrayList.addAll(modellist);
    }

    public class ViewHolder {
        TextView mTitleTv, mDescTv;
        ImageView mIconTv, favorite;
    }

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

    @Override
    public Object getItem(int i) {
        return modellist.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int i, View view, ViewGroup parent) {
        final ViewHolder holder;
        if (view == null) {
            holder = new ViewHolder();
            view = inflater.inflate(R.layout.row, null);

            //locate the views in row.xml
            holder.mTitleTv = (TextView) view.findViewById(R.id.mainTitle);
            holder.mDescTv = (TextView) view.findViewById(R.id.mainDesc);
            holder.mIconTv = view.findViewById(R.id.mainIcon);
            //initialize the favorite image view
            holder.favorite = view.findViewById(R.id.favorite);

            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }
        //set the result into textview
        holder.mTitleTv.setText(modellist.get(i).getTitle());
        holder.mDescTv.setText(modellist.get(i).getDesc());
        //Set the result in imagview
        holder.mIconTv.setImageResource(modellist.get(i).getIcon());

        if (modellist.get(i).isFavorite())
            holder.favorite.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_heart));
        else
            holder.favorite.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_heart_o));

        //listview soundfile file for songs in position
        soundfile = new int[]{R.raw.song_1, R.raw.song_2, R.raw.song_3, R.raw.song_4, R.raw.song_5, R.raw.song_6, R.raw.song_7, R.raw.song_8,};

        //fovarite/unfavorite

        holder.favorite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (modellist.get(i).isFavorite())
                    holder.favorite.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_heart_o));
                else
                    holder.favorite.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_heart));

                modellist.get(i).setFavorite();
            }
        });

        //listview item clicks
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //code later
                if (modellist.get(i).getTitle().equals("Song 001 | This song lyrics 1")) {
                    //start NewActivity with title for actionbar and text for textview
                    Intent intent = new Intent(mContext, NewActivity.class);
                    intent.putExtra("actionBarTitle", "Song 001");
                    intent.putExtra("position", 1);
                    intent.putExtra("contentTv", "1. O THOU to whose all-searching sight\n" +
                            "The darkness shineth as the light,\n" +
                            "Search, prove my heart, it pants for thee;\n" +
                            "O burst these bonds and set it free!\n" +
                            "\n" +
                            "2. Wash out its stain, refine its dross,\n" +
                            "Nail my affections to the cross:\n" +
                            "Hallow each thought, let all within\n" +
                            "Be clean, as thou, my Lord, art clean.\n\n\n\n");
                    mContext.startActivity(intent);
                }
                if (modellist.get(i).getTitle().equals("Song 002 | This song lyrics 2")) {
                    //start NewActivity with title for actionbar and text for textview
                    Intent intent = new Intent(mContext, NewActivity.class);
                    intent.putExtra("position", 2);
                    intent.putExtra("actionBarTitle", "Song 002");
                    intent.putExtra("contentTv", "3 Saviour, where’er thy steps I see,\n" +
                            "Dauntless, untired, I’ll follow thee;\n" +
                            "O let thy hand support me still\n" +
                            "And lead me to thy holy hill!\n" +
                            "\n" +
                            "4 If rough and thorny be the way,\n" +
                            "My strength proportion to my day,\n" +
                            "Till toil and grief and pain shall cease,\n" +
                            "Where all is calm and joy and peace.\n\n\n\n");
                    mContext.startActivity(intent);
                }
                if (modellist.get(i).getTitle().equals("Song 003 | This song lyrics 3")) {
                    //start NewActivity with title for actionbar and text for textview
                    Intent intent = new Intent(mContext, NewActivity.class);
                    intent.putExtra("position", 3);
                    intent.putExtra("actionBarTitle", "Song 003");
                    intent.putExtra("contentTv", "1. O THOU to whose all-searching sight\n" +
                            "The darkness shineth as the light,\n" +
                            "Search, prove my heart, it pants for thee;\n" +
                            "O burst these bonds and set it free!\n" +
                            "\n" +
                            "2. Wash out its stain, refine its dross,\n" +
                            "Nail my affections to the cross:\n" +
                            "Hallow each thought, let all within\n" +
                            "Be clean, as thou, my Lord, art clean.\n\n\n\n");
                    mContext.startActivity(intent);
                }
                if (modellist.get(i).getTitle().equals("Song 004 | This song lyrics 4")) {
                    //start NewActivity with title for actionbar and text for textview
                    Intent intent = new Intent(mContext, NewActivity.class);
                    intent.putExtra("position", 4);
                    intent.putExtra("actionBarTitle", "Song 004");
                    intent.putExtra("contentTv", "This is song lyrics detail\n\n\n\n");
                    mContext.startActivity(intent);
                }
                if (modellist.get(i).getTitle().equals("Song 005 | This song lyrics 5")) {
                    //start NewActivity with title for actionbar and text for textview
                    Intent intent = new Intent(mContext, NewActivity.class);
                    intent.putExtra("position", 5);
                    intent.putExtra("actionBarTitle", "Song 005");
                    intent.putExtra("contentTv", "This is song lyrics detail\n\n\n\n");
                    mContext.startActivity(intent);
                }
                if (modellist.get(i).getTitle().equals("Song 006 | This song lyrics 6")) {
                    //start NewActivity with title for actionbar and text for textview
                    Intent intent = new Intent(mContext, NewActivity.class);
                    intent.putExtra("position", 6);
                    intent.putExtra("actionBarTitle", "Song 006");
                    intent.putExtra("contentTv", "This is song lyrics detail\n\n\n\n");
                    mContext.startActivity(intent);
                }
                if (modellist.get(i).getTitle().equals("Song 007 | This song lyrics 7")) {
                    //start NewActivity with title for actionbar and text for textview
                    Intent intent = new Intent(mContext, NewActivity.class);
                    intent.putExtra("position", 7);
                    intent.putExtra("actionBarTitle", "Song 007");
                    intent.putExtra("contentTv", "This is song lyrics detail\n\n\n\n");
                    mContext.startActivity(intent);
                }

            }
        });


        return view;
    }

    //filter
    public void filter(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());
        modellist.clear();
        if (charText.length() == 0) {
            modellist.addAll(arrayList);
        } else {
            for (Model model : arrayList) {
                if (model.getTitle().toLowerCase(Locale.getDefault()).contains(charText)) {
                    modellist.add(model);
                }
            }
        }
        notifyDataSetChanged();
    }


}

Model.java 类

public class Model {

    String title;
    String desc;

    //favorites songs key
    private static String FAVORITE_SONGS_KEY = "favorites";

    //song identifier
    int id;

    int icon;

    //constructor
    public Model(String title, String desc, int icon) {
        this.title = title;
        this.desc = desc;
        this.icon = icon;
    }

    //getters


    public String getTitle() {
        return this.title;
    }

    public String getDesc() {
        return this.desc;
    }

    public int getIcon() {
        return this.icon;
    }

    public void setFavorite() {
        if (isFavorite()) unset();
        else addTofavorite();
    }

    public boolean isFavorite() {
        String listIds = PreferenceUtils.getPreference(FAVORITE_SONGS_KEY, null);
        if (listIds == null) return false;
        List ids = new Gson().fromJson(listIds, List.class);
        if (ids == null) ids = new ArrayList();
        return ids.contains(String.valueOf(this.id));
    }

    private void unset() {
        String listIds = PreferenceUtils.getPreference(FAVORITE_SONGS_KEY, null);
        if (listIds == null) listIds = new String();
        List ids = new Gson().fromJson(listIds, List.class);
        if (ids == null) ids = new ArrayList();
        ids.add(String.valueOf(this.id));
        if (ids.contains(String.valueOf(this.id))) ids.remove(String.valueOf(this.id));
        PreferenceUtils.setPreference(FAVORITE_SONGS_KEY, new Gson().toJson(ids));
    }

    private void addTofavorite() {
        String listIds = PreferenceUtils.getPreference(FAVORITE_SONGS_KEY, null);
        if (listIds == null) listIds = new String();

        List ids = new Gson().fromJson(listIds, List.class);
        if (ids == null) ids = new ArrayList();
        ids.add(String.valueOf(this.id));
        PreferenceUtils.setPreference(FAVORITE_SONGS_KEY, new Gson().toJson(ids));
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
    private String TAG = "MainActivity ----- ; " ;
    // Store instance variables

    private int page;
    private ConsentForm form;

    ListView listView;
    ListViewAdapter adapter;
    String[] title;
    String[] description;
    int[] icon;
    ArrayList<Model> arrayList = new ArrayList<Model>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //initialize preferences
        PreferenceUtils.initialize(getApplicationContext());

        ActionBar actionBar = getSupportActionBar();
        actionBar.setTitle("Redeemed Songs");

        title = new String[]{"Song 001 | This song lyrics 1","Song 002 | This song lyrics 2","Song 003 | This song lyrics 3","Song 004 | This song lyrics 4","Song 005 | This song lyrics 5","Song 006 | This song lyrics 6","Song 007 | This song lyrics 7"};

        description = new String[]{"MORNING song", "MORNING song", "MORNING song", "MORNING song", "MORNING song", "MORNING song", "MORNING song",};

        icon = new int[]{ R.drawable.song, R.drawable.song, R.drawable.song, R.drawable.song,R.drawable.song,R.drawable.song, R.drawable.song,};

        listView = findViewById(R.id.list);

        for (int i =0; i<title.length; i++){
            Model model =new Model(title[i], description[i], icon[i]);
            //let's simply say, the song identifier is just the order of the song in the list
            model.id = i;
            //bind all strings in an array
            arrayList.add(model);
        }

        //pass result to listview class
        adapter = new ListViewAdapter(this, arrayList);

        //bind the adapter to the listview class
        listView.setAdapter(adapter);



    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);

        MenuItem myActionMenuItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView)myActionMenuItem.getActionView();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                if (TextUtils.isEmpty(s)){
                    adapter.filter("");
                    listView.clearTextFilter();
                }
                else {
                    adapter.filter(s);
                }
                return true;
            }
        });

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id==R.id.action_settings){
            Toast.makeText(this, "Settings Selected", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, Main2Activity.class));
            return true;
            //do your funtionality here

        }
        else if (id==R.id.action_howtouse){
                Toast.makeText(this, "How-To", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, FavoriteListActivity.class));
            return true;
                //do your funtionality here


        }else if (id==R.id.action_favorites){
                Toast.makeText(this, "Favorites Selected", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, FavoriteListActivity.class));
            return true;
                //do your funtionality here


        }
        else if (id==R.id.action_developers){
            Toast.makeText(this, "About", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, Main4Activity.class));
            return true;
            //do your funtionality here

        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        return false;
    }
}

标签: javascriptandroid

解决方案


推荐阅读