I have been working on an android project. My project has a YoutubePlayer api. The video of EditText's video is taken and the video is shown. the following code works. But when I enter another id in the EditTex, the previous video is not replaced. The previous one looks the same. How can I fix this?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//find views by ID
youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
urlText = (EditText) findViewById(R.id.url);
btnGo = (View) findViewById(R.id.btn_go);
btnGo.setOnClickListener(onClickListener());
}
private YouTubePlayer.OnInitializedListener onInitialization() {
return new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
if (!wasRestored) {
// loadVideo() will auto play video
// Use cueVideo() method, if you don't want to play it automatically
youTubePlayer.loadVideo(urlText.getText().toString().trim());
// Showing player controls with default mode
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Toast.makeText(getApplicationContext(),
"onInitializationFailure()",
Toast.LENGTH_SHORT).show();
}
};
}
private View.OnClickListener onClickListener() {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
// Initializing video player with developer key
youTubeView.initialize(API_KEY, onInitialization());
}
};
}
Don't call initialize() again - once you get your success callback, retain a reference to the YouTubePlayer and use that to load subsequent videos:
private YouTubePlayer player = null;
//...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//find views by ID
youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
urlText = (EditText) findViewById(R.id.url);
btnGo = (View) findViewById(R.id.btn_go);
btnGo.setOnClickListener(onClickListener());
}
private YouTubePlayer.OnInitializedListener onInitialization() {
return new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
if (!wasRestored) {
//Keep doing what you're doing, and when finished...
this.player = youTubePlayer;
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
//...
}
};
}
private View.OnClickListener onClickListener() {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
if(player == null) {
youTubeView.initialize(API_KEY, onInitialization());
} else {
player.loadVideo(urlText.getText().toString().trim());
player.play();
}
}
};
Related
Stories progress class
How can I show all my pictures in arraylist coming from firebase as it is displaying only last picture on storyprogressbar .Arraylist contains all pictures Url.problem is not displaying all images on storiesProgressbar .. please help me sorting out the problem.
Here is my firebase tree from where I am getting data(pictures) enter image description here
DetailStatusActivity
public class DetailStatusActivity extends AppCompatActivity implements StoriesProgressView.StoriesListener {
StoriesProgressView storiesProgressView;
ImageView image;
int counter = 0;
long pressTime = 0L;
long limit = 500L;
public View.OnTouchListener onTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
pressTime = System.currentTimeMillis();
storiesProgressView.pause();
return false;
case MotionEvent.ACTION_UP:
long now = System.currentTimeMillis();
storiesProgressView.resume();
return limit < now - pressTime;
}
return false;
}
};
private String currentUserID;
private DatabaseReference statusRef;
private String visit_id;
private DatabaseReference detailStatusRef;
private ArrayList<String> imagesArray;
private DatabaseReference userRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_detail_status);
image = (ImageView) findViewById(R.id.image);
storiesProgressView = (StoriesProgressView) findViewById(R.id.stories);
visit_id = getIntent().getStringExtra("uid");
Log.d("cominghereId", visit_id);
currentUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
statusRef = FirebaseDatabase.getInstance().getReference().child("Statuses");
userRef = FirebaseDatabase.getInstance().getReference().child("Users");
detailStatusRef = FirebaseDatabase.getInstance().getReference();
View reverse = findViewById(R.id.reverse);
reverse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
storiesProgressView.reverse();
}
});
reverse.setOnTouchListener(onTouchListener);
View skip = findViewById(R.id.skip);
skip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
storiesProgressView.skip();
}
});
skip.setOnTouchListener(onTouchListener);
}
#Override
protected void onStart() {
super.onStart();
imagesArray=new ArrayList<>();
detailStatusRef.child("DetailStatusesImages").child(visit_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
imagesArray.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
DetailStatusModel Dupload = snapshot.getValue(DetailStatusModel.class);
imagesArray.add(Dupload.getImage());
}
Log.d("sizee", String.valueOf(imagesArray.size()));
storiesProgressView.setStoriesCount(imagesArray.size());
storiesProgressView.setStoryDuration(3000L);
storiesProgressView.setStoriesListener(DetailStatusActivity.this);
storiesProgressView.startStories(counter);
Glide.with(getApplicationContext()).load(imagesArray.get(counter)).into(image);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onNext() {
Glide.with(getApplicationContext()).load(imagesArray.get(++counter)).into(image);
Log.d("indexx", imagesArray.get(counter));
}
#Override
public void onPrev() {
if ((counter - 1) < 0) return;
Glide.with(getApplicationContext()).load(imagesArray.get(--counter)).into(image);
}
#Override
public void onComplete() {
finish();
}
#Override
protected void onDestroy() {
storiesProgressView.destroy();
super.onDestroy();
}
#Override
protected void onPause() {
storiesProgressView.pause();
super.onPause();
}
#Override
protected void onResume() {
storiesProgressView.resume();
super.onResume();
}
}
So I've made a MapActivity which shows a MapBox map.
Then I load in all my markers(pins, which are eventually Point objects with longitude and latitude) from the database into a List< Features > markerCoordinates. markerCoordinates is then given through GeoJsonSource().
Now all my markers are displayed on the map.
Now I can't figure out how to make a marker clickable, and when clicked I need to obtain the ID of the marker so I can later on redirect to another Activity and then load in all data based on that ID. This ID of the pin needs to be the same as the ID from the database.
Mapbox Documentation doesn't really helped me out with this problem.
Does any one know how to implement this?
MapActivity.java
public class MapActivity extends AppCompatActivity {
private MapView mapView;
DatabaseHelper myDb;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_moments:
Intent intent = new Intent(MapActivity.this, MapActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
break;
case R.id.navigation_addmoment:
Intent intent2 = new Intent(MapActivity.this, AddMomentActivity.class);
intent2.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent2);
break;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myDb = new DatabaseHelper(this);
Mapbox.getInstance(this, "pk.eyJ1IjoiaGlqYWNrbWFuaWFjIiwiYSI6ImNqdWlyb3E3NzE5bjc0Zm9lOHpta3AzajMifQ.ithKXW2RvhRzlPqXWBexyg");
setContentView(R.layout.activity_map);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(#NonNull MapboxMap mapboxMap) {
mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
// Importing markers from database
List<Feature> markerCoordinates = new ArrayList<>();
loadPins(markerCoordinates);
// Adding markers on the map
style.addSource(new GeoJsonSource("source-id",
FeatureCollection.fromFeatures(markerCoordinates)));
// Some styling below
style.addImage("marker-icon-id",
BitmapFactory.decodeResource(
MapActivity.this.getResources(), R.drawable.mapbox_marker_icon_default));
SymbolLayer symbolLayer = new SymbolLayer("layer-id", "source-id");
symbolLayer.withProperties(
PropertyFactory.iconImage("marker-icon-id")
);
style.addLayer(symbolLayer);
}
});
}
});
}
// Switch from map to moments
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.header_items, menu);
final MenuItem listItem = menu.findItem(R.id.list_menu);
listItem.setVisible(true);
listItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
Intent intent = new Intent(MapActivity.this, MomentsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
return true;
}
});
return true;
}
// Reading the Database, appending each row to allMarkers
public void loadPins(List<Feature> allMarkers) {
Cursor res = myDb.getAllData();
if(res.getCount() == 0) {
// Error message
return;
}
while(res.moveToNext()) {
double longitude = Double.parseDouble(res.getString(4));
double latitude = Double.parseDouble(res.getString(5));
if(longitude == 0 || latitude == 0) {
continue;
} else {
allMarkers.add(Feature.fromGeometry(
Point.fromLngLat(
longitude,
latitude
)
));
}
}
}
#Override
public void onStart() {
super.onStart();
mapView.onStart();
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onStop() {
super.onStop();
mapView.onStop();
}
#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);
}
}
First, you should implement the onMapClick or onMapLongClick methods, so that you can handle all map clicks and retrieve the data you need.
The steps to get the marker Id on every click are roughly these:
Check whether the click was on a marker or elsewhere.
You can do this by querying the source layer (your GeoJsonSource) and checking whether there is a feature nearby the clicked spot.
If a feature was found, get the property you need.
You could use feature.getProperties() to get all the properties or feature.getStringProperty("name_of_the_property") to get a specific one. See more here.
Check this example to see how to implement all of this.
I am using Youtube API for android. Below is the code
MainActivity.java
public class MainActivity extends AppCompatActivity implements YouTubePlayer.OnInitializedListener {
private static final int RECOVERY_REQUEST = 1;
private YouTubePlayerView youTubeView;
private YouTubePlayerFragment youTubePlayerFragment;
private YouTubePlayer player;
private boolean isFullScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
// youTubeView.initialize(Config.YOUTUBE_API_KEY, this);
youTubePlayerFragment = (YouTubePlayerFragment) getFragmentManager()
.findFragmentById(R.id.youtube_fragment);
youTubePlayerFragment.initialize(Config.YOUTUBE_API_KEY, this);
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
this.player = player;
this.player.cueVideo("fhWaJi1Hsfo"); // Plays https://www.youtube.com/watch?v=fhWaJi1Hsfo
// player.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);
player.setOnFullscreenListener(new YouTubePlayer.OnFullscreenListener() {
#Override
public void onFullscreen(boolean b) {
isFullScreen = true;
}
});
}
}
#Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_REQUEST).show();
} else {
String error = String.format(getString(R.string.player_error), errorReason.toString());
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(Config.YOUTUBE_API_KEY, this);
}
}
protected Provider getYouTubePlayerProvider() {
return youTubeView;
}
#Override
public void onBackPressed() {
Toast.makeText(this,"Back pressed",Toast.LENGTH_LONG).show();
if(isFullScreen)
{
player.setFullscreen(false);
}
else
{
super.onBackPressed();
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!--<com.google.android.youtube.player.YouTubePlayerView-->
<!--android:id="#+id/youtube_view"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="wrap_content"/>-->
<fragment
android:id="#+id/youtube_fragment"
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
When the Full Screen is visible and if the user clicked back, I want my Activity to be displayed. Instead what is happening now is the back button exists from the app.
How can I fix this?
UPDATE
I Identified the error, inside the setOnFullScreenListener it was never identified the app is in Full screen, even though it is. I tried forcing the boolean into true, but it ended up crashing saying the player is null
I'm not sure but in your onFullScreen() override method, you have set
isFullScreen = true;
Rather, use
isFullScreen = b;
Hope this helps.
I found the answer, just remove the if condition in onInitializationSuccess. Below is the code.
public class MainActivity extends AppCompatActivity implements YouTubePlayer.OnInitializedListener {
private static final int RECOVERY_REQUEST = 1;
private YouTubePlayerView youTubeView;
private YouTubePlayerFragment youTubePlayerFragment;
private YouTubePlayer player;
private boolean isFullScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
// youTubeView.initialize(Config.YOUTUBE_API_KEY, this);
youTubePlayerFragment = (YouTubePlayerFragment) getFragmentManager()
.findFragmentById(R.id.youtube_fragment);
youTubePlayerFragment.initialize(Config.YOUTUBE_API_KEY, this);
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
this.player = player;
this.player.cueVideo("fhWaJi1Hsfo"); // Plays https://www.youtube.com/watch?v=fhWaJi1Hsfo
// player.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);
this.player.setOnFullscreenListener(new YouTubePlayer.OnFullscreenListener() {
#Override
public void onFullscreen(boolean b) {
isFullScreen = b;
}
});
}
#Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_REQUEST).show();
} else {
String error = String.format(getString(R.string.player_error), errorReason.toString());
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(Config.YOUTUBE_API_KEY, this);
}
}
protected Provider getYouTubePlayerProvider() {
return youTubeView;
}
#Override
public void onBackPressed() {
if(isFullScreen)
{
Toast.makeText(this,"Full Screen",Toast.LENGTH_LONG).show();
player.setFullscreen(false);
}
else
{
Toast.makeText(this,"Not Full Screen",Toast.LENGTH_LONG).show();
super.onBackPressed();
}
}
}
I am making online media player app.. it works very well but I am unable to play next song when I click the next button
PLAYER CLASS
public class Player extends AppCompatActivity {
Intent i;
String sname,sid,spath;
ImageButton play;
Button nxt;
MediaPlayer mp;
ArrayList list;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player);
play = (ImageButton)findViewById(R.id.play_pause);
nxt = (Button) findViewById(R.id.next);
nxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// NO IDEA WHAT TO DO NOW
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp = MediaPlayer.create(Player.this,Uri.parse(spath));
if(mp.isPlaying()){
if(mp!=null){
mp.pause();
// Changing button image to play button
play.setImageResource(R.drawable.uamp_ic_play_arrow_white_48dp);
}
}else{
// Resume song
if(mp!=null){
mp.start();
// Changing button image to pause button
play.setImageResource(R.drawable.uamp_ic_pause_white_48dp);
}
}
}
});
i=getIntent();
sid=i.getStringExtra("sid");
sname=i.getStringExtra("sname");
spath=i.getStringExtra("spath");
}
#Override
public void onBackPressed() {
startActivity(new Intent(Player.this, song_list.class));
finish();
super.onBackPressed();
}
}
SONGLIST CLASS
public class song_list extends AppCompatActivity {
ListView listView;
ArrayList<pojonew> list;
String result,url;
json js;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.song_list);
listView = (ListView)findViewById(R.id.songs);
url="https://heeled-pipe.000webhostapp.com/select.php";
new SongData().execute();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pojonew p=(pojonew)list.get(position);
String sid=p.getId();
String sname=p.getName();
String spath=p.getPath();
Intent i = new Intent(song_list.this,Player.class);
i.putExtra("sid",sid);
i.putExtra("sname",sname);
i.putExtra("spath",spath);
startActivity(i);
}
});
}
SONGDATA CLASS
class SongData extends AsyncTask<Void, Void , Void>
{
#Override
protected Void doInBackground(Void... params) {
js = new json();
list = new ArrayList<>();
result = js.getdatafromurl(url);
Log.d("url",url);
try {
JSONObject jo = new JSONObject(result);
JSONArray ja= jo.getJSONArray("data");
for (int i=0;i<ja.length();i++){
JSONObject jo1 = ja.getJSONObject(i);
pojonew sp = new pojonew();
sp.setId(jo1.getString("id"));
sp.setName(jo1.getString("name"));
sp.setPath(jo1.getString("path"));
list.add(sp);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
custadapter n=new custadapter(list,song_list.this);
listView.setAdapter(n);
}
}
}
on click of the play get the position of list data item
and call the method below
public ModelClass loadNext(String id) {
ModelClass nextAudio = null;
int pos = 1;
for (int index = 0; index < FileList.size(); index++) {
if (ModelClass.get(index).getFileUID().equals(id)) {
pos = index + 1;
break;
}
}
if (pos != AudioFileList.size())
nextAudio = AudioFileList.get(pos);
return nextAudio;
}
load media player has your playing in on click of list view
I have the following class that I instantiate from my fragment:
public class FacebookLogin {
private CallbackManager mCallbackManager;
private LoginButton lButton;
private AccessToken accessToken;
private Profile profile;
private static final String TAG = "FacbookLogin";
public FacebookLogin(Context c) {
FacebookSdk.sdkInitialize(c);
mCallbackManager = CallbackManager.Factory.create();
Log.i(TAG, " Constructor called");
}
private FacebookCallback<LoginResult> mCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.i(TAG, " logged in...");
AccessToken accessToken = loginResult.getAccessToken();
profile = Profile.getCurrentProfile(); //Access the profile who Is the person login i
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
Log.i(TAG, " Error");
Log.e(TAG, e.getMessage());
}
};
public void setCallback(LoginButton lButton) {
lButton = lButton;
lButton.registerCallback(mCallbackManager, mCallback);
Log.i(TAG, " setCallback called");
}
And here Is my fragment-class:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fLogin = new FacebookLogin(getActivity().getApplicationContext());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.login, container, false);
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
final LoginButton loginButton = (LoginButton) getView().findViewById(R.id.login_button);
final TextView infoText = (TextView) getView().findViewById(R.id.text_details);
loginButton.setFragment(this);
loginButton.setReadPermissions("user_friends");
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.i(TAG, " Button clickde");
fLogin.setCallback(loginButton); //Let's register a callback
profile = fLogin.getProfile();
if (profile != null) {
Log.i(TAG, profile.getName()); //Call this after the callback request Is finished
} else {
Log.i(TAG, "NULL....... inside onresume");
}
}
});
}
I want to call profile = fLogin.getProfile(); after the callback request is complete. But I don't know how to do this. I have read about the onComplete();, but I don't know how to Implement It here.