Как хранить массивы в строках. xml или активах и использовать в ListViewAdapter - PullRequest
0 голосов
/ 15 февраля 2020

Я хочу создать более 1500 LyricsFullDetail в ListViewAdapter, но моя проблема в том, что я не хочу жестко кодировать полную информацию Lyrics в ListViewAdapter. java. Я хочу хранить все тексты песен и читать их из Strings. xml или папки с ресурсами. Файлы musi c сохраняются в папке raw. Я буду очень признателен, если вы поможете мне с примером fix.thanks Ниже приведены мои коды.

Это коды itemClick, которые я повторил 1500 раз, что дало мне «слишком большую ошибку кода»

Вот почему я изо всех сил пытаюсь сохранить его где-нибудь, как папка активов, и прочитать в ListViewAdapter

 //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.");
                    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.");
                    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.");
                    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");
                    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");
                    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");
                    mContext.startActivity(intent);
                }

            }
        });


        return view;
    }

Это 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();
    }


}

Это 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;
    }
}

1 Ответ

0 голосов
/ 15 февраля 2020

Вы можете создать списки и массивы строк в строках. xml затем их можно использовать в адаптере, вы можете иметь параллельный массив для сопоставления названия песни с текстами песен

Но вам, вероятно, лучше использовать базу данных SQLite для этого типа вещей либо напрямую, либо используя Android Комнаты.

Учебный материал для комнат (который является слоем поверх SQLite) https://developer.android.com/training/data-storage/room/

или более прямой https://developer.android.com/training/data-storage/sqlite.html

List<String> myLyricList = Arrays.asList(getResources().getStringArray(R.array.array_lyrics));

List<String> myTitleList = Arrays.asList(getResources().getStringArray(R.array.array_titles));

строк. xml

<string-array name="array_lyrics">
        <item>This song lyrics 1</item>
        <item>This song lyrics 2</item>
</string-array>

<string-array name="array_titles">
        <item>Song 001</item>
        <item>Song 002</item>
</string-array>

...