Youtube API crashes when onpause - java

Youtube API crashes when I am in onpause state.
When I am playing Youtube video onclick it is working fine but when I am minimizing my app in onpause state it crashes. So give me some suggestions. I never used Youtube API before so I have no idea about it. Please review my code whether it is good. if not, then please provide good
suggestion too. Thanks in advance.
package com.app.embedyoutube;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
public class MainActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener {
String key="AIzaSyASLaX32-EG2Rx0EWZFPbwhuBDgsBgC6e0";
YouTubePlayer youTubePlayer1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final YouTubePlayerView youtubePlayerView = findViewById(R.id.youtubePlayerView);
youtubePlayerView.initialize(key,this);
findViewById(R.id.b1).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
play("ScQrLSBAuQk");
}
});
findViewById(R.id.b2).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
play("Ow9-fzf4Qbk");
}
});
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer1=youTubePlayer;
youTubePlayer1.cueVideo("Ow9-fzf4Qbk");
youTubePlayer1.setPlayerStateChangeListener(new YouTubePlayer.PlayerStateChangeListener() {
#Override public void onAdStarted() { }
#Override public void onError(YouTubePlayer.ErrorReason arg0) { }
#Override public void onLoaded(String arg0) { }
#Override public void onLoading() { }
#Override public void onVideoEnded() { }
#Override public void onVideoStarted() { }
});
youTubePlayer1.setPlaybackEventListener(new YouTubePlayer.PlaybackEventListener() {
#Override public void onBuffering(boolean arg0) { }
#Override public void onPaused() { }
#Override public void onPlaying() { }
#Override public void onSeekTo(int arg0) { }
#Override public void onStopped() { }
});
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
public void play(String url)
{
if( youTubePlayer1 != null ) {
youTubePlayer1.cueVideo(url);
}
}
#Override
public void onPause()
{
super.onPause();
if (youTubePlayer1 != null) {
if(youTubePlayer1.isPlaying()) {
// currentPlayerTime = youTubePlayer1.getCurrentTimeMillis();
youTubePlayer1.pause();
}
}
}
}

#Override
public void onPause()
{
super.onPause();
if (youTubePlayer1 != null) {
youTubePlayer1.release();
}
}
and you can save your current video time in savedInstanceState
but for better solution i will recommend you to initialize your player in onResume and release it in onStop like this.
#Override
protected void onResume() {
super.onResume();
playerView.initialize(KEY, this);
}
#Override
public void onStop() {
if (player != null) {
player.release();
}
player = null;
super.onStop();
}

Related

MediaPlayer App is crashing when i try to run

I'm beginner in android development and tried to create a simple mediaplayer app which plays media from local source.
But it's crashing when i try to open it.
This is my java code.
package com.example.media;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
public class MainActivity extends AppCompatActivity {
Button play,pause;
SeekBar s;
MediaPlayer m;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m=MediaPlayer.create(this,R.raw.live);
play=findViewById(R.id.button3);
pause=findViewById(R.id.button4);
s.findViewById(R.id.seekBar);
s.setMax(m.getDuration());
s.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(fromUser)m.seekTo(progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
m.start();
}
});
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
m.pause();
}
});
}
}
You need to initialize the seekbar object instead of calling the findViewById method.
So just replace the dot with equal sign :
s=findViewById(R.id.seekBar);

Mapbox SDK Android Studio

I got to put the map in my app and running in my mobile, but I don't get to put the overlay file GeoJson from Assets Folder in the my locate folder in PC. I want to overlay the points from GeoJson and show popups of points' id. How could I do this?
Below the code that I made from tutorials in Mapbox site in Android Studio
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.maps.Style;
import com.mapbox.mapboxsdk.style.sources.GeoJsonSource;
import java.net.URI;
import java.net.URISyntaxException;
public class MainActivity extends AppCompatActivity {
private MapView mapView;
private final String SOURCE_ID = "SOURCE_ID";
private final String ICON_ID = "ICON_ID";
private final String LAYER_ID = "LAYER_ID";
private final String TAG = "TAG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.access_token));
setContentView(R.layout.activity_main);
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(#NonNull MapboxMap mapboxMap) {
mapboxMap.setStyle(Style.DARK, new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
try {
GeoJsonSource layer = new GeoJsonSource("mapView", new URI("assets://covid_unidades.geojson"));
style.addSource(layer);
} catch (URISyntaxException excepcion) {
Log.d(TAG, String.valueOf(excepcion));
}
}
});
}
});
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
#Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
} ```

How can I implement the "pause" function in my MediaPalyer?

The "stop" and "play" work fine, but "pause" works like "stop". When I press pause, the audiofile stops playing and when I press play, it starts from the beginning.
The "stop" and "play" work fine, but "pause" works like "stop". When I press pause, the audiofile stops playing and when I press play, it starts from the beginning.
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class HelloMoonFragment extends Fragment
{
private AudioPlayer mPlayer = new AudioPlayer();
private Button mPlayButton;
private Button mStopButton;
private Button mPauseButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_hello_moon, parent, false);
mPlayButton = (Button)v.findViewById(R.id.hellomoon_playButton);
mPlayButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
mPlayer.play(getActivity());
}
});
mPauseButton = (Button) v.findViewById(R.id.hellomoon_pauseButton);
mPauseButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
mPlayer.pause();
}
});
mStopButton = (Button)v.findViewById(R.id.hellomoon_stopButton);
mStopButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
mPlayer.stop();
}
});
return v;
}
#Override
public void onDestroy()
{
super.onDestroy();
mPlayer.stop();
}
}
package com.example.hellomoon;
import android.content.Context;
import android.media.MediaPlayer;
public class AudioPlayer {
private MediaPlayer mPlayer;
public void stop()
{
if(mPlayer != null)
{
mPlayer.release();
mPlayer = null;
}
}
public void pause()
{
if(mPlayer.isPlaying())
{
mPlayer.pause();
}
}
public void play(Context c)
{
stop();
mPlayer = MediaPlayer.create(c, R.raw.one_small_step);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
stop();
}
});
mPlayer.start();
}
}
it starts from the beginning because here:
public void play(Context c) {
stop();
mPlayer = MediaPlayer.create(c, R.raw.one_small_step);
you are releasing the old one a create it again
Try remembering the the player is paused:
public class AudioPlayer {
boolean isPaused = false;
public void pause() {
if(mPlayer.isPlaying()) {
mPlayer.pause();
isPaused = true;
}
}
public void play(Context c) {
if (isPaused && mPlayer != null) {
mPlayer.start();
isPaused = false
return;
}
stop();
mPlayer = MediaPlayer.create(c, R.raw.one_small_step);

Implementing Music Across Activities

Problem: When I use the home button to close the app the music continues playing. So I manually close the app by killing the activity, the music stops... for a few seconds and then starts again (and this time a restart is in order to turn it off).
MusicService.class:
package com.MyApp.App;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;
public class MusicService extends Service implements
MediaPlayer.OnErrorListener {
private final IBinder mBinder = new ServiceBinder();
MediaPlayer mPlayer;
private int length = 0;
public MusicService() {
}
public class ServiceBinder extends Binder {
MusicService getService() {
return MusicService.this;
}
}
#Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
#Override
public void onCreate() {
super.onCreate();
mPlayer = MediaPlayer.create(this, R.raw.test_music);
mPlayer.setOnErrorListener(this);
if (mPlayer != null) {
mPlayer.setLooping(true);
mPlayer.setVolume(100, 100);
}
mPlayer.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
onError(mPlayer, what, extra);
return true;
}
});
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mPlayer.start();
return START_STICKY;
}
public void pauseMusic() {
if (mPlayer.isPlaying()) {
mPlayer.pause();
length = mPlayer.getCurrentPosition();
}
}
public void resumeMusic() {
if (mPlayer.isPlaying() == false) {
mPlayer.seekTo(length);
mPlayer.start();
}
}
public void stopMusic() {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
#Override
public void onDestroy() {
super.onDestroy();
if (mPlayer != null) {
try {
mPlayer.stop();
mPlayer.release();
} finally {
mPlayer = null;
}
}
}
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(this, "music player failed", Toast.LENGTH_SHORT).show();
if (mPlayer != null) {
try {
mPlayer.stop();
mPlayer.release();
} finally {
mPlayer = null;
}
}
return false;
}
}
MainPage.class:
package com.MyApp.App;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
public class MainPage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
Intent music = new Intent();
music.setClass(this, MusicService.class);
startService(music);
}
#Override
protected void onDestroy() {
super.onDestroy();
mServ.stopMusic();
}
#Override
protected void onPause() {
super.onPause();
mServ.pauseMusic();
}
#Override
protected void onStop() {
super.onStop();
mServ.stopMusic();
}
private boolean mIsBound = false;
private MusicService mServ;
private ServiceConnection Scon = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder binder) {
mServ = ((MusicService.ServiceBinder) binder).getService();
}
public void onServiceDisconnected(ComponentName name) {
mServ = null;
}
};
void doBindService() {
bindService(new Intent(this, MusicService.class), Scon,
Context.BIND_AUTO_CREATE);
mIsBound = true;
}
void doUnbindService() {
if (mIsBound) {
unbindService(Scon);
mIsBound = false;
}
}
}
(NOTE: I have taken excerpts from my app, so I may have forgotten imports in this code, but all imports are correctly included in the app.)
Fixed:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
doBindService();
Intent music = new Intent();
music.setClass(this, MusicService.class);
startService(music);
}
and
#Override
protected void onDestroy() {
super.onDestroy();
doUnbindService();
}
please red : onCreate, OnPause , OnResume

CursorLoader does not refresh data

I'm creating application to add movie data via external web service to internal database and display list of movies as the main activity in ListFragment, another activity is responsible for search function.
ListFragment mentioned above fetches data from database using LoaderManager. Also this fragment is retained using setRetainInstance(true).
Problem that I encounter is that when I navigate to search, add something to database, and go back to ListFragment by pressing Back Button its not refreshed i.e. added movie is not displayed.
A few important things:
I'm not using ContentProvider so I manually retrieve Cursor from my data base in onCreateLoaderMethod.
I'm using support library - I hope that all imports are proper (if someone could check).
ListFragment uses custom CursorAdapter as its view.
Here is the code:
package com.mp.movieplanner;
import android.app.Activity;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import com.mp.movieplanner.data.DataManager;
public class MovieListFragment extends ListFragment
implements LoaderManager.LoaderCallbacks<Cursor> {
public static String TAG = MovieListFragment.class.getSimpleName();
private OnMovieSelectedListener mCallback;
private DataManager mDataManager;
private MovieCursorAdapter mAdapter;
public interface OnMovieSelectedListener {
public void onMovieSelected(int position);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.i(TAG, "onAttach(Activity)");
mDataManager = ((MoviePlannerApp)activity.getApplication()).getDataManager();
try {
mCallback = (OnMovieSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnMovieSelectedListener");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate(Bundle)");
final int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ? android.R.layout.simple_list_item_activated_1
: android.R.layout.simple_list_item_1;
setRetainInstance(true);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.i(TAG, "onActivityCreated(Bundle)");
super.onActivityCreated(savedInstanceState);
mAdapter = new MovieCursorAdapter(getActivity(), null, 0);
setListAdapter(mAdapter);
getLoaderManager().initLoader(0, null, this);
}
#Override
public void onStart() {
super.onStart();
Log.i(TAG, "onStart()");
if (getFragmentManager().findFragmentById(R.id.movie_details_fragment) != null) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
}
#Override
public void onResume() {
super.onResume();
Log.i(TAG, "onResume()");
}
#Override
public void onDetach() {
super.onDetach();
Log.i(TAG, "onDetach()");
mCallback = null;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Notify the parent activity of selected item
if (mCallback != null) {
mCallback.onMovieSelected(position);
// Set the item as checked to be highlighted when in two-pane layout
getListView().setItemChecked(position, true);
}
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(getActivity()) {
#Override
public Cursor loadInBackground() {
return mDataManager.getMovieCursor();
}
};
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> arg0) {
mAdapter.swapCursor(null);
}
#Override
public void onPause() {
Log.i(TAG, "onPause()");
super.onPause();
}
#Override
public void onStop() {
Log.i(TAG, "onStop()");
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy()");
}
}
I would advise:
#Override
public void onResume() {
super.onResume();
Log.i(TAG, "onResume()");
getLoaderManager().restartLoader(0, null, this);
}
#Override
public void onResume() {
super.onResume();
Log.i(TAG, "onResume()");
getLoaderManager().initLoader(0, null, this);
}
try that

Categories