Exoplayer: next and previous buttons - android

I want implement next and previous buttons below the ExoPlayer. I'm basing my code on this thread:
Implementing next button in audio player android
and the links in these ones:
How to add Listener for next , previous , rewind and forward in Exoplayer
How to add next song and previous song play button in audio player using android studio2.3?
The Exoplayer is in a fragment and opens on the right side of the screen on a tablet screen and in a separate activity on a mobile screen when the user clicks on one of the recipe steps. Data to the StepsFragment(implements an onClickListener) is sent via parcelable from the parent activity(code below).
Next and previous buttons are only implemented on the mobile screen(code works fine). I'm passing the arraylist and position from the parent activity in the onClick method and retrieving them in the fragment. The code works fine w/o the buttons, and both the list and the position are sent via parcelable to the VideoFragment only to implement the buttons. I decided to put the buttons in the Video Fragment.
Nothing happens when clicking on either the next or previous button. Code flow is indicated in the comments above the code in the onClickListener. I've tried to debug but no errors are displayed. Is this the right way to pass the arraylist? Although it's not shown in the debug and the log cat, I think it might be null. Can someone please have a look? Thank you in advance.
VideoFragment(contains Exoplayer code):
public class VideoFragment extends Fragment
{
// Tag for logging
private static final String TAG = VideoFragment.class.getSimpleName();
/**
* Mandatory empty constructor for the fragment manager to instantiate the fragment
*/
public VideoFragment()
{
}
ArrayList<Steps> stepsArrayList;
Steps stepClicked;
Recipes recipes;
SimpleExoPlayer mExoPlayer;
#BindView(R.id.playerView)
SimpleExoPlayerView mPlayerView;
#BindView(R.id.thumbnail_url)
ImageView thumbnailUrlImage;
public int stepPosition;
private long mPlayerPosition;
String videoUrl;
Uri videoUrl_Parse;
Uri thumbnailUrl_Parse;
String thumbnailUrl;
#BindView(R.id.previous_button)
Button previousButton;
#BindView(R.id.next_button)
Button nextButton;
#BindView(R.id.step_long_description)
TextView stepLongDescription;
String stepLongDescriptionUrl;
boolean mTwoPane;
private static final String KEY_POSITION = "position";
public static final String STEPS_LIST_INDEX = "list_index";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
//Inflate the Steps fragment layout
View rootView = inflater.inflate(R.layout.fragment_video, container, false);
// Bind the views
ButterKnife.bind(this, rootView);
Bundle bundle = this.getArguments();
if (bundle != null)
{
//Track whether to display a two-pane or single-pane UI
stepClicked = getArguments().getParcelable("Steps");
if (stepClicked != null)
{
mTwoPane = getArguments().getBoolean("TwoPane");
stepPosition = getArguments().getInt("StepPosition");
stepsArrayList = getArguments().getParcelableArrayList("StepsArrayList");
stepsArrayList = new ArrayList<>();
videoUrl = stepClicked.getVideoUrl();
Log.i("VideoUrl: ", stepClicked.getVideoUrl());
videoUrl_Parse = Uri.parse(videoUrl);
thumbnailUrl = stepClicked.getThumbnailUrl();
thumbnailUrl_Parse = Uri.parse(thumbnailUrl);
stepLongDescriptionUrl = stepClicked.getStepLongDescription();
Log.i("Step: ", stepClicked.getStepLongDescription());
stepLongDescription.setText(stepLongDescriptionUrl);
if (thumbnailUrl != null)
{
Picasso.with(getContext())
.load(thumbnailUrl_Parse)
.into(thumbnailUrlImage);
}
}
if (mTwoPane)
{
previousButton.setVisibility(View.INVISIBLE);
nextButton.setVisibility(View.INVISIBLE);
} else
{
previousButton.setVisibility(View.VISIBLE);
nextButton.setVisibility(View.VISIBLE);
//https://stackoverflow.com/questions/45253477/implementing-next-button-in-audio-player-android
nextButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if (stepPosition < stepsArrayList.size() - 1)
{
//Add or subtract the position in 1
stepClicked= stepsArrayList.get(stepPosition);
stepPosition++;
//Using the position, get the current step from the steps list
stepClicked= stepsArrayList.get(stepPosition);
//Extract the video uri from the current step
videoUrl = stepClicked.getVideoUrl();
Log.d("VideoUrlNext: ", stepClicked.getVideoUrl());
videoUrl_Parse = Uri.parse(videoUrl);
//Call initializePlayer() by passing the new video uri
initializePlayer(videoUrl_Parse);
}
}
});
previousButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if (stepPosition> 0)
{
stepPosition--;
//Using the position, get the current step from the steps list
stepClicked= stepsArrayList.get(stepPosition);
//Extract the video uri from the current step
videoUrl = stepClicked.getVideoUrl();
videoUrl_Parse = Uri.parse(videoUrl);
//Call initializePlayer() by passing the new video uri
initializePlayer(videoUrl_Parse);
}
}
});
}
}
if (savedInstanceState != null)
{
stepsArrayList = savedInstanceState.getParcelableArrayList(STEPS_LIST_INDEX);
mPlayerPosition = savedInstanceState.getLong(KEY_POSITION);
}
// Return the root view
return rootView;
}
//ExoPlayer code based on: https://codelabs.developers.google.com/codelabs/exoplayer-intro/#2
public void initializePlayer(Uri videoUrl)
{
if (mExoPlayer == null)
{
TrackSelector trackSelector = new DefaultTrackSelector();
LoadControl loadControl = new DefaultLoadControl();
mExoPlayer = ExoPlayerFactory.newSimpleInstance(getActivity(), trackSelector, loadControl);
mPlayerView.setPlayer((SimpleExoPlayer) mExoPlayer);
String userAgent = Util.getUserAgent(getContext(), "Baking App");
MediaSource mediaSource = new ExtractorMediaSource(videoUrl,
new DefaultDataSourceFactory(getContext(), userAgent),
new DefaultExtractorsFactory(), null, null);
mExoPlayer.prepare(mediaSource);
if (mPlayerPosition != C.TIME_UNSET)
{
mExoPlayer.seekTo(mPlayerPosition);
}
mExoPlayer.setPlayWhenReady(true);
}
}
#Override
public void onStart()
{
super.onStart();
if (Util.SDK_INT > 23 || mExoPlayer == null)
{
initializePlayer(videoUrl_Parse);
}
}
#Override
public void onPause()
{
super.onPause();
if (mExoPlayer != null)
{
mPlayerPosition = mExoPlayer.getCurrentPosition();
}
if (Util.SDK_INT <= 23)
{
releasePlayer();
}
}
#Override
public void onResume()
{
super.onResume();
if ((Util.SDK_INT <= 23 || mExoPlayer == null))
{
mPlayerPosition = mExoPlayer.getCurrentPosition();
}
}
#Override
public void onStop()
{
super.onStop();
if (Util.SDK_INT > 23 || mExoPlayer != null)
{
mExoPlayer.getCurrentPosition();
}
releasePlayer();
}
/**
* Release ExoPlayer.
*/
private void releasePlayer()
{
if (mExoPlayer != null)
{
mPlayerPosition = mExoPlayer.getCurrentPosition();
mExoPlayer.release();
mExoPlayer = null;
}
}
#Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
//Save the fragment's state here
outState.putParcelableArrayList(STEPS_LIST_INDEX, stepsArrayList);
outState.putLong(KEY_POSITION, mPlayerPosition);
super.onSaveInstanceState(outState);
}
}
Parent Activity:
public class IngredientStepsActivity extends AppCompatActivity implements StepsListFragment.OnStepClickListener
{
private static final String TAG = IngredientStepsActivity.class.getSimpleName();
private Context context;
Recipes recipes;
// Track whether to display a two-pane or single-pane UI
public boolean mTwoPane;
public int stepPosition;
ArrayList<Steps> stepsArrayList;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ingredientsteps);
// Determine if you're creating a two-pane or single-pane display
if (savedInstanceState == null)
{
if (getIntent() != null && getIntent().getExtras() != null)
{
recipes = getIntent().getExtras().getParcelable("Recipes");
if(findViewById(R.id.tablet_detail_layout) != null)
{
// This LinearLayout will only initially exist in the two-pane tablet case
mTwoPane = true;
// Only create new fragments when there is no previously saved state
/*
Add the fragment to its container using a FragmentManager and a Transaction
Send the ingredients array list in Parcelable to the Ingredients Fragment
*/
FragmentManager fragmentManager = getSupportFragmentManager();
Bundle ingredientsBundle = new Bundle();
ingredientsBundle.putParcelable("Recipes", recipes);
//Pass Over the bundle to the Ingredients Fragment
IngredientsFragment ingredientsFragment = new IngredientsFragment();
ingredientsFragment.setArguments(ingredientsBundle);
fragmentManager.beginTransaction().replace(R.id.ingredients_fragment_container, ingredientsFragment).commit();
//Pack Data in a bundle call the bundle "stepsBundle" to differentiate it from the "ingredientsBundle"
Bundle stepsBundle = new Bundle();
stepsBundle.putParcelable("Recipes", recipes);
//Pass Over the bundle to the Steps Fragment
StepsListFragment stepsListFragment = new StepsListFragment();
stepsListFragment.setArguments(stepsBundle);
fragmentManager.beginTransaction().replace(R.id.steps_fragment_container, stepsListFragment).commit();
}
else
{
// We're in single-pane mode and displaying fragments on a phone in separate activities
mTwoPane = false;
FragmentManager fragmentManager = getSupportFragmentManager();
Bundle ingredientsBundle = new Bundle();
ingredientsBundle.putParcelable("Recipes", recipes);
//Pass Over the bundle to the Ingredients Fragment
IngredientsFragment ingredientsFragment = new IngredientsFragment();
ingredientsFragment.setArguments(ingredientsBundle);
fragmentManager.beginTransaction().replace(R.id.ingredients_fragment_container, ingredientsFragment).commit();
//Pack Data in a bundle call the bundle "stepsBundle" to differentiate it from the "ingredientsBundle"
Bundle stepsBundle = new Bundle();
stepsBundle.putParcelable("Recipes", recipes);
//Pass Over the bundle to the Steps Fragment
StepsListFragment stepsListFragment = new StepsListFragment();
stepsListFragment.setArguments(stepsBundle);
fragmentManager.beginTransaction().replace(R.id.steps_fragment_container, stepsListFragment).commit();
}
}
}}
#Override
public void onClick(Steps stepClicked)
{
if (mTwoPane)
{
Bundle stepsVideoBundle = new Bundle();
stepsVideoBundle.putParcelable("Steps", stepClicked);
stepsVideoBundle.putBoolean("TwoPane", mTwoPane);
stepsVideoBundle.putInt("StepPosition", stepPosition);
stepsVideoBundle.putParcelableArrayList("StepsArrayList", stepsArrayList);
VideoFragment videoFragment = new VideoFragment();
videoFragment.setArguments(stepsVideoBundle);
getSupportFragmentManager().beginTransaction().replace(R.id.video_fragment_container, videoFragment).commit();
}
else
{
Log.i("Step: ", stepClicked.getStepShortDescription());
Intent intent = new Intent(IngredientStepsActivity.this, VideoPhoneActivity.class);
intent.putExtra("Steps", stepClicked);
startActivity(intent);
}
}
}

Related

Getting a null pointer exception when trying to pass a boolean via an interface

I am using an interface, as is standard (best?) practice to communicate between a series of fragments. The business logic requires the app to collect some information in fragment n+1 and if the "next" button is tapped then the user goes to fragment n+2. If the "back" button is tapped then the user goes to fragment n. I am also using a nice sliding animation to display the transition from one fragment to the other depending on the direction. I cannot figure out why this is not working and I am getting the null pointer error on this line:
createPlanListener.onCreatePlan(bundle);
Here is the initial fragment Mealplan.class where I trigger the transition. I have left all of the boiler plate code generated by Android Studio as is:
public class MealplanFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private FloatingActionButton createMealplan;
// bunch of variables
private Bundle bundle;
private OnCreatePlanListener createPlanListener;
public MealplanFragment() {
// Required empty public constructor
}
public static MealplanFragment newInstance(String param1, String param2) {
MealplanFragment fragment = new MealplanFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Other code that has nothing to do with the bundle or the listener
// Floating action bar
createMealplan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bundle.putBoolean("direction", true);
createPlanListener.onCreatePlan(bundle);
}
});
return mealplanView;
}
public void onButtonPressed(Bundle bundle) {
if (createPlanListener != null) {
createPlanListener.onCreatePlan(bundle);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
mealplanContext = context;
if (context instanceof OnCreatePlanListener) {
createPlanListener = (OnCreatePlanListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
createPlanListener = null;
}
public interface OnCreatePlanListener {
void onCreatePlan(Bundle bundle);
}
#Override
public void onResume() {
super.onResume();
}
And here is MainActivity.class
public class MainActivity extends AppCompatActivity implements
MealplanFragment.OnCreatePlanListener {
// Non related variables
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// MealplanFragment is the default fragment at onCreate
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, new MealplanFragment(), null).commit();
}
}
#Override
public void onCreatePlan(Bundle bundle) {
if (bundle != null) {
Boolean direction = bundle.getBoolean("direction");
ReceptionFragment fragment = new ReceptionFragment();
openFragment(bundle, fragment, direction);
}
}
private void openFragment(Bundle bundle, Fragment fragment, Boolean direction) {
fragment.setArguments(bundle);
//Starting fragment with animation
if (direction) {
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_right).replace(R.id.frame_container, fragment, null);
fragmentTransaction.commit();
} else {
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_left).replace(R.id.frame_container, fragment, null);
fragmentTransaction.commit();
}
}
}
createMealplan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bundle.putBoolean("direction", true);
createPlanListener.onCreatePlan(bundle);
}
});
This is your click listener. bundle is defined as class variable but never initialized and hence the null pointer exception. I would suggest that you use a local variable -> create a new instance of bundle, add data and then invoke callback. Also, createPlanListener is nullable, so you should add a check for that as well.

Update Data from Broadcast receiver to fragment list view in the background

I'm new to android development, I was making this app that receives messages, onReceive. I want to update those data in the ListView that is in a fragment and the update should happen in the background. Broadcast Receiver is registered globally
#Override
public void onReceive(Context context, Intent intent) {
Hover.initialize(context);
/* IncomingSMSReceiver incomingSMSReceiver = new IncomingSMSReceiver();
incomingSMSReceiver.onReceive(context,intent);*/
String uuid = intent.getStringExtra("response_message");
Log.d(TAG, " " + uuid);
if (intent.hasExtra("transaction_extras")) {
HashMap t_extras = (HashMap) intent.getSerializableExtra("transaction_extras");
/*if (t_extras.containsKey("confirmCode")) {
String confirmationCode = t_extras.get("confirmCode").toString();
Log.d(TAG, " "+confirmationCode);
}*/
if (t_extras.containsKey("Tsh")) {
String balance = t_extras.get("Tsh").toString();
Log.d(TAG," "+balance);
Bundle bundle = new Bundle();
bundle.putString("id", uuid);
bundle.putString("message", balance);
FragmentHistory fragmentHistory = new FragmentHistory();
fragmentHistory.setArguments(bundle);
}
}
}
Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// return inflater.inflate(R.layout.fragment_history, container,false);
View view = inflater.inflate(R.layout.fragment_history, container, false);
/* mRecyclerView =(RecyclerView) view.findViewById(R.id.recyclerView_history);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.setHasFixedSize(true);
configAdapter();*/
dataSaver.initializeDataSaver(getActivity());
// listScore = view.findViewById(R.id.list);
return view;
}
#Override
public void onActivityCreated( Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//dataSaver.setViewList("Hello", "Hola");
dataSaver.getDataList(this.getActivity());
/*try {
Bundle bundle = getActivity().getIntent().getExtras();
dataSaver.setViewList(bundle.getString("id"), bundle.getString("message"));
} catch (Exception e) {
e.printStackTrace();
}*/
}
#Override
public void onResume() {
super.onResume();
dataSaver.getDataList(this.getActivity());
}
#Override
public void onPause() {
super.onPause();
Bundle arguments = getArguments();
if (arguments != null) {
handleArguments(arguments);
}
Bundle extras = getActivity().getIntent().getExtras();
if (extras != null) {
handleExtras(extras);
}
}
#Override
public void onStop() {
super.onStop();
Bundle arguments = getArguments();
if (arguments != null) {
handleArguments(arguments);
}
Bundle extras = getActivity().getIntent().getExtras();
if (extras != null) {
handleExtras(extras);
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
Bundle arguments = getArguments();
if (arguments != null) {
handleArguments(arguments);
}
Bundle extras = getActivity().getIntent().getExtras();
if (extras != null) {
handleExtras(extras);
}
Toast.makeText(getActivity(), "Destroyed", Toast.LENGTH_LONG).show();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Bundle arguments = getArguments();
}
private void handleArguments(Bundle arguments) {
// TODO
try {
String id =arguments.getString("id");
String message = arguments.getString("message");
dataSaver.setViewList(id, message);
} catch (Exception e) {
e.printStackTrace();
}
}
ListView Adapter
private ArrayList<TransDetails> scores;
TransDetails transDetails;
private MySharedPreference sharedPreference;
private ListView listScore;
private HashSet<String> scoreset;
private Gson gson;
public void initializeDataSaver(Activity activity){
transDetails = new TransDetails();
scores = new ArrayList<>();
gson = new Gson();
sharedPreference = new MySharedPreference(activity);
getHighScoreListFromSharedPreference();
}
/*public void setGson(Gson gson) {
this.gson = gson;
}*/
public Gson getGson() {
return gson;
}
/*public void setActivity(Activity activityf){
activityf = getActivity();
}
public Activity getActivity(){
return getActivity();
}*/
public void getHighScoreListFromSharedPreference() {
//retrieve data from shared preference
String jsonScore = sharedPreference.getHighScoreList();
Type type = new TypeToken<List<TransDetails>>(){}.getType();
scores = gson.fromJson(jsonScore, type);
if (scores == null) {
scores = new ArrayList<>();
}
}
public void saveScoreListToSharedpreference(ArrayList<TransDetails> scoresList) {
//convert ArrayList object to String by Gson
String jsonScore = gson.toJson(scoresList);
//save to shared preference
sharedPreference.saveHighScoreList(jsonScore);
}
public void upDateList(final String id, final String message){
transDetails.setId(id);
transDetails.setId(message);
scores.add(0, transDetails);
}
public void setViewList(String trans_id, String trans_amount){
if (trans_id != null) {
transDetails.setId(trans_id);
transDetails.setMessage(trans_amount);
scores.add(0,transDetails); //add to scores list
saveScoreListToSharedpreference(scores);
}
}
public void getDataList(Activity activity){
listScore = activity.findViewById(R.id.list);
if (scores.size() == 0) {
Toast.makeText(activity, "No data in sharedPreferences", Toast.LENGTH_SHORT).show();
} else {
getHighScoreListFromSharedPreference();
//get data
//set adapter for listview and visible it
ListViewAdapter adapter = new ListViewAdapter(activity, scores);
listScore.setAdapter(adapter);
}
}
Fragments can't work standalone and must be in an activity.
so first step is create an Activity and put your fragment in it.
then you must start that activity with an intent into your broadcast receiver. something like that:
context.startActivity(new Intent(this,ListActivity.class));
the other issue is that when new message receive your startActivity will launch again and create repeatedly. for avoid this issue you must add a flag to your Intent in this way:
context.startActivity(new Intent(this,ListActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
this flag is for avoid from recreating activity and bring to front existing one.
in this way the intent and data you passed to that will receive in onNewIntent() method of activity and you can handle your data there.
so instead of setArguments in fragment you must start intent with bundle:
context.startActivity(new Intent(this,ListActivity.class).putExtras(bundle).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));

Multiple Exoplayer instance using fragments

My aim is to show several video at one Activity at the same time using ExoPlayer 2. (I got hls source for each video). I'm succesfully play one video. So I decided to make implementation of the Player inside Fragment and create new Fragment for each hls sources to put them inside Activity. But only one Fragment succesfully playing video, other Fragments looks like black square without any content. How to resolve it?
I'm using ExoPlayer 2.7.2 .
My Activity code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Bundle bundle1 = new Bundle();
bundle1.putString(SmallPlayerfragment.VIDEO_KEY, SmallPlayerfragment.Source1);
Bundle bundle2 = new Bundle();
bundle2.putString(SmallPlayerfragment.VIDEO_KEY, SmallPlayerfragment.Source2);
Fragment fragment1 = new SmallPlayerfragment();
fragment1.setArguments(bundle1);
Fragment fragment2 = new SmallPlayerfragment();
fragment2.setArguments(bundle2);
if (getSupportFragmentManager().findFragmentByTag(SmallPlayerfragment.TAG1) == null
| getSupportFragmentManager().findFragmentByTag(SmallPlayerfragment.TAG2) == null)
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.test_container, fragment2, SmallPlayerfragment.TAG2)
.replace(R.id.bottom_test_container, fragment1, SmallPlayerfragment.TAG1)
.commit();
}
My Fragment code
public class SmallPlayerfragment extends Fragment {
String mVideoURL;
public final static String VIDEO_KEY = "videoKey";
public final static String Source2 = "source2";
public final static String Source1 = "source1";
public final static String TAG1 = "fragment_1";
public final static String TAG2 = "fragment_2";
PlayerView mPlayerView;
SimpleExoPlayer mPlayer;
public SmallPlayerfragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_small_player, container, false);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mPlayerView = getActivity().findViewById(R.id.small_player);
if (getArguments() != null) {
mVideoURL = getArguments().getString(VIDEO_KEY);
} else {
mVideoURL = Source1;
}
}
#Override
public void onStart() {
super.onStart();
Log.d("test", "onStart Fragment");
if (Util.SDK_INT > 23) {
initializePlayer();
}
}
#Override
public void onResume() {
super.onResume();
Log.d("test", "onResume Fragment");
// hideSystemUi();
if ((Util.SDK_INT <= 23 || mPlayer == null)) {
initializePlayer();
}
}
#Override
public void onPause() {
Log.d("test", "onPause Fragment");
super.onPause();
if (Util.SDK_INT <= 23) {
releasePlayer();
}
}
#Override
public void onStop() {
Log.d("test", "onStop Fragment");
super.onStop();
if (Util.SDK_INT > 23) {
releasePlayer();
}
}
#SuppressLint("InlinedApi")
private void hideSystemUi() {
mPlayerView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
private void initializePlayer() {
mPlayer = ExoPlayerFactory.newSimpleInstance(
new DefaultRenderersFactory(getContext()),
new DefaultTrackSelector(), new DefaultLoadControl());
mPlayerView.setPlayer(mPlayer);
mPlayer.seekTo(0);
Uri uri = Uri.parse(mVideoURL);
MediaSource mediaSource = buildMediaSource(uri);
mPlayer.prepare(mediaSource, true, false);
mPlayer.setPlayWhenReady(true);
}
private MediaSource buildMediaSource(Uri uri) {
// Measures bandwidth during playback. Can be null if not required.
DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
// Produces DataSource instances through which media data is loaded.
DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(getContext(),
Util.getUserAgent(getContext(), "yourApplicationName"), bandwidthMeter);
// This is the MediaSource representing the media to be played.
MediaSource videoSource = new HlsMediaSource.Factory(dataSourceFactory)
.createMediaSource(uri);
// Prepare the player with the source.
return videoSource;
}
private void releasePlayer() {
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
I think its just a focus issue. The fragment needs to be in focus to play video.
Also in your Exoplayer fragment drop a little if to check for focus before playing the video.
The fragment in focus should only play the video.

How to make 500 Questions Quiz in android with single activity?

I am creating an android app, where I'll be asking for multiple types of questions using RadioButtons. I don't want to make multiple Activities for these questions. Can anyone please tell me how to do that with a short example, of at least two questions?
You can use multiples fragments... or call the activity itself multiple times...
I did an app like yours and i choose the first method!
This is some fragment of a project that i wrote, and the activity that manipulate it, you will have to change it according to your needs.
Activity
public class CollectActivity extends FragmentActivity {
MyPageAdapter pageAdapter;
NonSwipeableViewPager pager;
SpringIndicator springIndicator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collect);
List<Fragment> fragments = getFragments();
pager = (NonSwipeableViewPager) findViewById(R.id.view_pager);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
PagerModelManager manager = new PagerModelManager();
manager.addCommonFragment(fragments, getTitles());
ModelPagerAdapter adapter = new ModelPagerAdapter(getSupportFragmentManager(), manager);
pager.setAdapter(adapter);
springIndicator = (SpringIndicator) findViewById(R.id.indicator);
springIndicator.setViewPager(pager);
springIndicator.setOnTabClickListener(new TabClickListener() {
#Override
public boolean onTabClick(int position) {
return false;
}
});
}
private List<Fragment> getFragments() {
List<Fragment> fList = new ArrayList<Fragment>();
fList.add(CollectFragment.newInstance("Fragment 1"));
fList.add(CollectFragment.newInstance("Fragment 2"));
fList.add(CollectFragment.newInstance("Fragment 3"));
//add your fragments with a loop
return fList;
}
private List<String> getTitles() {
return Lists.newArrayList("1", "2", "3");
}
public void swipeFragment() {
pager.setCurrentItem(pager.getCurrentItem() + 1);
}
public int getFragment() {
return pager.getCurrentItem();
}
}
Fragment
public class CollectFragment extends Fragment {
private Button openButton;
private Button confirmationCloseButton;
private Button yesRenew;
private Button noRenew;
private BroadcastReceiver udpMessages;
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
public static final CollectFragment newInstance(String message) {
CollectFragment f = new CollectFragment();
Bundle bdl = new Bundle(1);
bdl.putString(EXTRA_MESSAGE, message);
f.setArguments(bdl);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String message = getArguments().getString(EXTRA_MESSAGE);
View v = null;
if (message.compareTo("Fragment 1") == 0) {
v = inflater.inflate(R.layout.fragment_collect_open, container, false);
openButton = (Button) v.findViewById(R.id.open_button);
openButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i2 = new Intent();
i2.setComponent(new ComponentName("qira.com.locker", "qira.com.locker.Service.MessageService"));
i2.putExtra("Message", "CONFIRM_LOCKER_1_CLOSED");
getContext().startService(i2);
}
});
}
if (message.compareTo("Fragment 2") == 0) {
v = inflater.inflate(R.layout.fragment_collect_close, container, false);
confirmationCloseButton = (Button) v.findViewById(R.id.confirmation_close_button);
confirmationCloseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i2 = new Intent();
i2.setComponent(new ComponentName("qira.com.locker", "qira.com.locker.Service.MessageService"));
i2.putExtra("Message", "OPEN_LOCKER_1");
getContext().startService(i2);
}
});
}
if (message.compareTo("Fragment 3") == 0) {
v = inflater.inflate(R.layout.fragment_collect_renew, container, false);
yesRenew = (Button) v.findViewById(R.id.yes_button);
noRenew = (Button) v.findViewById(R.id.no_button);
yesRenew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((CollectActivity) getActivity()).swipeFragment();
}
});
noRenew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getContext(), ReserveActivity.class);
startActivity(i);
}
});
}
return v;
}
#Override
public void onResume() {
super.onResume();
udpMessages = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() != null && intent.getAction().equals("UDP.MESSAGES.COLLECT")) {
if (intent.getExtras().getString("Type").compareTo("OPEN_LOCKER_1-LOCKER_OPENED") == 0) {
if (((CollectActivity) getActivity()).getFragment() != 0) { // onCreateView called twice, dont know why... workaround to solve this problem
((CollectActivity) getActivity()).swipeFragment();
}
}
if (intent.getExtras().getString("Type").compareTo("CONFIRM_LOCKER_1_CLOSED-TRUE") == 0) {
if (((CollectActivity) getActivity()).getFragment() != 1) { // onCreateView called twice, dont know why... workaround to solve this problem
((CollectActivity) getActivity()).swipeFragment();
}
}
}
}
};
getContext().registerReceiver(udpMessages, new IntentFilter("UDP.MESSAGES.COLLECT"));
}
#Override
public void onPause() {
super.onPause();
getContext().unregisterReceiver(udpMessages);
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
}

How to pass value from non_activity to fragment?

I want to pass a value from an Activity to a Fragment but my Activity doesn't have a layout.
I have used a barcode scanner so I want to send scanned data to Fragment class but I am getting a null value error, so please help me out.
public class ScanCasepaperActivity extends AppCompatActivity implements ZBarScannerView.ResultHandler,DiagnosisFragment.OnFragmentInteractionListener {
private ZBarScannerView mScannerView;
private String TAG = ScanCasepaperActivity.class.getName();
private static ScanCasepaperActivity context;
private TextView mCasePaperNo, mDateTime, mpatientName, mgender, mage, mrefBy;
private int CASEPAPERID;
DiagnosisFragment diagnosisFragment;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
// Programmatically initialize the scanner view
mScannerView = new ZBarScannerView(this);
setContentView(mScannerView);
//DiagnosisFragment DiagnosisFragment = new DiagnosisFragment(this);
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
mScannerView.startCamera(); // Start camera on resume
mScannerView.setAutoFocus(true);
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera(); // Stop camera on pause
}
#Override
public void handleResult(Result rawResult) {
Log.e(TAG, "handleResult");
DiagnosisFragment diagnosisFragment = new DiagnosisFragment();
Table_Barcode_Methods barcodeMethods = new Table_Barcode_Methods(getApplicationContext());
// Do something with the result here
long bar = Long.parseLong(rawResult.getContents());
int id = 0;
id = barcodeMethods.ISBarCodeNoAvailable(bar);
int s1 = 0;
s1 = (int) Long.parseLong(String.valueOf(id));
showFragment(s1);
//tableNewCasePaperMethods.getbar(s1);
// DiagnosisFragment.(s1);
// android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
// fragmentManager.beginTransaction().replace(R.id.content1, diagnosisFragment).commit();
// DiagnosisFragment.newInstance(args);
// diagnosisFragment = new DiagnosisFragment();
// DiagnosisFragment.newInstance(s1);
// Bundle bundle = new Bundle();
// bundle.putInt("id",s1);
// diagnosisFragment.setArguments(bundle);
// DiagnosisFragment.UpDateUI(s1);
Log.e(TAG + "barcodescanid", String.valueOf(id));
Log.e(TAG + "Contents", String.valueOf(bar)); // Prints scan results
Intent i1=new Intent(ScanCasepaperActivity.this,HomeActivity.class);
startActivity(i1);
}
}
if you want your activity shows in ScanCasepaperActivity,just add a method in your fragment and call it in your activity. if you wanna show a fragment in HomeActivity,pass your result through Intent or SharedPrefrece.

Categories

Resources