嗨我目前在我的Android媒体播放器项目上工作,一切都很好,但后来我改变了布局设计,现在我每次启动时都得到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个月后,我就一直致力于这个项目,但现在我仍然坚持这个错误
答案 0 :(得分:4)
这一行
btnSongList.setOnClickListener(new OnClickListener(){@Override public void
onClick(View v) {visible();}});
您从未为此特定视图调用findViewById()
,因此指针仍为空。
答案 1 :(得分:1)
第117行尝试使用返回null的View
,或者尚未初始化。
您是否更改了布局文件中任何View
的id属性?最后,每当你改变一个布局文件时,你需要清理并重建你的项目,因为旧的版本被缓存以便更快地启动并且通常会破坏它们!
答案 2 :(得分:1)
以下一段代码是第117行:
btnSongList.setOnClickListener(new OnClickListener(){@Override public void
onClick(View v) {visible();}});
但是,btnSongList仅在第50行出现一次:
private ImageButton btnSongList;
代码缺少btnSongList的任何初始化。因此发生NullPointerException。也许缺少一段代码(如果布局中的btnPlaylist是代码中的btnSongList):
btnSongList = (ImageButton) findViewById(R.id.btnPlaylist);