Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/228.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 列表视图未发送已单击的确切列表项_Java_Android_Listview - Fatal编程技术网

Java 列表视图未发送已单击的确切列表项

Java 列表视图未发送已单击的确切列表项,java,android,listview,Java,Android,Listview,我不确定,但我的列表不起作用,应该是,当点击onItemClick时,我应该将其转移到另一个类并打开该活动,当我尝试启动Tactivity时,它正在打开,但没有点击要播放的确切项目。顺便说一句,这是一个媒体播放器。我真的需要帮助 正在播放的活动 private ImageButton btnPlay; private ImageButton btnForward; private ImageButton btnBackward; private ImageButton btnNext; priv

我不确定,但我的列表不起作用,应该是,当点击onItemClick时,我应该将其转移到另一个类并打开该活动,当我尝试启动Tactivity时,它正在打开,但没有点击要播放的确切项目。顺便说一句,这是一个媒体播放器。我真的需要帮助

正在播放的活动

private ImageButton btnPlay;
private ImageButton btnForward;
private ImageButton btnBackward;
private ImageButton btnNext;
private ImageButton btnPrevious;
private ImageButton btnRepeat;
private ImageButton btnShuffle;
private SeekBar songProgressBar;
private TextView songTitleLabel;
private TextView songCurrentDurationLabel;
private TextView songTotalDurationLabel;
// Media Player
private  MediaPlayer mp;
// Handler to update UI timer, progress bar etc,.
private Handler mHandler = new Handler();;
private SongsManager songManager;
private Utilities utils;
private int seekForwardTime = 5000; // 5000 milliseconds
private int seekBackwardTime = 5000; // 5000 milliseconds
private int currentSongIndex = 0;
private boolean isShuffle = false;
private boolean isRepeat = false;
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

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

    // All player buttons
    btnPlay = (ImageButton) findViewById(R.id.btnPlay);
    btnForward = (ImageButton) findViewById(R.id.btnForward);
    btnBackward = (ImageButton) findViewById(R.id.btnBackward);
    btnNext = (ImageButton) findViewById(R.id.btnNext);
    btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
    btnRepeat = (ImageButton) findViewById(R.id.btnRepeat);
    btnShuffle = (ImageButton) findViewById(R.id.btnShuffle);
    songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
    songTitleLabel = (TextView) findViewById(R.id.songTitle);
    songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
    songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);

    // Mediaplayer
    mp = new MediaPlayer();
    songManager = new SongsManager();
    utils = new Utilities();

    // Listeners
    songProgressBar.setOnSeekBarChangeListener(this); // Important
    mp.setOnCompletionListener(this); // Important

    // Getting all songs list
    songsList = songManager.getPlayList();

    // By default play first song
    playSong(0);

    /**
     * Play button click event
     * plays a song and changes button to pause image
     * pauses a song and changes button to play image
     * */
    btnPlay.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // check for already playing
            if(mp.isPlaying()){
                if(mp!=null){
                    mp.pause();
                    // Changing button image to play button
                    btnPlay.setImageResource(R.drawable.btn_play);
                }
            }else{
                // Resume song
                if(mp!=null){
                    mp.start();
                    // Changing button image to pause button
                    btnPlay.setImageResource(R.drawable.btn_pause);
                }
            }

        }
    });

    /**
     * Forward button click event
     * Forwards song specified seconds
     * */
    btnForward.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // get current song position
            int currentPosition = mp.getCurrentPosition();
            // check if seekForward time is lesser than song duration
            if(currentPosition + seekForwardTime <= mp.getDuration()){
                // forward song
                mp.seekTo(currentPosition + seekForwardTime);
            }else{
                // forward to end position
                mp.seekTo(mp.getDuration());
            }
        }
    });

    /**
     * Backward button click event
     * Backward song to specified seconds
     * */
    btnBackward.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // get current song position
            int currentPosition = mp.getCurrentPosition();
            // check if seekBackward time is greater than 0 sec
            if(currentPosition - seekBackwardTime >= 0){
                // forward song
                mp.seekTo(currentPosition - seekBackwardTime);
            }else{
                // backward to starting position
                mp.seekTo(0);
            }

        }
    });

    /**
     * Next button click event
     * Plays next song by taking currentSongIndex + 1
     * */
    btnNext.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // check if next song is there or not
            if(currentSongIndex < (songsList.size() - 1)){
                playSong(currentSongIndex + 1);
                currentSongIndex = currentSongIndex + 1;
            }else{
                // play first song
                playSong(0);
                currentSongIndex = 0;
            }

        }
    });

    /**
     * Back button click event
     * Plays previous song by currentSongIndex - 1
     * */
    btnPrevious.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if(currentSongIndex > 0){
                playSong(currentSongIndex - 1);
                currentSongIndex = currentSongIndex - 1;
            }else{
                // play last song
                playSong(songsList.size() - 1);
                currentSongIndex = songsList.size() - 1;
            }

        }
    });

    /**
     * Button Click event for Repeat button
     * Enables repeat flag to true
     * */
    btnRepeat.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if(isRepeat){
                isRepeat = false;
                Toast.makeText(getApplicationContext(), "Repeat is OFF", Toast.LENGTH_SHORT).show();
                btnRepeat.setImageResource(R.drawable.repeat);
            }else{
                // make repeat to true
                isRepeat = true;
                Toast.makeText(getApplicationContext(), "Repeat is ON", Toast.LENGTH_SHORT).show();
                // make shuffle to false
                isShuffle = false;
                btnRepeat.setImageResource(R.drawable.repeat1);
                btnShuffle.setImageResource(R.drawable.shuffle);
            }
        }
    });

    /**
     * Button Click event for Shuffle button
     * Enables shuffle flag to true
     * */
    btnShuffle.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if(isShuffle){
                isShuffle = false;
                Toast.makeText(getApplicationContext(), "Shuffle is OFF", Toast.LENGTH_SHORT).show();
                btnShuffle.setImageResource(R.drawable.shuffle);
            }else{
                // make repeat to true
                isShuffle= true;
                Toast.makeText(getApplicationContext(), "Shuffle is ON", Toast.LENGTH_SHORT).show();
                // make shuffle to false
                isRepeat = false;
                btnShuffle.setImageResource(R.drawable.shuffle1);
                btnRepeat.setImageResource(R.drawable.repeat);
            }
        }
    });



}

/**
 * Receiving song index from playlist view
 * and play the song
 * */
@Override
protected void onActivityResult(int requestCode,
                                 int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode == 100){
         currentSongIndex = data.getExtras().getInt("songIndex");
         // play selected song
         playSong(currentSongIndex);

    }

}

/**
 * Function to play a song
 * @param songIndex - index of song
 * */
public void  playSong(int songIndex){
    // Play song
    try {
        mp.reset();
        mp.setDataSource(songsList.get(songIndex).get("songPath"));
        mp.prepare();
        mp.start();
        // Displaying Song title
        String songTitle = songsList.get(songIndex).get("songTitle");
        songTitleLabel.setText(songTitle);

        // Changing Button Image to pause image
        btnPlay.setImageResource(R.drawable.btn_pause);

        // set Progress bar values
        songProgressBar.setProgress(0);
        songProgressBar.setMax(100);

        // Updating progress bar
        updateProgressBar();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

/**
 * Update timer on seekbar
 * */
public void updateProgressBar() {
    mHandler.postDelayed(mUpdateTimeTask, 100);
}   

/**
 * Background Runnable thread
 * */
private Runnable mUpdateTimeTask = new Runnable() {
       public void run() {
           long totalDuration = mp.getDuration();
           long currentDuration = mp.getCurrentPosition();

           // Displaying Total Duration time
           songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
           // Displaying time completed playing
           songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));

           // Updating progress bar
           int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
           //Log.d("Progress", ""+progress);
           songProgressBar.setProgress(progress);

           // Running this thread after 100 milliseconds
           mHandler.postDelayed(this, 100);
       }
    };

/**
 *
 * */
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {

}

/**
 * When user starts moving the progress handler
 * */
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
    // remove message Handler from updating progress bar
    mHandler.removeCallbacks(mUpdateTimeTask);
}

/**
 * When user stops moving the progress hanlder
 * */
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
    mHandler.removeCallbacks(mUpdateTimeTask);
    int totalDuration = mp.getDuration();
    int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);

    // forward or backward to certain seconds
    mp.seekTo(currentPosition);

    // update timer progress again
    updateProgressBar();
}

/**
 * On Song Playing completed
 * if repeat is ON play same song again
 * if shuffle is ON play random song
 * */
@Override
public void onCompletion(MediaPlayer arg0) {

    // check for repeat is ON or OFF
    if(isRepeat){
        // repeat is on play same song again
        playSong(currentSongIndex);
    } else if(isShuffle){
        // shuffle is on - play a random song
        Random rand = new Random();
        currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
        playSong(currentSongIndex);
    } else{
        // no repeat or shuffle ON - play next song
        if(currentSongIndex < (songsList.size() - 1)){
            playSong(currentSongIndex + 1);
            currentSongIndex = currentSongIndex + 1;
        }else{
            // play first song
            playSong(0);
            currentSongIndex = 0;
        }
    }
}

@Override
 public void onDestroy(){
 super.onDestroy();
    mp.release();
 }
TabSongsActivity列表视图

public ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();


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

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

        SongsManager plm = new SongsManager();
        // get all songs from sdcard
        this.songsList = plm.getPlayList();

        // 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
        ListAdapter adapter = new SimpleAdapter(this, songsListData,
            R.layout.playlist_item, new String[] { "songTitle" }, new int[] {
                    R.id.songTitle });

        setListAdapter(adapter);

        // selecting single ListView item
        ListView lv = getListView();
        // listening to single listitem click
        lv.setOnItemClickListener(new OnItemClickListener() {

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

                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                    NowPlayingActivity.class);
                // Sending songIndex to PlayerActivity
                in.putExtra("songIndex", songIndex);
                setResult(100, in);
                 startActivityForResult(i, 100);

            }
        });

    }
歌曲管理者

public class SongsManager {
    // SDCard Path
    final String MEDIA_PATH = Environment.getExternalStorageDirectory().getPath() + "/";
    private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
    private String mp3Pattern = ".mp3";
    // Constructor
    public SongsManager(){

    }

    /**
     * Function to read all mp3 files from sdcard
     * and store the details in ArrayList
     * */
    public ArrayList<HashMap<String, String>> getPlayList() {
        System.out.println(MEDIA_PATH);
        if (MEDIA_PATH != null) {
            File home = new File(MEDIA_PATH);
            File[] listFiles = home.listFiles();
            if (listFiles != null && listFiles.length > 0) {
                for (File file : listFiles) {
                    System.out.println(file.getAbsolutePath());
                    if (file.isDirectory()) {
                        scanDirectory(file);
                    } else {
                        addSongToList(file);
                    }
                }
            }
        }
        // return songs list array
        return songsList;
    }

    /**
     * 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"));
        }
    }
    private void scanDirectory(File directory) {
        if (directory != null) {
            File[] listFiles = directory.listFiles();
            if (listFiles != null && listFiles.length > 0) {
                for (File file : listFiles) {
                    if (file.isDirectory()) {
                        scanDirectory(file);
                    } else {
                        addSongToList(file);
                    }

                }
            }
        }
    }

    private void addSongToList(File song) {
        if (song.getName().endsWith(mp3Pattern)) {
            HashMap<String, String> songMap = new HashMap<String, String>();
            songMap.put("songTitle",
                    song.getName().substring(0, (song.getName().length() - 4)));
            songMap.put("songPath", song.getPath());

            // Adding each song to SongList
            songsList.add(songMap);
        }
    }
}
你需要使用

int index = data.getIntExtra("songIndex", 0);
而不是

int index = data.getExtras().getInt("songIndex");
getExtras方法使用putExtras返回一个bundle集

编辑:

在TabSongsActivity中,您拥有

   Intent in = new Intent(getApplicationContext(),
        NowPlayingActivity.class);
    // Sending songIndex to PlayerActivity
    in.putExtra("songIndex", songIndex);
    setResult(100, in);                  /// REMOVE THIS!!
    startActivityForResult(i, 100);
在NowPlayingActivity中,删除onActivityResult,并将其放在其他地方,可能是onCreate

 Intent in = getIntent();
 int songIndex = in.getIntExtra("songIndex",0)

首先,不要自己扫描sd卡。sd卡上可能有数十万个文件,将它们全部存储,然后向下筛选列表可能会很慢和/或内存不足。请改用媒体内容提供商。它已经为您扫描了sd卡,并且可以给您一个列表,其中只包含音乐文件,包括艺术家/专辑/标题和其他元数据

在代码中,您保留了歌曲列表的两个不同副本:一个在NowPlayingActivity中,另一个在TabSongsActivity中,您分别填充它们,并扫描sd卡中的每一个。如果在这两次扫描之间sd卡上有任何更改,则两个列表将不同,并且一个列表中的项目N可能不再对应于另一个列表中的项目N。只使用一个列表

最后,代码不起作用的原因是您混淆了startActivityForResult、setResult和onActivityResult。 startActivityForResult应位于具有onActivityResult方法的活动中,而setResult调用应位于startActivityForResult启动的活动中


如上所述,您只需从TabSongsActivity启动NowPlayingActivity。如果这真的是您想要的,那么您应该只使用普通的startActivity,并在NowPlayingActivity.onCreate或onResume或其他内容中检索意图及其附加内容。您实现的onActivityResult方法将永远不会被调用。

我在这里看不到任何明显的东西。也许在SongsManager.getPlaylist?我包括了歌曲管理器njzk2,谢谢你的回复!但我想指出的是,McClick在tabsongs活动上,而OnActivity则是nowplayingactivity的结果。他们有联系吗?我不是很确定,因为作为一个初学者,我只是参考了其他网站,并提出了这些。如果您能帮助我,我将非常感激。当调用两次时,扫描文件系统可能不会产生相同的结果。你至少应该确保只扫描一次。我认为你需要学习更多关于活动的基本知识,才能解决你的问题。阅读文档了解它是如何工作的,这样就更容易理解错误所在。我有一个错误,类型Intent中的getIntExtraString,int方法不适用于参数StringOh,这是因为该方法包含两个参数。我更新了答案。第二个参数是在找不到请求的整数时的默认值。发生了相同的输出,可能错误来自onitemClick或onActivity结果?您能检查一下吗?您的TabSongsActivity正在呼叫PlayingActivity吗?或者是另一种方式?是的,我的TabSongsActivity是调用NowPlayingActivity。TabSongsActivity是歌曲列表,NowPlayingActivity是从TabSongs接收OnItemClick的播放器。感谢您的回复,但在此之前,这是有效的。作为玩家的NowPlaying活动以前位于TabActivity中,因此它是在mainActivity开始时创建的。TabSongsActivity以前是一个按钮的活动,该按钮将为该玩家打开一个列表。它工作得很好,但现在我意识到列表应该在选项卡上,所以我切换了这两个活动。在onItemClick上添加了startactivity,但现在无法单击特定项目。我很困惑。马科尼就在这里,你也应该考虑改变这个。你正在把你的启动活动和结果调用混为一谈。非常感谢马可尼和默莱维德,我会进一步研究它。我会在第二天提交,所以我很忙:但再次感谢你给我的线索!