Search code examples
androidlistviewapkmedia-player

showing list of songs in listview android studio


Here is the code which I want to show the list of mp3 files from device storage and when each of them is clicked its name will be toasted and in the near future play that music. I can see the file names in the specific folder but when I click on them There is no toast. what is the real problem?! Tnx in advance.

listView = (ListView)findViewById(R.id.lv1);
    List<String> list = new ArrayList<String😠);
    String path = Environment.getExternalStorageDirectory().getPath();
    path += "/Music";
    File file = new File(path);
    File  [] inn = file.listFiles();


    for(int i=0;i<inn.length;i++)
    {
        try {
            list.add(inn[i].getName().toString());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String😠this,android.R.layout.simple_list_item_1,list);
    listView.setAdapter(arrayAdapter);



}
    @Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    String name = parent.getItemAtPosition(position).toString();
    Toast.makeText(getApplicationContext(),name,Toast.LENGTH_LONG).show();

}

Solution

  • You need to set a Click Listener for yor list view. You can do that on the onCreate method. Similiar to:

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_activity_name);
        listView = (ListView)findViewById(R.id.lv1);
    
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Debug to make sure that you are getting the name in the variable
                String name = parent.getItemAtPosition(position).toString();
                Toast.makeText(getApplicationContext(),name,Toast.LENGTH_LONG).show();
            }
        }
    }