Play a YouTube Video in Your android app - java

hello there i have created an app for playing Youtube videos i works fine but i want when i click on next button the next videos plays. how i will create an array for it which contain the youtube videos link. i m new to Android programming plz help.
public class TutorialsActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
public static final String DEVELOPER_KEY = "AIzaSyAIeerJ_5ClQHLtIpXtk5DH2S4mZ9lwGKs";
private static final String VIDEO_ID = "eQW4R5gLlUk";
private static final String VIDEO_ID1 = "H2c_x4YWx7I";
private static final int RECOVERY_DIALOG_REQUEST = 1;
YouTubePlayerFragment myYouTubePlayerFragment;
Button btnNext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tutorials);
myYouTubePlayerFragment = (YouTubePlayerFragment)getFragmentManager().findFragmentById(R.id.youtubeplayerfragment);
myYouTubePlayerFragment.initialize(DEVELOPER_KEY, this);
btnNext = (Button) findViewById(R.id.btnNext);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, final YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
player.cueVideo(VIDEO_ID1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_DIALOG_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(DEVELOPER_KEY, this);
}
}
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerView)findViewById(R.id.youtubeplayerfragment);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
}

just i shared my working source of your requirement.
SampleActivity.java
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
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;
import java.util.ArrayList;
import www.ns7.tv.R;
import www.ns7.tv.controller.YoutubeManager;
public class SampleActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener, View.OnClickListener {
private static final String TAG = "YoutubeLiveTvActivity";
private Button mBtnNext;
private YouTubePlayerView mYouTubePlayerView = null;
private YouTubePlayer mLiveTvPlayer = null;
private ArrayList<String> mVideoIdList = new ArrayList<>();
private int mOffset = 0;
private String mCurrentVideoId;
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.sample);
mBtnNext = (Button) findViewById(R.id.btnNext);
mYouTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_view);
mYouTubePlayerView.initialize(YoutubeManager.YOUTUBE_API_KEY, this);
mBtnNext.setOnClickListener(this);
updateVideoIdList();//add all video id in list
updateVideoId();//set current video id to mCurrentVideoId string
}
private void updateVideoId() {
if (mOffset >= mVideoIdList.size())
mOffset = 0;
mCurrentVideoId = mVideoIdList.get(mOffset);
}
private void updateVideoIdList() {
mVideoIdList.clear();
mVideoIdList.add("p0JcLbXfYXA");
mVideoIdList.add("63pKwVE4Uog");
mVideoIdList.add("QJXsurYoJ10");
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
try {
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.MINIMAL);
mLiveTvPlayer = youTubePlayer;
// mLiveTvPlayer.setOnFullscreenListener(YoutubeLiveTvActivity.this);
if (!b) {
mYouTubePlayerView.setVisibility(View.VISIBLE);
youTubePlayer.loadVideo(mCurrentVideoId);
}
} catch (Exception e) {
Log.e(TAG, " error : ", e);
}
}
#Override
protected void onResume() {
super.onResume();
if (mLiveTvPlayer == null) {
mYouTubePlayerView.initialize(YoutubeManager.YOUTUBE_API_KEY, this);
} else {
mLiveTvPlayer.loadVideo(mCurrentVideoId);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
#Override
protected void onDestroy() {
if (mLiveTvPlayer != null) {
mLiveTvPlayer.release();
}
if (mYouTubePlayerView != null) {
mYouTubePlayerView.removeAllViews();
}
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onClick(View view) {
switch (view.getId())
{
case R.id.btnNext:
{
mOffset++;// move the mOffset to next video id
updateVideoId();
mLiveTvPlayer.loadVideo(mCurrentVideoId);//load next video
}
break;
}
}
}
sample.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#android:color/black"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/btnNext"
android:background="#android:color/black"
>
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtube_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
/>
</RelativeLayout>
<Button
android:id="#+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Next"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>
Above code youtube video play at 0 position when you click next button , next video will be play. if list last item reached then it will again move to 0 position.
Output :

Related

Android: Back click exists from app when using YouTube API

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();
}
}
}

Android Studio multiple numbers with spinner selection

So I'm attempting to have a spinner where you select a currency to convert to from GBP, enter a value in GBP and convert to the selected currency from the spinner by pressing a button. The converted value will then appear in the textview below
Here is the following code I have in the Convert activity i'm using, the app is crashing upon trying to switch to this layout from the main menu, however it was working before i tried adding the multiplication code. Thanks in advance.
public class Convert extends AppCompatActivity {
final EditText currency_input = (EditText) findViewById(R.id.editText_currency_input);
final TextView answer = (TextView) findViewById(R.id.textView_convert_to);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.convert);
Spinner spinner_convert_from = (Spinner) findViewById(R.id.spinner_convert_from);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.currency_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_convert_from.setAdapter(adapter);
}
private void USD() {
answer.setText(String.valueOf(Double.valueOf(String.valueOf(currency_input.getText()))*1.2798));
}
private void EUR() {
answer.setText(String.valueOf(Double.valueOf(String.valueOf(currency_input.getText()))*1.14502));
}
private void AUD() {
answer.setText(String.valueOf(Double.valueOf(String.valueOf(currency_input.getText()))*1.71911));
}
private void CAD() {
answer.setText(String.valueOf(Double.valueOf(String.valueOf(currency_input.getText()))*1.7226));
}
private void JPY() {
answer.setText(String.valueOf(Double.valueOf(String.valueOf(currency_input.getText()))*142.482));
}
private void CHF() {
answer.setText(String.valueOf(Double.valueOf(String.valueOf(currency_input.getText()))* 1.24662));
}
private void CNY() {
answer.setText(String.valueOf(Double.valueOf(String.valueOf(currency_input.getText()))* 8.7714));
}
private void KRW() {
answer.setText(String.valueOf(Double.valueOf(String.valueOf(currency_input.getText()))*1430.8));
}
private void SEK() {
answer.setText(String.valueOf(Double.valueOf(String.valueOf(currency_input.getText()))* 11.1187));
}
public class planOnClickListener implements AdapterView.OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int pos,
long id) {
parent.getItemAtPosition(pos);
if (pos == 0) {
USD();
} else if (pos == 1) {
EUR();
} else if (pos == 2) {
AUD();
} else if (pos == 3) {
CAD();
} else if (pos == 4) {
JPY();
} else if (pos == 5) {
CHF();
} else if (pos == 6) {
CNY();
} else if (pos == 7) {
KRW();
} else if (pos == 8) {
SEK();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
}
There are some common errors in your codes. I have updated your code.
Here is the working code:
//Convert.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class Convert extends AppCompatActivity {
EditText currency_input ;
TextView answer;
String input;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.convert);
// Views
currency_input = (EditText) findViewById(R.id.editText_currency_input);
answer = (TextView) findViewById(R.id.textView_convert_to);
// Default value
currency_input.setText("0.0");
Spinner spinner_convert_from = (Spinner) findViewById(R.id.spinner_convert_from);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.currency_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_convert_from.setAdapter(adapter);
// Add item selected listener
spinner_convert_from.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int pos,
long id) {
// Get input text
input = currency_input.getText().toString();
if (pos == 0) {
USD();
} else if (pos == 1) {
EUR();
} else if (pos == 2) {
AUD();
} else if (pos == 3) {
CAD();
} else if (pos == 4) {
JPY();
} else if (pos == 5) {
CHF();
} else if (pos == 6) {
CNY();
} else if (pos == 7) {
KRW();
} else if (pos == 8) {
SEK();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void USD() {
answer.setText(String.valueOf(Double.valueOf(input)*1.2798));
}
private void EUR() {
answer.setText(String.valueOf(Double.valueOf(input)*1.14502));
}
private void AUD() {
answer.setText(String.valueOf(Double.valueOf(input)*1.71911));
}
private void CAD() {
answer.setText(String.valueOf(Double.valueOf(input)*1.7226));
}
private void JPY() {
answer.setText(String.valueOf(Double.valueOf(input)*142.482));
}
private void CHF() {
answer.setText(String.valueOf(Double.valueOf(input)* 1.24662));
}
private void CNY() {
answer.setText(String.valueOf(Double.valueOf(input)* 8.7714));
}
private void KRW() {
answer.setText(String.valueOf(Double.valueOf(input)*1430.8));
}
private void SEK() {
answer.setText(String.valueOf(Double.valueOf(input)* 11.1187));
}
}
Here is your layout XML:
// convert.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_margin="16dp"
tools:context="com.ferdous.stackoverflowanswer.Convert">
<TextView
android:id="#+id/textView_convert_to"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="24dp"/>
<Spinner
android:id="#+id/spinner_convert_from"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp">
</Spinner>
<EditText
android:id="#+id/editText_currency_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"/>
</LinearLayout>
OUTPUT:

How to add admob banner in a fragment view?

I am new to android development and I am confused about how to add admob banner to a fragment activity(I think its calling fragment). I am modifying a source code.
I have a layout file called fragment_ftp.xml and its as below
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:ads="http://schemas.android.com/apk/res-auto">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text=""
android:id="#+id/statusText"
android:layout_above="#+id/startStopButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="99dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text=""
android:id="#+id/ftpAddressText"
android:layout_below="#+id/startStopButton"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/start_ftp"
android:id="#+id/startStopButton"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/primary_red"
android:text=""
android:id="#+id/warningText"
android:layout_above="#+id/startStopButton"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ftp_image"
android:layout_above="#+id/warningText"
android:layout_centerHorizontal="true" />
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
ads:adSize="SMART_BANNER"
ads:adUnitId="#string/banner_home_footer" />
</RelativeLayout>
</RelativeLayout>
I had added the admob banner and in the preview, I can see that. Please check the below screenshot.
But the issues is that, Where should I write the java code for this admob banner. I don't have a corresponding activity for this fragment_ftp.xml.
Searching for fragment_ftp, I could see only a java file as follows.
FTPServerFragment.java
package com.filename.fragments;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
public class FTPServerFragment extends Fragment {
TextView statusText,warningText,ftpAddrText;
Button ftpBtn;
Futils utils = new Futils();
private MainActivity mainActivity;
private View rootView;
private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMan.getActiveNetworkInfo();
if (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI){
warningText.setText("");
}
else{
stopServer();
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
warningText.setText(utils.getString(getContext(),R.string.ftp_no_wifi));
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
};
private BroadcastReceiver ftpReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action == FTPService.ACTION_STARTED) {
statusText.setText(utils.getString(getContext(), R.string.ftp_status_running));
warningText.setText("");
ftpAddrText.setText(getFTPAddressString());
ftpBtn.setText(utils.getString(getContext(),R.string.stop_ftp));
}
else if(action == FTPService.ACTION_FAILEDTOSTART){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
warningText.setText("Oops! Something went wrong");
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
else if(action == FTPService.ACTION_STOPPED){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_ftp,container,false);
// return inflater.inflate(R.layout.article_view, container, false);
statusText =(TextView) rootView.findViewById(R.id.statusText);
warningText = (TextView) rootView.findViewById(R.id.warningText);
ftpAddrText = (TextView) rootView.findViewById(R.id.ftpAddressText);
ftpBtn = (Button) rootView.findViewById(R.id.startStopButton);
SharedPreferences Sp = PreferenceManager.getDefaultSharedPreferences(getContext());
int th = Integer.parseInt(Sp.getString("theme", "0"));
// checking if theme should be set light/dark or automatic
int theme1 = th == 2 ? PreferenceUtils.hourOfDay() : th;
ImageView ftpImage = (ImageView)rootView.findViewById(R.id.ftp_image);
//light theme
if(theme1 == 0){
ftpImage.setImageResource(R.drawable.ic_ftp_light);
}else{
//dark
ftpImage.setImageResource(R.drawable.ic_ftp_dark);
}
ftpBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(!FTPService.isRunning()){
if(FTPService.isConnectedToWifi(getContext()))
startServer();
else
warningText.setText(utils.getString(getContext(),R.string.ftp_no_wifi));
}
else{
stopServer();
}
}
});
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
mainActivity=(MainActivity)getActivity();
mainActivity.setActionBarTitle(utils.getString(getActivity(), R.string.ftp));
mainActivity.floatingActionButton.hideMenuButton(true);
mainActivity.buttonBarFrame.setVisibility(View.GONE);
mainActivity.supportInvalidateOptionsMenu();
}
#Override
public void onDestroy(){
super.onDestroy();
}
private void startServer() {
getContext().sendBroadcast(new Intent(FTPService.ACTION_START_FTPSERVER));
}
private void stopServer() {
getContext().sendBroadcast(new Intent(FTPService.ACTION_STOP_FTPSERVER));
}
#Override
public void onResume(){
super.onResume();
updateStatus();
IntentFilter wifiFilter = new IntentFilter();
wifiFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
getContext().registerReceiver(mWifiReceiver,wifiFilter);
IntentFilter ftpFilter = new IntentFilter();
ftpFilter.addAction(FTPService.ACTION_STARTED);
ftpFilter.addAction(FTPService.ACTION_STOPPED);
ftpFilter.addAction(FTPService.ACTION_FAILEDTOSTART);
getContext().registerReceiver(ftpReceiver,ftpFilter);
}
#Override
public void onPause(){
super.onPause();
getContext().unregisterReceiver(mWifiReceiver);
getContext().unregisterReceiver(ftpReceiver);
}
private void updateStatus(){
if(FTPService.isRunning()){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_running));
ftpBtn.setText(utils.getString(getContext(),R.string.stop_ftp));
ftpAddrText.setText(getFTPAddressString());
}
else{
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
private String getFTPAddressString(){
return "ftp://"+FTPService.getLocalInetAddress(getContext()).getHostAddress()+":"+FTPService.getPort();
}
}
I this the java page where I shall write the admob call?
try and use this code solve the issue
http://www.androidhive.info/2016/02/android-how-to-integrate-google-admob-in-your-app/
your code java has to be added inside onCreateView function in FTPServerFragement like this :
public class FTPServerFragment extends Fragment {
TextView statusText,warningText,ftpAddrText;
Button ftpBtn;
Futils utils = new Futils();
private MainActivity mainActivity;
private View rootView;
private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMan.getActiveNetworkInfo();
if (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI){
warningText.setText("");
}
else{
stopServer();
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
warningText.setText(utils.getString(getContext(),R.string.ftp_no_wifi));
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
};
private BroadcastReceiver ftpReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action == FTPService.ACTION_STARTED) {
statusText.setText(utils.getString(getContext(), R.string.ftp_status_running));
warningText.setText("");
ftpAddrText.setText(getFTPAddressString());
ftpBtn.setText(utils.getString(getContext(),R.string.stop_ftp));
}
else if(action == FTPService.ACTION_FAILEDTOSTART){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
warningText.setText("Oops! Something went wrong");
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
else if(action == FTPService.ACTION_STOPPED){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_ftp,container,false);
// return inflater.inflate(R.layout.article_view, container, false);
statusText =(TextView) rootView.findViewById(R.id.statusText);
warningText = (TextView) rootView.findViewById(R.id.warningText);
ftpAddrText = (TextView) rootView.findViewById(R.id.ftpAddressText);
ftpBtn = (Button) rootView.findViewById(R.id.startStopButton);
//your ads
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = rootView.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
SharedPreferences Sp = PreferenceManager.getDefaultSharedPreferences(getContext());
int th = Integer.parseInt(Sp.getString("theme", "0"));
// checking if theme should be set light/dark or automatic
int theme1 = th == 2 ? PreferenceUtils.hourOfDay() : th;
ImageView ftpImage = (ImageView)rootView.findViewById(R.id.ftp_image);
//light theme
if(theme1 == 0){
ftpImage.setImageResource(R.drawable.ic_ftp_light);
}else{
//dark
ftpImage.setImageResource(R.drawable.ic_ftp_dark);
}
ftpBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(!FTPService.isRunning()){
if(FTPService.isConnectedToWifi(getContext()))
startServer();
else
warningText.setText(utils.getString(getContext(),R.string.ftp_no_wifi));
}
else{
stopServer();
}
}
});
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
mainActivity=(MainActivity)getActivity();
mainActivity.setActionBarTitle(utils.getString(getActivity(), R.string.ftp));
mainActivity.floatingActionButton.hideMenuButton(true);
mainActivity.buttonBarFrame.setVisibility(View.GONE);
mainActivity.supportInvalidateOptionsMenu();
}
#Override
public void onDestroy(){
super.onDestroy();
}
private void startServer() {
getContext().sendBroadcast(new Intent(FTPService.ACTION_START_FTPSERVER));
}
private void stopServer() {
getContext().sendBroadcast(new Intent(FTPService.ACTION_STOP_FTPSERVER));
}
#Override
public void onResume(){
super.onResume();
updateStatus();
IntentFilter wifiFilter = new IntentFilter();
wifiFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
getContext().registerReceiver(mWifiReceiver,wifiFilter);
IntentFilter ftpFilter = new IntentFilter();
ftpFilter.addAction(FTPService.ACTION_STARTED);
ftpFilter.addAction(FTPService.ACTION_STOPPED);
ftpFilter.addAction(FTPService.ACTION_FAILEDTOSTART);
getContext().registerReceiver(ftpReceiver,ftpFilter);
}
#Override
public void onPause(){
super.onPause();
getContext().unregisterReceiver(mWifiReceiver);
getContext().unregisterReceiver(ftpReceiver);
}
private void updateStatus(){
if(FTPService.isRunning()){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_running));
ftpBtn.setText(utils.getString(getContext(),R.string.stop_ftp));
ftpAddrText.setText(getFTPAddressString());
}
else{
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
private String getFTPAddressString(){
return "ftp://"+FTPService.getLocalInetAddress(getContext()).getHostAddress()+":"+FTPService.getPort();
}
}

MainActivity destroys itself between Splash Screen LifeCycle

I have an SplashScreen and a MainActivity, when tha app launchs it displays the Splash Screen (3 secs delay) then the MainActivity, but when I click a BarNotification of mi App (outside of the App) the Splash Screen Displays(3 seconds delay) and the App Crashes, in LogCat he MainActivity Destroys itself between the Splash Screen Intent LifeCycle. (at lines 29,30 logcat)
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/browser"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
splash.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:background="#color/white"
>
<ImageView android:layout_width="wrap_content"
android:contentDescription="splash screen"
android:id="#+id/splash"
android:src="#drawable/splash"
android:layout_height="wrap_content"
android:scaleType="centerInside"/>
</LinearLayout>
Why I'm not able to Launch correctly the App through the Bar Notificaction?
Here is some code:
MainActivity.java
public class MainActivity extends Activity {
private WebView webview;
public MainActivity() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
log.debug("onCreate(): " + savedInstanceState);
MyApplication.startSomeMobileCore(this);
MyApplication.startSomeMobileNotifier(this);
setContentView(R.layout.main);
onNewIntent(getIntent());
}
#Override
protected void onStart() {
log.debug("onStart()");
super.onStart();
}
#Override
protected void onRestart() {
super.onRestart();
this.wasRestarted = true;
}
#Override
protected void onResume() {
super.onResume();
}
protected void onPause() {
super.onPause();
this.receivedIntent = false;
}
protected void onStop() {
super.onStop();
this.receivedIntent = false;
}
public void onDestroy() {
super.onDestroy();
}
#Override
public void onNewIntent(Intent intent) {
log.debug("onNewIntent(): " + intent);
super.onNewIntent(intent);
if(intent == null) {
log.warn("Received null intent, will ignore");
}
if ("OK".equals(authCode)) {
if (intent != null && intent.getData() != null &&
("content".equals(intent.getData().getScheme()) ||
"http".equals(intent.getData().getScheme()))) {
log.debug("intent.getData() :" + intent.getData() + "; intent.getData().getScheme() : " + intent.getData().getScheme());
String requestedPath;
if ("http".equals(intent.getData().getScheme())) {
requestedPath = URLDecoder.decode(intent.getData().toString());
} else {
requestedPath = intent.getData().getPath();
}
showResource(requestedPath);
} else {
log.debug("Intent without data -> go to entry page after splash screen");
showResource(Configuration.properties.getProperty(""));
}
} else {
Intent errorIntent = new Intent(this, ErrorIntent.class);
startActivity(errorIntent);
// finish actual activity
finish();
}
log.debug("Show splash screen");
Intent intentSplash = new Intent(this, SplashIntent.class);
startActivity(intentSplash);
}
void showResource(String resourceToShow) {
webview = (WebView)findViewById(R.id.browser);
webview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
webview.setWebViewClient(new WebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.loadUrl(resourceToShow);
}
}
SplashIntent.java
public class SplashIntent extends Activity {
// Time splash screen should be shown (in ms)
private static final int splashTime = 3000;
static Logger log = Logger.getLogger(SplashIntent.class);
#Override
public void onCreate(final Bundle savedInstanceState) {
log.debug("SplashIntent: onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
log.debug("SplashIntent: killing splash");
finish();
}
}, splashTime);
}
}
logcat
Hope you guys can help me with this... I'm really out of ideas at this point
Try this inside your SplashIntent class
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent mainIntent = new Intent(Splash.this,MainActivity.class);
SplashIntent.this.startActivity(mainIntent);
SplashIntent.this.finish();
},splashTime);

How implement a GIF in my Android app? [duplicate]

This question already has answers here:
Display Animated GIF
(29 answers)
Closed 8 years ago.
Hey I'm new to android programming.
I want to know how I can easily implement a GIF in my Android app.
What I have to do?
I tried this, but I do something wrong. It's not working. >>THIS<<
Basically i am giving you following example which loads image online from some web-site and change it each after some time duration.
public class Gif_First extends Activity {
WebView mWebView;
int i = 0;
CountDownTimer mTimer;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.animation);
mTimer = new CountDownTimer(15000, 1000) {
private String[] myArray = {
"http://i.share.pho.to/09d99399_o.gif",
"http://i.share.pho.to/220dd194_o.gif",
"http://i.share.pho.to/6f3a5ae4_o.gif",
"http://i.share.pho.to/1b264cb7_o.gif",
"http://i.share.pho.to/824b1aab_o.gif",
"http://i.share.pho.to/c6728fb8_o.gif",
"http://i.share.pho.to/5508a2e1_o.gif",
"http://i.share.pho.to/aa64f9a9_o.gif",
"http://i.share.pho.to/d4619e93_o.gif",
"http://i.share.pho.to/2d50de0a_o.gif",
"http://i.share.pho.to/23c030eb_o.gif",
"http://i.share.pho.to/d6e3ccad_o.gif",
"http://i.share.pho.to/eaaeaf88_o.gif",
"http://i.share.pho.to/9708dd88_o.gif",
"http://i.share.pho.to/7f879974_o.gif",
"http://i.share.pho.to/efe8afa3_o.gif",
"http://i.share.pho.to/259954ac_o.gif",
"http://i.share.pho.to/bdbc28f2_o.gif" };
int currentIndex = 0;
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
if (currentIndex < myArray.length) {
mWebView.loadUrl(myArray[currentIndex]);
currentIndex++;
} else {
currentIndex = 0;
if (currentIndex < myArray.length)
mWebView.loadUrl(myArray[currentIndex]);
currentIndex++;
mTimer.start();
}
mTimer.start();
}
// code comment end
};
mTimer.start();
mWebView = (WebView) findViewById(R.id.webviewActionView);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("http://i.share.pho.to/49cf97de_o.gif");
mWebView.setWebViewClient(new WebSliderWebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(mWebView, url);
//Toast.makeText(getApplicationContext(), "Done!",
// Toast.LENGTH_SHORT).show();
}
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
//Toast.makeText(getApplicationContext(),
// "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
private class WebSliderWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
and here is XML File.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/DogView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:orientation="vertical" >
<WebView
android:id="#+id/webviewActionView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
I think all link is dead but you can upload some image over there and change the link and then try.

Categories

Resources