Search code examples
androidnullpointerexceptionandroid-mediaplayerwebviewclient

NullPointerException when initializing the media player on url


I need help, there are osvnonoe Activiti in which history is loaded tracks, when you click on the track opens an alert dialog with loading the page, then the link is redirected, and the output is a link with the track, which I send to the media player in the service, but I get a NullPointerException

Example link

http://s.spynetstation.com/m/8/Loud%20Sound/TAMFREE026/unknown-Blitzkrieg-320kbps.mp3

Error

FATAL EXCEPTION: main
java.lang.NullPointerException
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:783)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:761)
at com.spynetstation.MediaService.initT(MediaService.java:132)
at com.spynetstation.MainActivity$14.shouldOverrideUrlLoading(MainActivity.java:716)
at android.webkit.CallbackProxy.uiOverrideUrlLoading(CallbackProxy.java:224)
at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:324)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
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:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)

Code Activity

public class MainActivity extends FragmentActivity {

MediaPlayer mediaPlayer;
static AudioManager am;
static CheckBox pdaStream;
Button btnNews;
static TitleAdapter titleAdapter;
static ViewPager mViewPager;
RelativeLayout RelativeLayout1;
static String selectStream;
public String stream_sel;
public static String colors_sel;
public int stream;
public static int colors;
public boolean checker;
public static boolean track;
public boolean searchtrack;
public boolean searchtrackhistory;
static SharedPreferences mSettings;
static TextView titleMusic;
static boolean replay = false;
public MusicIntentReceiver myReceiver;
//History
public LinearLayout history;
public Button btn_up;
public boolean history_view = false;
public static TextView history1;
public static TextView history2;
public static TextView history3;
public static TextView history4;
public static TextView history5;
boolean loadingFinished = true;
boolean redirect = false;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Create();
}


public void Create(){
    setContentView(R.layout.activity_main);

    //Settings
    mSettings = PreferenceManager.getDefaultSharedPreferences(this);
    //Language settings
    lang = mSettings.getString("lang", "default");  
    if (lang.equals("default")) {lang=getResources().getConfiguration().locale.getCountry();}
    locale = new Locale(lang);
    Locale.setDefault(locale);
    Configuration config = new Configuration();
    config.locale = locale;
    Log.i("Lang change", "Locale="+locale);
    getBaseContext().getResources().updateConfiguration(config, null);
    //End Language

    mViewPager = (ViewPager) findViewById(R.id.pager);
    RelativeLayout1 = (RelativeLayout) findViewById(R.id.RelativeLayout1);
    pdaStream = (CheckBox) findViewById(R.id.pdaStream);
    pdaStream.setText(R.string.chkbox);

    checker = mSettings.getBoolean("checker", false);
    Log.i("Resume: checker=",""+checker);
    track = mSettings.getBoolean("track", false);
    Log.i("Resume: track=",""+track);
    searchtrack = mSettings.getBoolean("searchtrack", false);
    Log.i("Resume: searchtrack=",""+searchtrack);
    searchtrackhistory = mSettings.getBoolean("searchtrackhistory", false);
    Log.i("Resume: searchtrackhistory=",""+searchtrackhistory);
    stream_sel = mSettings.getString("stream", "1");
    Log.i("Resume: stream_sel=",""+stream_sel);
    if (stream_sel.equals("0")) {
        stream = 0;}
    else if (stream_sel.equals("1")) {
        stream = 1;}
    else if (stream_sel.equals("2")) {
        stream = 2;}
    else stream = 1;
    Log.i("Default Stream=", " "+stream);

    //---
    Log.i("MainActivity","onCreate");

    titleAdapter = new TitleAdapter(getSupportFragmentManager());
    mViewPager.setAdapter(titleAdapter);
    mViewPager.setCurrentItem(stream);
    mViewPager.setOffscreenPageLimit(3);
    stream_buf = stream;



    am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    SeekBar music = (SeekBar)findViewById(R.id.seekBar1);
    initBar(music, AudioManager.STREAM_MUSIC);
    if (Free) {pdaStream.setChecked(true);}
    else {pdaStream.setChecked(checker);}
    titleMusic = (TextView) findViewById(R.id.titleMusic);
    titleMusic.setSelected(true);
    titleMusic.setVisibility(View.VISIBLE);
    CallReceiver.state = true;

    StartHistory();

    IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
    myReceiver = new MusicIntentReceiver();
    registerReceiver(myReceiver, filter);

    SearchTrack(); 
    startService(new Intent(this, MediaService.class));
}


public void StartHistory() {
    history1 = (TextView) findViewById(R.id.history1);
    history1.setSelected(true);
    history2 = (TextView) findViewById(R.id.history2);
    history2.setSelected(true);
    history3 = (TextView) findViewById(R.id.history3);
    history3.setSelected(true);
    history4 = (TextView) findViewById(R.id.history4);
    history4.setSelected(true);
    history5 = (TextView) findViewById(R.id.history5);
    history5.setSelected(true);
    history = (LinearLayout) findViewById(R.id.history);
    history.setVisibility(View.INVISIBLE);
    btn_up = (Button) findViewById(R.id.btn_up);
    btn_up.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (history_view){
                    Log.i("StartHistory","History close");
                    btn_up.setBackgroundResource(R.drawable.up);
                    history.setVisibility(View.INVISIBLE);
                    history_view=false;
                    MediaService.only_his=false;
                    if (MediaService.mediaPlayer==null){
                        titleMusic.setText(" ");
                    }
                } else {
                    Log.i("StartHistory","History open");
                    btn_up.setBackgroundResource(R.drawable.up2);
                    history.setVisibility(View.VISIBLE);
                    history_view=true;
                    if (MediaService.mediaPlayer==null){
                        MediaService.only_his=true;

                            if (stream_buf==0){
                                MediaService.InputHistory("http://liquid.spynetstation.com:8000/meta.txt");
                                MediaService.SearchInHistory("http://liquid.spynetstation.com:8000/linkable_current_track.txt");
                            }
                            if (stream_buf==1){
                                MediaService.InputHistory("http://main.spynetstation.com:8000/meta.txt");
                                MediaService.SearchInHistory("http://main.spynetstation.com:8000/linkable_current_track.txt");
                            }
                            if (stream_buf==2){
                                MediaService.InputHistory("http://dub.spynetstation.com:8000/meta.txt");
                                MediaService.SearchInHistory("http://dub.spynetstation.com:8000/linkable_current_track.txt");
                            }

                    }else {MediaService.only_his=false;}
            }

        } 
    });
}


public void SearchTrack(){

    final String searchurl = "https://www.google.ru/search?q=";
    titleMusic.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (searchtrack){} else {
                if (MediaService.currentlyPlaying != null){
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(searchurl + MediaService.currentlyPlaying)));
                }
            }
        }
    });
    history1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (searchtrackhistory){} else {
                if (MediaService.his[1] != null){
                    ShowTrack(MediaService.searchhis[0],MediaService.his[1]);
                }
            }
        }
    });
    history2.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (searchtrackhistory){} else {
                if (MediaService.his[2] != null){
                    ShowTrack(MediaService.searchhis[1],MediaService.his[2]);
                }
            }
        }
    });
    history3.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (searchtrackhistory){} else {
                if (MediaService.his[3] != null){
                    ShowTrack(MediaService.searchhis[2],MediaService.his[3]);
                }
            }
        }
    });
    history4.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (searchtrackhistory){} else {
                if (MediaService.his[4] != null){
                    ShowTrack(MediaService.searchhis[3],MediaService.his[4]);
                }
            }
        }
    });
    history5.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (searchtrackhistory){} else {
                if (MediaService.his[5] != null){
                    ShowTrack(MediaService.searchhis[4],MediaService.his[5]);
                }
            }
        }
    });
}

public void ShowTrack(final String smetaout,String stitleout){

    AlertDialog.Builder alert = new AlertDialog.Builder(this); 
    alert.setTitle(stitleout);

    final WebView wv = new WebView(this);


    Log.d("My Webview", "ShowTrack");


    wv.getSettings().setJavaScriptEnabled(true);
    wv.loadUrl(smetaout);
    wv.setWebViewClient(new WebViewClient() {



         @Override
           public boolean shouldOverrideUrlLoading(WebView view, String url) {


               if (!loadingFinished) {
                  redirect = true; 
               }

           loadingFinished = false;

           view.loadUrl(url);
           Log.d("shouldOverrideUrlLoading", url);
           Uri myUri = Uri.parse(url);
           MediaService.initT(myUri);
           MediaService.startT();
           return true;
           }



           @Override
           public void onPageFinished(WebView view, String url) {

               if(!redirect){
                  loadingFinished = true;
               }

               if(loadingFinished && !redirect){

               } else{
                  redirect = false; 
               }

            }

    });

    alert.setView(wv);
    alert.setNegativeButton("Close", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            dialog.dismiss();
        }
    });
    alert.show();
}


}

Code Service

public class MediaService extends Service implements OnPreparedListener,OnCompletionListener{

static boolean isPlayingMain = false;
static boolean isPlayingLiquid = false;
static boolean isPlayingDubstep = false;
static MediaPlayer mediaPlayer;
static NotificationManager nm;
private static NotificationCompat.Builder mBuilder;
private static Notification.Builder mNBuilder;
public static Context ctx;



public IBinder onBind(Intent paramIntent)  {
    return null;
}


public static void initT(Uri urlTrack){
    try {
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    Log.d("initT",""+urlTrack);
    mediaPlayer.setDataSource(ctx,urlTrack);
    mediaPlayer.prepare();
    } catch (IOException e) {
          e.printStackTrace();
    } catch (IllegalArgumentException e) {
          e.printStackTrace();
    }
    Log.i("MediaService", "prepare");

}

public static void startT(){
    mediaPlayer.setOnPreparedListener(new OnPreparedListener() {  
        @Override  
        public void onPrepared(MediaPlayer mp) {
            mp.start();
            Log.i("MediaService", "start");

        }
    });

}



public static void releaseMP() {
    if (mediaPlayer != null) {
        try {
            mediaPlayer.release();
            Log.i("MediaService", "release"); 
            mediaPlayer = null;
        } 
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

@Override
public void onCompletion(MediaPlayer mp) {
    Log.i("MediaService", "onCompletion"); 

}

@Override
public void onPrepared(MediaPlayer mp) {
    Log.i("MediaService", "onPrepareed");
}

public void onCreate()  {
    super.onCreate();
    ctx = getApplicationContext();
    //notif(titleNotif, contentNotif);
    //this.nm = ((NotificationManager)getSystemService("notification"));

}


public void onDestroy()  {
    //this.nm.cancelAll();
    stopForeground(true);
    if(CallReceiver.telManager != null) {
        CallReceiver.telManager.listen(CallReceiver.phoneListener, PhoneStateListener.LISTEN_NONE);
        Log.i("CallReceiver", "Destroy");
    }
}


public int onStartCommand(Intent paramIntent, int paramInt1, int paramInt2)  {

    try    {
          TimeUnit.SECONDS.sleep(0);
          notif(getResources().getString(R.string.title_notif),getResources().getString(R.string.title_notif));
          return super.onStartCommand(paramIntent, paramInt1, paramInt2);
        }
        catch (InterruptedException localInterruptedException)    {
          for (;;)      {
            localInterruptedException.printStackTrace();
          }
        }
}


public void notif(String titleNotif, String contentNotif){

    //building the notification
    mBuilder = new NotificationCompat.Builder(ctx)
    .setSmallIcon(R.drawable.spy)
    .setContentTitle(titleNotif)
    .setTicker(contentNotif)
    .setOngoing(true)
    //.addAction(R.drawable.media_play, "Play", notificationIntent)
    ;

    Intent notificationIntent = new Intent(ctx, MainActivity.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(pendingIntent);
    //Notification n = mBuilder.build();
    //nm.notify(1, n);


    startForeground(1, mBuilder.build());

}


}

Solution

  • Thank you all for your answers! Decided as follows:

    In the service has changed as follows:

    public static void initT(Context context,Uri urlTrack){
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            Log.d("initT",""+urlTrack);
            mediaPlayer.setDataSource(context,urlTrack);
            mediaPlayer.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        Log.i("MediaService", "prepare");
    }
    

    In Activity changed as follows:

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (!loadingFinished) {
            redirect = true;
        }
        loadingFinished = false;
        view.loadUrl(url);
        Log.d("shouldOverrideUrlLoading", url);
        Uri myUri = Uri.parse(url);
        context = getApplicationContext();
        MediaService.releaseMP();
        MediaService.initT(context, myUri);
        MediaService.startT();
        return true;
    }