#android #android-fragments
#Android #android-фрагменты
Вопрос:
У меня есть следующий код
Статический класс
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Handler;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
import java.util.concurrent.TimeUnit;
public class CustomMedia {
public static MediaPlayer mediaPlayer,englishmediaPlayer;
public static TextView duration,englishduration;
public static double timeElapsed = 0, finalTime = 0;
public static double englishtimeElapsed = 0, englishfinalTime = 0;
public static int forwardTime = 2000, backwardTime = 2000;
public static Handler durationHandler = new Handler();
public static int englishforwardTime = 2000, englishbackwardTime = 2000;
public static Handler englishdurationHandler = new Handler();
public static SeekBar seekbar,englishseekbar;
public static void initializeViews(View v,Context context,Integer songName){
mediaPlayer = MediaPlayer.create(context,songName);
finalTime = mediaPlayer.getDuration();
duration = (TextView)v.findViewById(R.id.song_duration_display);
seekbar = (SeekBar)v.findViewById(R.id.media_seekbar);
seekbar.setMax((int) finalTime);
seekbar.setClickable(false);
}
// play mp3 song
public static void play() {
mediaPlayer.start();
timeElapsed = mediaPlayer.getCurrentPosition();
seekbar.setProgress((int) timeElapsed);
durationHandler.postDelayed(updateSeekBarTime, 100);
}
//handler to change seekBarTime
private static Runnable updateSeekBarTime = new Runnable() {
public void run() {
//get current position
timeElapsed = mediaPlayer.getCurrentPosition();
//set seekbar progress
seekbar.setProgress((int) timeElapsed);
//set time remaing
double timeRemaining = finalTime - timeElapsed;
duration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining), TimeUnit.MILLISECONDS.toSeconds((long) timeRemaining) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining))));
//repeat yourself that again in 100 miliseconds
durationHandler.postDelayed(this, 100);
}
};
// pause mp3 song
public static void pause() {
mediaPlayer.pause();
}
// go forward at forwardTime seconds
public static void forward(View view) {
//check if we can go forward at forwardTime seconds before song endes
if ((timeElapsed forwardTime) <= finalTime) {
timeElapsed = timeElapsed forwardTime;
//seek to the exact second of the track
mediaPlayer.seekTo((int) timeElapsed);
}
}
// go backwards at backwardTime seconds
public static void rewind(View view) {
//check if we can go back at backwardTime seconds after song starts
if ((timeElapsed - backwardTime) > 0) {
timeElapsed = timeElapsed - backwardTime;
//seek to the exact second of the track
mediaPlayer.seekTo((int) timeElapsed);
}
}
public static void stop(View view) {
mediaPlayer.seekTo(0);
mediaPlayer.pause();
}
}
Музыкальный фрагмент
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class OldMusic extends Fragment {
View v;
ImageView play;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.old_music, container, false);
play= (ImageView) v.findViewById(R.id.btn_play);
return v;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
CustomMedia.initializeViews(v,getContext(),R.raw.somya);
play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CustomMedia.play();
}
});
}
@Override
public void onPause() {
super.onPause();
}
}
Я создал статический класс для медиаплеера, чтобы я мог вызывать его во многих фрагментах.Но я получаю следующее исключение нулевого указателя.Может ли кто-нибудь помочь мне исправить это?
Обновлено
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.asd.learn.OldMusic.onActivityCreated(OldMusic.java:34)
at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1970)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1041)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1197)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1562)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:483)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4960)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)
Комментарии:
1. трассировка стека после ошибки
2. @sanjeetkumarSingh. Получение исключения с нулевым указателем в play.setOnClickListener (новый вид. OnClickListener() {
3. в трассировке стека ошибок найдите
CausedBy
, который укажет, где произошла ошибка4. @sanjeetkumarSingh.обновленный вопрос
5. Проблема в переменной
play
, почему вы не перемещаете код внутриonActivityCreated
вonCreateView
?