java - findviewbyid上的Android空指针异常

标签 java android media-player

您好,我目前正在开发我的 android mediaplayer 项目,一切都很好,但后来我更改了布局设计,现在我每次启动时都会遇到 java.nullpointerexception,我到处都在寻找答案,但我所做的一切都没有工作......任何人都可以帮助我吗?

这里是layout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:orientation="vertical" >

<SeekBar
    android:id="@+id/sbSong"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_marginBottom="72dp" />

<ImageButton
    android:id="@+id/btnNext"
    android:contentDescription="@string/Next"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:src="@drawable/next" />

<ImageButton
    android:id="@+id/btnBack"
    android:contentDescription="@string/Previous"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:src="@drawable/previous" />

<ImageButton
    android:id="@+id/btnPlay"
    android:contentDescription="@string/btnPlay"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:src="@drawable/play" />

<ImageButton
    android:id="@+id/btnShuffle"
    android:contentDescription="@string/shuffleOn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/sbSong"
    android:layout_alignParentRight="true"
    android:src="@drawable/shuffle_off" />

<ImageButton
    android:id="@+id/btnRepeat"
    android:contentDescription="@string/repeatOn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/sbSong"
    android:layout_alignParentLeft="true"
    android:src="@drawable/repeat_off" />

<TextView
    android:id="@+id/txtDuration"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/btnShuffle"
    android:layout_toLeftOf="@+id/btnShuffle"
    android:text="TextView" />

<TextView
    android:id="@+id/txtCurrentPosition"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/btnRepeat"
    android:layout_toRightOf="@+id/btnRepeat"
    android:text="TextView" />

<ImageView
    android:id="@+id/AlbumArtwork"
    android:contentDescription="@string/noSong"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/btnShuffle"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="66dp"
    android:src="@drawable/noartwork" />




<TextView
    android:id="@+id/txtSongTitle"
    android:layout_width="wrap_content"
    android:layout_height="40dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:text="Medium Text"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<ImageButton
    android:id="@+id/btnPlaylist"
    android:contentDescription="@string/SongList"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:src="@drawable/dropdown" />

<ListView
    android:id="@+id/lstSongs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:visibility="invisible"
    android:layout_below="@+id/txtSongTitle" >
</ListView>


<EditText
    android:id="@+id/searchbox"
    android:visibility="invisible"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@+id/btnPlaylist"
    android:ems="10" >

    <requestFocus />
</EditText>

</RelativeLayout>

-和.java 包 com.example.player;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


import com.example.player.R;

import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public  class MainActivity extends Activity implements OnCompletionListener {
//Declaration de variable globale
//button
private ImageButton btnPlayPause;
private ImageButton btnShuffle;
private ImageButton btnRepeat;
private ImageButton btnNext;
private ImageButton btnBack;
private ImageButton btnSongList;
private SeekBar songBar;
private TextView txtTitle;
private TextView txtCurrentTime;
private TextView txtDuration;
private ListView lstSongs;
private ImageView cover;
private EditText searchbox;
//Variable
private boolean isShuffle = false;
private boolean isRepeat = false;
private boolean isVisible = false;
private String minutes = "";
private String seconds = "";
private int textlength = 0;
private ArrayList<HashMap<String,String>> songs_sort = new  
    ArrayList<HashMap<String,String>>();
@SuppressLint("SdCardPath")
private String SDCARD ="/sdcard/";
//MediaPlayer
private MediaPlayer mp;
private int songIndex = 0;
//Songs
public ArrayList<HashMap<String, String>> songs = new ArrayList<HashMap<String, 
    String>>();
//Handler de la seekbar
private final Handler handler = new Handler();

//Au load de l'Activity
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initialise();
}

private void initialise()
{

    //MediaPlayer
    mp = new MediaPlayer();
    //Dont Move Screen
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    //findViewById
    btnPlayPause = (ImageButton) findViewById(R.id.btnPlay);
    btnShuffle = (ImageButton) findViewById(R.id.btnShuffle);
    btnRepeat = (ImageButton) findViewById(R.id.btnRepeat);
    btnNext = (ImageButton) findViewById(R.id.btnNext);
    btnBack = (ImageButton) findViewById(R.id.btnBack);
    txtTitle = (TextView) findViewById(R.id.txtSongTitle);
    txtCurrentTime = (TextView) findViewById(R.id.txtCurrentPosition);
    txtDuration = (TextView) findViewById(R.id.txtDuration);
    lstSongs = (ListView) findViewById(R.id.lstSongs);
    songBar = (SeekBar) findViewById(R.id.sbSong);
    cover = (ImageView) findViewById(R.id.AlbumArtwork);
    searchbox = (EditText) findViewById(R.id.searchbox);
    //set les Listener
    btnPlayPause.setOnClickListener(new OnClickListener() {@Override public void 
    onClick(View v) {playPause();}});
    btnShuffle.setOnClickListener(new OnClickListener() {@Override public void 
    onClick(View v) {shuffle();}});
    btnRepeat.setOnClickListener(new OnClickListener() {@Override public void 
    onClick(View v) {repeat();}});
    btnNext.setOnClickListener(new OnClickListener(){@Override public void 
    onClick(View v) {next();}});
    btnBack.setOnClickListener(new OnClickListener(){@Override public void 
    onClick(View v) {back();}});
    btnSongList.setOnClickListener(new OnClickListener(){@Override public void 
    onClick(View v) {visible();}});
    searchbox.addTextChangedListener(new TextWatcher(){

        public void afterTextChanged(Editable et)
        {

        }
        @Override
        public void beforeTextChanged(CharSequence chars, int start,
                int count, int after) {
            // TODO Auto-generated method stub

        }


        @Override
        public void onTextChanged(CharSequence chars, int start, int 
                    count,int after)
        {
            // TODO Auto-generated method stub
            textlength = searchbox.getText().length();
            if(textlength > 0)
            {
                songs_sort.clear();
                for(int i = 0; i < songs.size();i++)
                {
                    if(textlength < 
                                            songs.get(i).get("songTitle").length())
                    {

    if(searchbox.getText().toString().equalsIgnoreCase((String) 
    songs.get(i).get("songTitle").subSequence(0, textlength)))
                        {

    songs_sort.add(songs.get(i));
                        }
                    }
                }
                adapt(songs_sort);
            }
            else
            {
                createPlaylist(SDCARD); 
            }


        }


    });
    mp.setOnCompletionListener(this);

    songBar.setOnTouchListener(new OnTouchListener() {@Override public boolean 
    onTouch(View v, MotionEvent event) {
        seekChange(v);
        return false; }
    });
    //la playlist
    createPlaylist(SDCARD);
}

//rempli la listview avec les titres de chansons
private void createPlaylist(String dir)
{
    songs.clear();
    /*Aller chercher TOUTES les chansons de la sdcard 
     * grâce a un cursor et une db
     * la db Mediastore est créer par android pour
     * stocker tout les informations sur les fichiers de la sdcard
     * je pousse le resultat de ma requete dans mon array de chansons
     * avec un while
     */
    String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";

    String[] projection = {
            MediaStore.Audio.Media.TITLE,
            MediaStore.Audio.Media.ARTIST,
            MediaStore.Audio.Media.DATA
    };

    @SuppressWarnings("deprecation")
    Cursor cursor = this.managedQuery(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            projection,
            selection,
            null,
            null);

    while(cursor.moveToNext()){
        HashMap<String,String> song = new HashMap<String,String>();
        song.put("songTitle",cursor.getString(0)+"-"+cursor.getString(1));
        song.put("songPath",cursor.getString(2) );
        songs.add(song);
    }

    //j'utilisais ceci avant pour aller chercher les chansons par une boucle de fichier
/*  File root = new File(dir);
    //loop a travers la carte sd Note: listFiles() n'entre pas dans les folders
    if(root.listFiles().length > 0)
    {
        for(File file : root.listFiles())
        {
            //if(file.isDirectory())
            //{

            //}else
            //{
                if(file.toString().endsWith(".mp3"))
                {
                    HashMap<String, String> song = new HashMap<String, 
   String>();
                    song.put("songTitle", file.getName().substring(0, 
   (file.getName().length() - 4)));
                    song.put("songPath", file.getPath());
                    songs.add(song);
                }
            //}
        }

    }*/

    //lier avec adapter
    adapt(songs);
}

private void adapt(ArrayList<HashMap<String,String>> array)
{

    //sort le arraylist
    Collections.sort(array, new Comparator<HashMap<String,String>>() {
        @Override
        public int compare(HashMap<String, String> lhs,
                HashMap<String, String> rhs) {
            // TODO Auto-generated method stub
            return 
   lhs.get("songTitle").compareToIgnoreCase(rhs.get("songTitle"));
        }
    });

    //Lier le array au listview comme data   
    ListAdapter adapter = new SimpleAdapter(this, array,R.layout.song_item, new 
    String[] { "songTitle" }, new int[] {R.id.song });
    lstSongs.setAdapter(adapter);
    lstSongs.setOnItemClickListener(new OnItemClickListener(){

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int 
    position,
                long id) {
            // TODO Auto-generated method stub
            playthis(position);
        }

    });
}

//joue la chanson a l'index selectionner
private void playthis(int position)
{
    songIndex = position;
    String path = songs.get(songIndex).get("songPath");
    Log.w("PLAYER","song path = "+ path);
    try {
        mp.reset();
        mp.setDataSource(path);
        mp.prepare();
        songBar.setMax(mp.getDuration());
        btnPlayPause.setImageResource(R.drawable.pause);
        txtTitle.setText(songs.get(songIndex).get("songTitle"));
        txtCurrentTime.setText("0:00");
        mp.start();
        timer();
        progressBar();
        getCover(path);

    } catch (Exception e) {
        // TODO: handle exception
    }
}



//Function PlayPause Button
private void playPause()
{   
    if(mp.isPlaying()){
        if(mp!=null){
            mp.pause();
            // je change l'image du boutton
            btnPlayPause.setImageResource(R.drawable.play);
        }
    }else{
        // repartir la chanson
        if(mp!=null){
            mp.start();
            // je change l'image du boutton
            btnPlayPause.setImageResource(R.drawable.pause);
        }
    }

}

//Function next la chanson
private void next()
{

    if(isShuffle)
    {
        //sort une chanson random
        Random rand = new Random();
        songIndex = rand.nextInt(songs.size()-1);
        playthis(songIndex);
    }
    else
    {

        //check si la chanson qui vient d'être jouer est la derniere de la liste
        if(songIndex < songs.size()-1)
        {
            songIndex = songIndex + 1;
            playthis(songIndex);
        }
        else
        {
            //repart avec la premiere chanson
            playthis(0);
        }

    }
}

//Function back() lit la chanson précédente ou une autre random
private void back()
{
    if(isShuffle)
    {
        //sort une chanson random
        Random rand = new Random();
        songIndex = rand.nextInt(songs.size()-1);
        playthis(songIndex);
    }
    else
    {

        //check si la chanson qui vient d'être jouer est la premiere de la liste
        if(songIndex > 0)
        {
            songIndex = songIndex - 1;
            playthis(songIndex);
        }
        else
        {
            //joue la derniere chanson
            playthis(songs.size()-1);
        }

    }
}

//Function timer pour le current time of the song
private void timer()
{
    //Duration de la chanson
    minutes = String.valueOf(mp.getDuration()/60000);
    seconds = String.valueOf(mp.getDuration() % 60000);
    seconds = seconds.substring(0, 2);
    txtDuration.setText(minutes+":"+seconds);

    ScheduledExecutorService myShedule = Executors.newScheduledThreadPool(1);

    myShedule.scheduleWithFixedDelay(
            new Runnable(){
       @Override
       public void run() {
        monitorHandler.sendMessage(monitorHandler.obtainMessage());
       }}, 
            200, //initialDelay
            200, //delay
            TimeUnit.MILLISECONDS);

      }

   Handler monitorHandler = new Handler(){

       @Override
       public  void handleMessage(Message msg) {
           mediacurrentposition();
       }

  };

  //Function mediacurrentposition
  private void mediacurrentposition()
  {
    if(mp.isPlaying())
    {
        minutes = String.valueOf(mp.getCurrentPosition()/60000);
        seconds = String.valueOf(mp.getCurrentPosition() % 60000);
        //seconds = seconds.substring(0, 2);
        /*if(Integer.getInteger(seconds) < 10)
        {
            seconds = "0"+seconds ;
        }*/
        txtCurrentTime.setText(minutes+":"+seconds);
    }
  }




//Function seekbar qui suis la chanson
private void progressBar()
{
    songBar.setProgress(mp.getCurrentPosition());
    if (mp.isPlaying()) {
        Runnable notification = new Runnable() {
            public void run() {
                progressBar();
            }
        };
        handler.postDelayed(notification,1000);
    }else{
        mp.pause();
        btnPlayPause.setImageResource(R.drawable.play);
        songBar.setProgress(mp.getCurrentPosition());
    }

}
//partir la chanson ou la seekbar est
private void seekChange(View v)
{
    SeekBar sb = (SeekBar)v;
    if(mp.isPlaying()){
        mp.seekTo(sb.getProgress());
    }
    else
    {
        mp.seekTo(sb.getProgress());
    }

    timer();
}

private void shuffle()
{
    if(isShuffle)
    {
        isShuffle = false;
        btnShuffle.setImageResource(R.drawable.shuffle_off);
    }else{
        isShuffle = true;
        btnShuffle.setImageResource(R.drawable.shuffle_on);
    }

}

private void repeat()
{
    if(isRepeat)
    {
        isRepeat = false;
        btnRepeat.setImageResource(R.drawable.repeat_off);
    }else{
        isRepeat = true;
        btnRepeat.setImageResource(R.drawable.repeat_on);
    }
}

@Override
public void onCompletion(MediaPlayer arg0)
{
    if(isRepeat)
    {
        //joue la même chanson sur repeat
        playthis(songIndex);
    }
    else if(isShuffle)
    {
        //sort une chanson random
        Random rand = new Random();
        songIndex = rand.nextInt(songs.size()-1);
        playthis(songIndex);
    }
    else
    {
        //la prochaine chanson suivant la  chanson qui vient d'être jouer
        //check si la chanson qui vient d'être jouer est la derniere de la liste
        if(songIndex < songs.size()-1)
        {
            songIndex = songIndex + 1;
            playthis(songIndex);
        }
        else
        {
            //repart avec la premiere chanson
            playthis(0);
        }

    }
}

private void visible()
{
    if(isVisible)
    {
        lstSongs.setVisibility(View.INVISIBLE);
        searchbox.setVisibility(View.INVISIBLE);
        isVisible = false;
        cover.setVisibility(View.VISIBLE);
        txtCurrentTime.setVisibility(View.VISIBLE);
        txtDuration.setVisibility(View.VISIBLE);
    }
    else
    {
        lstSongs.setVisibility(View.VISIBLE);
        searchbox.setVisibility(View.VISIBLE);
        isVisible = true;
        cover.setVisibility(View.INVISIBLE);
        txtCurrentTime.setVisibility(View.INVISIBLE);
        txtDuration.setVisibility(View.INVISIBLE);
    }
}

@TargetApi(10)
@SuppressLint({ "NewApi", "NewApi", "NewApi" })
private void getCover(String path)
{
    MediaMetadataRetriever  metaDataRetriver = new MediaMetadataRetriever();
    metaDataRetriver.setDataSource(path);
    byte[] pic;
    pic = metaDataRetriver.getEmbeddedPicture();

    if(pic == null)
    {
        cover.setImageResource(R.drawable.noartwork);
    }
    else
    {
        Bitmap bMap;
        bMap = BitmapFactory.decodeByteArray(pic, 0, pic.length);
        cover.setImageBitmap(bMap);
    }
}

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


}

-Logcat

11-30 11:06:28.989: D/AndroidRuntime(15673): Shutting down VM
11-30 11:06:28.989: W/dalvikvm(15673): threadid=1: thread exiting with uncaught 
exception (group=0x40018578)
11-30 11:06:28.999: E/AndroidRuntime(15673): FATAL EXCEPTION: main
11-30 11:06:28.999: E/AndroidRuntime(15673): java.lang.RuntimeException: Unable to  
start activity ComponentInfo{com.example.player/com.example.player.MainActivity}:   
java.lang.NullPointerException
11-30 11:06:28.999: E/AndroidRuntime(15673):    at 
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
11-30 11:06:28.999: E/AndroidRuntime(15673):    at 
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
11-30 11:06:28.999: E/AndroidRuntime(15673):    at 
android.app.ActivityThread.access$1500(ActivityThread.java:117)
11-30 11:06:28.999: E/AndroidRuntime(15673):    at 
android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
11-30 11:06:28.999: E/AndroidRuntime(15673):    at 
android.os.Handler.dispatchMessage(Handler.java:99)
11-30 11:06:28.999: E/AndroidRuntime(15673):    at 
android.os.Looper.loop(Looper.java:130)
11-30 11:06:28.999: E/AndroidRuntime(15673):    at 
android.app.ActivityThread.main(ActivityThread.java:3687)
11-30 11:06:28.999: E/AndroidRuntime(15673):    at 
java.lang.reflect.Method.invokeNative(Native Method)
11-30 11:06:28.999: E/AndroidRuntime(15673):    at 
java.lang.reflect.Method.invoke(Method.java:507)
11-30 11:06:28.999: E/AndroidRuntime(15673):    at 
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
11-30 11:06:28.999: E/AndroidRuntime(15673):    at 
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
11-30 11:06:28.999: E/AndroidRuntime(15673):    at 
dalvik.system.NativeStart.main(Native Method)
11-30 11:06:28.999: E/AndroidRuntime(15673): Caused by: java.lang.NullPointerException
11-30 11:06:28.999: E/AndroidRuntime(15673):    at 
com.example.player.MainActivity.initialise(MainActivity.java:117)
11-30 11:06:28.999: E/AndroidRuntime(15673):    at 
com.example.player.MainActivity.onCreate(MainActivity.java:88)
11-30 11:06:28.999: E/AndroidRuntime(15673):    at 
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-30 11:06:28.999: E/AndroidRuntime(15673):    at   
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
11-30 11:06:28.999: E/AndroidRuntime(15673):    ... 11 more

好吧,我知道有很多代码......自从我在学校的最后一个项目 2 个月以来,我一直在从事该项目,但现在我遇到了那个错误

最佳答案

这行在这里

btnSongList.setOnClickListener(new OnClickListener(){@Override public void 
    onClick(View v) {visible();}});

您从未为这个特定 View 调用过 findViewById(),因此指针仍然为空。

关于java - findviewbyid上的Android空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13648860/

相关文章:

Java:使用相同的元素初始化大小为 n > 1 的集合(列表)

java - 检索分成 2 个或更多字符串的文本行

android - Eclipse Juno 和 android maven 插件

android - 从改造响应中获取 JSONArray

Android MediaPlayer,是否支持渐进式下载音频?

java - 如何在 java 代码中使用 logcat 命令?

Android:将 ACTION_PICK_ACTIVITY 与 AppWidget 结合使用来确定在按下时打开哪个应用程序

Android MediaPlayer 导致游戏卡住并显示 "AudioHardware pcm playback is going to standby"

java - 在我的 Swing GUI 中嵌入视频的简单方法

java - Java jit 编译器每次运行都会编译它的代码吗?