0

I searched the google and even the stackoverflow for the solution, but nothing worked and this is really making me insane now. :(

I want the only item to be highlighted is the one which I click on the listview. When I click on the item, it gets highlighted in red color. But once I scroll the list, I find multiple items are getting highlighted with red, and coming back to the item I find it turned to default color, that is non-highlighted mode. Getting crazy over this, working on this from the past 3 hours still unable to find a solution. :( Would really appreciate your advice. I know this is my third post in a day but I am quite new to android, so stumbling over this a few times. My code is stated below-

package com.example.mp3;


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;

import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;

import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;


public class MainActivity extends Activity implements View.OnClickListener, OnCompletionListener {

    ListView list;
    ArrayAdapter<String> listAdapter ;
    ArrayList<String> listTest;
     ArrayList<String> listSoundNames;
    ImageButton play,stop,back,next;
    String songpath,song,title;
    int index,current_position;
    File[] listFile;
    SharedPreferences sharedPref;
    MediaPlayer mp,mp2;
    ActionBar bar;
    private Boolean state=false;
    private static int save = -1;
    int count=0;
    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {



        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        song = sharedPref.getString("songname", "name");

        mp=new MediaPlayer();
        mp2 = new MediaPlayer();

        mp.setOnCompletionListener(this);


        list = (ListView)findViewById(R.id.list);
        //list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

        listTest = new ArrayList<String>( );
        listSoundNames=new ArrayList<String>();

        play = (ImageButton)findViewById(R.id.play);
        back = (ImageButton)findViewById(R.id.prev);
        next = (ImageButton)findViewById(R.id.next);

        //adding listeners
        play.setOnClickListener(this);
        back.setOnClickListener(this);
        next.setOnClickListener(this);


        //action bar controls
        bar = getActionBar();
        bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#DF0174")));

        Scanner("/sdcard/");///storage path


        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////*Adding listener to songs*//////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        if(listTest.size() != 0)
        {
            listAdapter = new ArrayAdapter<String> (MainActivity.this,R.layout.simplerow, listSoundNames);
            list.setAdapter(listAdapter);
            list.setOnItemClickListener(new OnItemClickListener() 
            {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
            {
                ///////////////////changing list item background on click///////////////////


                //view.setSelected(true);  ///////////////////PROBLEM/////////////

                for(int a = 0; a < parent.getChildCount(); a++)
                {
                    parent.getChildAt(a).setBackgroundColor(Color.BLACK);

                }

                view.setBackgroundColor(Color.RED);



                ////////////////////////////////////////////////////////////////////////////
                //accessing song path
                String selected = listTest.get(position);
                list.setItemChecked(position, true);//

                //accessing the song name
                String name = (String) ((TextView) view).getText();
                title = name;
                //bar.setTitle(title);
                //Log.e(TAG, name);

                Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();
                try{
                    mp.reset();
                    mp.setDataSource(listTest.get(position));//source
                    mp.prepare();
                    mp.start();
                    index = position;
                    play.setImageResource(R.drawable.pause);
                    }
                catch(Exception e){e.printStackTrace();}



            }


            });




            }

        }



        ////////////////////////////////////////////////////////////////////////////////////////////
        //////////////////////////////////*Songs added here to list*////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////

        private void Scanner(String path) {
            // TODO Auto-generated method stub
            {
                try 
                {
                        File fl = new File(path);
                        File[] listOfFiles = fl.listFiles();              

                        for (File listOfFile : listOfFiles)
                         {
                            String s = listOfFile.getName();

                            if(s.endsWith(".mp3"))
                            {

                            songpath = listOfFile.getPath();
                            listTest.add(songpath);//adding song names to list
                            //listTest.toString().replaceFirst(songpath, s);



                            // store file name in listSoundNames
                            int pos = s.lastIndexOf(".");
                            if (pos > 0)
                            {
                                song = s.substring(0, pos);
                            }
                            listSoundNames.add(song);

                            }


                            /////////////////////////////////
                            File f = new File(path+s+"/");
                            if (f.exists() && f.isDirectory()) {
                            Scanner(path+s+"/");
                            }
                            ////////////////////////////////


                        }



                }
            catch (Exception e) { }
            }

            }








    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        if (v.equals(play))
        {
            if(mp.isPlaying())
            {
                mp.pause();
                Toast.makeText(MainActivity.this, "paused", Toast.LENGTH_SHORT).show();
                //change in button image//
                play.setImageResource(R.drawable.play);

            }
            else
            {
                mp.start();
                Toast.makeText(MainActivity.this, "started", Toast.LENGTH_SHORT).show();
                //change in button image//
                play.setImageResource(R.drawable.pause);
                //
            }
        }


            if (v.equals(back))
            {
                mp.stop();
                mp.reset();
                //bar.setTitle(song);
                if(index!=0)
                {
                index = index -1;
                }
                else
                {
                    index = (list.getAdapter().getCount()-1)-1;

                }

                Uri uri = Uri.parse(listTest.get(index).toString());//getting the path of next song
                try {


                    mp.setDataSource(getApplicationContext(), uri);//setting new data source 


                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (SecurityException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_SHORT).show();///PROBLEM:MOVING HERE AFTER CLICKING NEXT BUTTON
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                try {
                    mp.prepare();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }        
                mp.start();//PROBLEM: NOT PLAYING
                Toast.makeText(MainActivity.this, ""+uri, Toast.LENGTH_SHORT).show();

            }


            if (v.equals(next))
            {

                mp.stop();
                mp.reset();
                index = index +1;


                Uri uri = Uri.parse(listTest.get(index).toString());//getting the path of next song

                try {


                    mp.setDataSource(getApplicationContext(), uri);//setting new data source 


                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (SecurityException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_SHORT).show();///PROBLEM:MOVING HERE AFTER CLICKING NEXT BUTTON
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                try {
                    mp.prepare();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }        
                mp.start();//PROBLEM: NOT PLAYING
                Toast.makeText(MainActivity.this, ""+uri, Toast.LENGTH_SHORT).show();


            }


    }


    @Override
    public void onCompletion(MediaPlayer arg0) {
        // TODO Auto-generated method stub
        play.setImageResource(R.drawable.play);
    }

    /*@Override
    protected void onStop() {
        super.onStop();
        mp.stop();
        Toast.makeText(getApplicationContext(), "stopped", Toast.LENGTH_LONG).show();

    }*/

}
  • 1
    Can you post your adapter class? – Raghavendra Oct 09 '15 at 13:13
  • updated the whole code –  Oct 09 '15 at 13:15
  • Try [this](http://stackoverflow.com/questions/3121153/baseadapter-causing-listview-to-go-out-of-order-when-scrolled) use a custom adapter – Raghavendra Oct 09 '15 at 13:21
  • But to use this, I need to change the whole code. I don't want that. Any other options available to overcome this? –  Oct 09 '15 at 13:24
  • This is caused by view recycling. It is impossible to achieve what your want without a custom adapter. Or maybe you need to add a onScrollListener, and each time a new item appears your make you sure it has the right background. Still a custom adapter will be best. And it is not much work to add it. –  Oct 09 '15 at 15:23

0 Answers0