Thursday, 30 April 2015

Difference between Iterator and List Iterator Example

/*
 *    Iterator traverse elements only in one direction i.e forward
 *    ListIterator traverse elements in both directions i.e forward and backward
 *    Using ListIterator we can modify the existing list as well as done in below sample
 */

public class IteratorClass extends Activity
{

ArrayList<String> miteratorList;
Iterator<String> mIterator;
ListIterator<String> mListIterator;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initiViews();
}

private void initiViews()
{
//Initializing the ArrayList
miteratorList=new ArrayList<String>();

//Adding values to the ArrayList
miteratorList.add("A");
miteratorList.add("B");
miteratorList.add("C");
miteratorList.add("D");
miteratorList.add("E");


//method to traverse elements using Iterator here
usingIterator();

//Initializing the mListIterator here
mListIterator=miteratorList.listIterator();

//method to traverse and modify elements using mListIterator here
usingListIterator();

//method to traverse elements using Iterator here
usingIterator();

usingListIteratorTOTraverseBackward();

}


private void usingIterator()
{
//Initializing the mIterator here
mIterator=miteratorList.iterator();//Returns an iterator on the elements of this list.
while(mIterator.hasNext())
{
Object element = mIterator.next();
System.out.print(element + " ");
}

//O/P goes like this => 04-29 18:32:44.590: I/System.out(26302): A B C D E

System.out.println();
}


private void usingListIterator()
{
//Modifying the existing list using list iterator
while (mListIterator.hasNext()) {
Object element=mListIterator.next();
mListIterator.set(element+"Z");  
}

System.out.println();

//04-29 18:45:44.588: I/System.out(1605): AZ BZ CZ DZ EZ

}


private void usingListIteratorTOTraverseBackward()
{
// Now, display the list in reverse order using ListIterator
     while(mListIterator.hasPrevious()) {
        Object element = mListIterator.previous();
        System.out.print(element + " ");
      }
      System.out.println();
     
          // 04-29 18:52:30.478: I/System.out(5954): EZ DZ CZ BZ AZ

}

}

Wednesday, 22 April 2015

Clearing/Deleting Webview's Web Storage in Android

Sometimes our webview load's previously loaded url when we are saving cookies and maintaining cache etc.now what happens is webview maintains web storage for these loaded pages.In order to load new url everytime we've to clear/delete this web storage.

Now in order to do this we've to write this code :


WebStorage webStorage = WebStorage.getInstance();

webStorage.deleteAllData();

wvAppWebView.reload();  
 
 wvAppWebView.loadUrl(URL);

Monday, 20 April 2015

Login Via Instagram and getting user profile info Android

Generally we get an requirement to login via instagram in our android app. So how to do the i'm going to describe here :


Download and include instagramlib.jar in libs

Follow the code and you are done :

1. MainActivity.java

public class MainActivity extends Activity {
private InstagramApp mApp;
private Button btnConnect,btnshowpofile;
private TextView tvSummary;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.instagram_main);
mApp = new InstagramApp(this, ApplicationData.CLIENT_ID,
ApplicationData.CLIENT_SECRET, ApplicationData.CALLBACK_URL);
mApp.setListener(listener);
tvSummary = (TextView) findViewById(R.id.tvSummary);
btnConnect = (Button) findViewById(R.id.btnConnect);
btnshowpofile = (Button) findViewById(R.id.btnshowpofile);
btnshowpofile.setOnClickListener(new OnClickListener() 
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
openInstagram(MainActivity.this, mApp.getUserName());
}
}); 
btnConnect.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) 
{
if (mApp.hasAccessToken()) {
final AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setMessage("Disconnect from Instagram?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog, int id) {
mApp.resetAccessToken();
btnConnect.setText("Connect");
tvSummary.setText("Not connected");
}
}).setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog, int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
} 
else 
{
mApp.authorize();
}
}
});
if (mApp.hasAccessToken()) 
{
tvSummary.setText("Connected as " + mApp.getUserName());
btnConnect.setText("Disconnect");
}
}

OAuthAuthenticationListener listener = new OAuthAuthenticationListener() {
@Override
public void onSuccess() {
tvSummary.setText("Connected as " + mApp.getUserName());
btnConnect.setText("Disconnect");
}
@Override
public void onFail(String error) {
Toast.makeText(MainActivity.this, error, Toast.LENGTH_SHORT).show();
}
};
private void openInstagram(Context con,String mUserName) {
 try {
  Intent iIntent = getPackageManager().getLaunchIntentForPackage("com.instagram.android");
  iIntent.setData(Uri.parse("instagram://user?username="+mUserName));   
  con.startActivity(iIntent);
 } 
catch (Exception e) {
  con.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://instagram.com/"+mUserName)));
}
}
}

Note : get your scerets keys from instagram developer when Registering your app.

2. Instragramkeys.java

public class Instragramkeys{
public static final String CLIENT_ID = "your client id here";
public static final String CLIENT_SECRET = "your client secret id here";
public static final String CALLBACK_URL = "instagram://connect";
}

XML Layout:

1. instagram_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btnConnect"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="40dip"
        android:text="Connect" />

    <Button
        android:id="@+id/btnshowpofile"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="40dip"
        android:text="showprofile" />

    <TextView
        android:id="@+id/tvSummary"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dip"
        android:layout_marginLeft="15dip"
        android:layout_marginTop="5dp"
        android:text="Not connected" />

</LinearLayout>



2. mainifestfile

  <uses-permission android:name="android.permission.INTERNET" />

output Screens :







Sunday, 19 April 2015

Post a Picture using Facebook sdk 4.01 Android

Use this Method to post Image on facebook using facebook 4.01 SDK. To login follow previous tutorials.



private void postPhoto() {

        Bitmap image = BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_launcher);

        SharePhoto sharePhoto = new SharePhoto.Builder().setBitmap(image).build(); // oR SharePhoto sharePhoto = new SharePhoto.Builder().setImageUrl("path").build();

        ArrayList<SharePhoto> photos = new ArrayList<>();

        photos.add(sharePhoto);

        SharePhotoContent sharePhotoContent =

                new SharePhotoContent.Builder().setRef("Testing picture post").setPhotos(photos).build();

            ShareApi.share(sharePhotoContent, shareCallback);

       

    }

Thursday, 16 April 2015

Posting a status update on Facebook using 4.01


  •   Declare these variables 
  private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
  private CallbackManager callbackManager;
  private ShareDialog shareDialog;
  •  initialize callbackmanager
        callbackManager = CallbackManager.Factory.create();
  •  Now Call this method to share content on facebook (including text,url etc)
private void postStatusUpdate() {       
        ShareLinkContent linkContent = new ShareLinkContent.Builder()
                .setContentTitle("Hello Facebook")
                .setContentDescription(
                        "The 'Hello Facebook' sample  showcases simple Facebook integration")
                .setContentUrl(Uri.parse("http://developers.facebook.com/docs/android"))
                .build();
        ShareApi.share(linkContent, shareCallback);
       }

Facebook Login with Facebook 4.01 SDK Released recently



There are many changes in new sdk release by facebook for app integration.New Facebook sdk has simplified many things from older versions.

So what we have to do to integrate facebook in our app with new sdk follows :

Download the facebook sdk from this link :

Include latest Facebook sdk in your workspace.Some libraries you may have to include in order to make sdk run.that will be ;

1. android-support-v4.jar
2. bolts-android-1.1.2.jar (this can be found from older sdk libs folder).

clean the imported sdk and all set now.
now create your android project and include facebook sdk in your project and finally your project structure will go like this :



now from code side .

1. MainActivity.java

public class MainActivity extends ActionBarActivity {
Button mFacebookloginbtn;
private CallbackManager callbackManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initiViews();
}
private void initiViews() {
mFacebookloginbtn=(Button)findViewById(R.id.Facebookloginbtn);

FacebookSdk.sdkInitialize(MainActivity.this.getApplicationContext());
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,new FacebookCallback() {
@Override
public void onSuccess(LoginResult loginResult) {
Log.e("loginresult", loginResult.toString());
if(Profile.getCurrentProfile()!=null){
Log.e("Pofile",Profile.getCurrentProfile().getName()+Profile.getCurrentProfile().getFirstName()+Profile.getCurrentProfile().getLastName()+Profile.getCurrentProfile().getId()); 
}else{
Profile.fetchProfileForCurrentAccessToken();
Log.e("Pofile",Profile.getCurrentProfile().getName()+Profile.getCurrentProfile().getFirstName()+Profile.getCurrentProfile().getLastName()+Profile.getCurrentProfile().getId());
}
}
@Override
public void onCancel() {
}
@Override
public void onError(FacebookException exception) {
}
});
mFacebookloginbtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
LoginManager.getInstance().logInWithReadPermissions(MainActivity.this,Arrays.asList("public_profile", "user_friends"));
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
1. activity_main.xml


Output Screen :








Things to be noticed here are :


1.LoginManager.getInstance().logInWithReadPermissions(MainActivity.this,
Arrays.asList("public_profile", "user_friends")); 

this lone will make us start with login in facebook.

Define your app permissions here read,write,publish etc.


2. FacebookSdk.sdkInitialize(MainActivity.this.getApplicationContext());

This line will initialize our facebook sdk and Initialize our
sdk for our app.


3. You have to implement a callback named LoginManager in
order to get the login response here . Which goes like this :


LoginManager.getInstance().registerCallback(callbackManager,new
FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult
loginResult) {
}
}

@Override 
public void onCancel() {

}
@Override 
public void onError(FacebookException
exception) {
}
});

Here you have to pass a CallbackManager interface which can be
initialize like this : 

private CallbackManager callbackManager;
callbackManager =CallbackManager.Factory.create();


4. Now if we want some info regarding user then we can get like
this on login success callback :

if(Profile.getCurrentProfile()!=null){
Log.e("Profile<><><>",
Profile.getCurrentProfile().getName()+Profile.getCurrentProfile().getFirstName()+Profile.getCurrentProfile().getLastName()+Profile.getCurrentProfile().getId());
}else{
Profile.fetchProfileForCurrentAccessToken();
Log.e("Profile<><><>",
Profile.getCurrentProfile().getName()+Profile.getCurrentProfile().getFirstName()+Profile.getCurrentProfile().getLastName()+Profile.getCurrentProfile().getId());
}

Here we have to use Profile class define in facebook sdk to fetch the
information.

5. Resultcode inside onActivityResult after login success will
be : 64206

Which can be used if we've to handle multiple conditions inside
onActivityResult 




Cheers!!!







Wednesday, 15 April 2015

Webview content coming small in 5+ android versions as compared to lower versions

Issue Faced when changing target version from 17 to 21

hi guys today i was working on a issue which was : Content (i.e images,text etc loaded from a url) inside the webview was coming small and Same content was coming of bigger size in Lower versions (Android Version <= 4.4).As there are some changes made in the latest webview this was the reason.

I added following properties to my webview and My Problem was solved.

wvWebView.setInitialScale(1);

wvWebView.getSettings().setLoadWithOverviewMode(true);

wvWebView.getSettings().setUseWideViewPort(true);




Before






After










hope this help others as well.

Happy coding!!
Cheers!!

Tuesday, 14 April 2015

Generating KEY HASH programmactically for Signed android app

Put this code in your splash class or in Lanucher class before making the app signed.And after install the app and your signed key hash will be printed, which can be checked in logcat.

 
  try {

      PackageInfo info = getPackageManager().getPackageInfo("YOURPACKAGENAME", PackageManager.GET_SIGNATURES);

      for (Signature signature : info.signatures) {

      MessageDigest md = MessageDigest.getInstance("SHA");

      md.update(signature.toByteArray());

      String hashCode = Base64.encodeToString(md.digest(), Base64.DEFAULT);

      System.out.println("hashKey for Facebook :"+hashCode);

      Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));

      }

      } catch (NameNotFoundException e) {
  

      } catch (NoSuchAlgorithmException e) {

    
      }

      

Adding Transalation to Android app.

Google play store automatically translates the app name and info according to country selected in the device.So we generally need not to add translations. But if we want to add our own translations for specfic languages then we can do that.

In order to do that click on the "Add translation" tab in the developer console inside the Store listing.
Then follow these screen shots and you are done with your custom translation for different selected languages.


1. Select Manage Translation and click on add your own translation :





2.Select the languages you want to add translations for :


3.Select the language you want add translation for and fill the required details :




For more details visit the below link :
https://support.google.com/googleplay/android-developer/answer/113469?hl=en

Monday, 13 April 2015

IDTech Unimag Card Swiper on Android Demo

We will be Getting Name,Card number and expiry date from the card using IDTech Unimag Card Swiper.Here we will be initializing the card swiper inside oncreate, So when activity starts card reader is ready to accept the card.Attached your IDTech card reader to device and run the below code.Swipe the card when activity is visible.

Download the IDT_UniMagSDKAndroid_v4.4.jar from below link and place in your libs folder :

http://spsrprofessionals.com/ClientSite/readers/DMPointOfSale/dMPointOfSale/libs/


1. CardReaderActivity.java

public class CardReaderActivity extends Activity implements uniMagReaderMsg {

private uniMagReader myUniMagReader = null;
private TextView tvCardData;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
// initialize class object
if (myUniMagReader == null)
myUniMagReader = new uniMagReader(this, this);
// initilize view id.
initView();
// init asyntask to read card value.
// new InitCardReader().execute();
new Thread() {
public void run() {
myUniMagReader.setSaveLogEnable(false);
myUniMagReader.setXMLFileNameWithPath(null);
myUniMagReader.loadingConfigurationXMLFile(true);
// myUniMagReader.setVerboseLoggingEnable(true);
myUniMagReader.registerListen();
myUniMagReader.startSwipeCard();
}
}.start();
}

/**
* This method getting all widget id from xml and initialize view by theirT
* ids.
*
* @return void
* **/

private void initView() {
tvCardData = (TextView) findViewById(R.id.tv_swip);
//btnSwipe = (Button) findViewById(R.id.btn_swipe);
//myUniMagReader.startSwipeCard();
}

@Override
public void onDestroy() {
myUniMagReader.stopSwipeCard();
myUniMagReader.unregisterListen();
myUniMagReader.release();
super.onDestroy();
}

@Override
public boolean getUserGrant(int arg0, String arg1) {
Log.d("asd", "getUserGrant -- " + arg1);
return true;
}

@Override
public void onReceiveMsgAutoConfigProgress(int arg0) {
// TODO Auto-generated method stub
Log.d("asd", "onReceiveMsgAutoConfigProgress");
}

@Override
public void onReceiveMsgCardData(byte arg0, byte[] arg1) {
Log.d("asd", "onReceiveMsgCardData");
Log.d("asd", "Successful swipe!");

String strData = new String(arg1);
Log.d("asd", "SWIPE - " + strData);
if (myUniMagReader.isSwipeCardRunning()) {
myUniMagReader.stopSwipeCard();
}
// Match the data we want.
String pattern = "%B(\\d+)\\^([^\\^]+)\\^(\\d{4})";
Log.d("asd", pattern);
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(strData);
String card = "";
String name = "";
String exp = "";
String data = "";
if (m.find()) {
for (int a = 0; a < m.groupCount(); ++a) {
Log.d("asd", a + " - " + m.group(a));
}
card = m.group(1);
name = m.group(2);
exp = m.group(3);
data = "Name:" + name + "\nCard:" + card + "\nExpire:" + exp;
Log.d("asd", data);
tvCardData.setText("Card Data: \n" + data);
displayMsgAndReset(null);
} else {
displayMsgAndReset(null);
}

}

@Override
public void onReceiveMsgCommandResult(int arg0, byte[] arg1) {
Log.d("asd", "onReceiveMsgCommandResult.....");
}

@Override
public void onReceiveMsgConnected() {
Log.d("asd", "onReceiveMsgConnected");
Log.d("asd", "Card reader is connected.");
displayMsgAndReset("Device connected...");
}

@Override
public void onReceiveMsgDisconnected() {
Log.d("asd", "onReceiveMsgDisconnected");
if (myUniMagReader.isSwipeCardRunning()) {
myUniMagReader.stopSwipeCard();
}
//myUniMagReader.release();
displayMsgAndReset("Device disconnected...");

}

@Override
public void onReceiveMsgFailureInfo(int arg0, String arg1) {
Log.d("asd", "onReceiveMsgFailureInfo -- " + arg1);
}

@Override
public void onReceiveMsgSDCardDFailed(String arg0) {
Log.d("asd", "onReceiveMsgSDCardDFailed -- " + arg0);
}

@Override
public void onReceiveMsgTimeout(String arg0) {

displayMsgAndReset(null);
}

@Override
public void onReceiveMsgToConnect() {
Log.d("asd", "Swiper Powered Up");
}

@Override
public void onReceiveMsgToSwipeCard() {
Log.d("asd", "onReceiveMsgToSwipeCard");
// displayAlert("Swip card");

}

@Override
public void onReceiveMsgAutoConfigCompleted(StructConfigParameters arg0) {
Log.d("asd", "onReceiveMsgAutoConfigCompleted");
}

@Override
public void onReceiveMsgAutoConfigProgress(int arg0, double arg1,
String arg2) {
// TODO Auto-generated method stub

}

@Override
public void onReceiveMsgProcessingCardData() {
// TODO Auto-generated method stub

}

@Override
public void onReceiveMsgToCalibrateReader() {
// TODO Auto-generated method stub

}

/**
* This method will show alert
* ***/
private void displayMsgAndReset(String msg) {
myUniMagReader.startSwipeCard();
if(msg!=null)
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();

}

}

2. activity_splash.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:gravity="center"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv_swip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="@string/app_name"
        android:textColor="@color/black"
        android:textSize="20sp"
        android:textStyle="bold" />

</LinearLayout>

3. manifest.xml permission

 <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
 <uses-permission android:name="android.permission.RECORD_AUDIO"/>
 <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Making Soap Web Service call in Android

Before Starting we need to take care of these for parameters

1. NAMESPACE
2. SOAP_ACTION
3. URL
4. METHOD_NAME

Fill these values correctly.You can get these values by hitting your url in browser as shown in below image :





SOAP_ACTION = NAMESPACE+MTHOD_NAME (always)

URL will be your web service url. 

Now the java code in android to get the result from the soap service:

1. MainActivity.java

public class MainActivity extends ActionBarActivity {



@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

 new BackTask().execute();

}



class BackTask extends AsyncTask<Void, Void, Void>{



@Override

protected Void doInBackground(Void... params) {

WebserviceCall com = new WebserviceCall();

          //Call Webservice class method and pass values and get response

          String mResponse = com.getSoapResponse("Login");  

          Log.i("Output", "----"+mResponse);

return null;

}

}



}




2. WebserviceCall.java

public class  WebserviceCall {

/**

 * Variable Declaration................

 *

 */

String namespace = "http://tempuri.org/";

private String url = "your URL Here";

String SOAP_ACTION;

SoapObject request = null, objMessages = null;

SoapSerializationEnvelope envelope;

AndroidHttpTransport androidHttpTransport;


public String getSoapResponse(String MethodName)

{

try {
SOAP_ACTION = namespace + MethodName;

//Adding values to request object

request = new SoapObject(namespace, MethodName);


//Adding String value to request object (User name in this case)

PropertyInfo mUsername =new PropertyInfo();

mUsername.setName("UserName");

mUsername.setValue("kamal@gmail.Com");

mUsername.setType(String.class);

request.addProperty(mUsername);


//Adding String value to request object (password in this case)

PropertyInfo mPassword =new PropertyInfo();

mPassword.setName("Password");

mPassword.setValue("122");

mPassword.setType(String.class);

request.addProperty(mPassword);



// Creating SOAP envelope          

envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

//You can comment that line if your web service is not .NET one.

envelope.dotNet = true;

envelope.setOutputSoapObject(request);

androidHttpTransport = new AndroidHttpTransport(url);

androidHttpTransport.debug = true;//need to be set true if it is a .net service

//SOAP calling webservice

androidHttpTransport.call(SOAP_ACTION, envelope);//making the soap call here

// Web service response

String result = envelope.getResponse().toString();//getting the service response here

return result;

}

catch (Exception e) {

// TODO: handle exception

return e.toString();


}

}

}


3. Define internet permission in manifest file :

   <uses-permission android:name="android.permission.INTERNET"/>

Friday, 10 April 2015

Internet Check in android app

Most of the times we have to check for the internet connection in our android app.So thats how we do in android :

Android provided a class named ConnectivityManager which helps for checking the internet availability.Using this we can check for the internet as well as can get the type of connectiona available i.e wifi,mobile etc.

And here the code for it :


void checkInternet()
{
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = connectivityManager .getActiveNetworkInfo();
if(activeNetwork!=null && activeNetwork.isConnected()){
Log.e("State<><><>", activeNetwork.getState().toString()+"");
Log.e("activeNetwork", activeNetwork.getTypeName()+"");
}else{
Toast.makeText(getApplicationContext(), "Not Connected to internet", Toast.LENGTH_LONG).show();
}
}

Define these permissions in the manifest file :


<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />



How to save String,integer etc preferences in android

Android provides below storage options to store our data.We just have to choose depending on our requrirement.

1. Shared Preferences : to store data corresponding to particular keys. Data can be int,string,boolen etc.

2. Internal Storage : to store data in internal storage can be images,videos,text files etc.

3. External Storage : same as internal can be use to stored above data.

4. SQLite Databases : Sqlite is a mobile database in android which allows us to store data as we do in web but on small scale.

5. Network Connection : we can use web services to store data on web servers.

Here i will providing code for storing our small scale data in preferences via methods.We just have to pass the keys and values to store and keys to fetch those stored values.


1. For Storing Integer values : 

public static void saveIntSharePrefs(Context mContext,int Position,String key)
  {
SharedPreferences pref = mContext.getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
editor.putInt(key,Position);
editor.commit();
}

2. For Fetching Integer values :

public static int getSaveIntSharePrefs(Context mContext,String key)
{
SharedPreferences pref = mContext.getSharedPreferences("MyPref", 0); // 0 - for private mode
return pref.getInt(key, 0);
}

3. For Storing String values : 

public static void saveStringSharePrefs(Context mContext,String value,String key)
{
SharedPreferences pref = mContext.getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
editor.putString(key,value);
editor.commit();
}

4. For Fetching String values :

public static String getSaveStringSharePrefs(Context mContext,String key)
{
SharedPreferences pref = mContext.getSharedPreferences("MyPref", 0); // 0 - for private mode
return pref.getString(key, "");
}


5.For Storing Boolean values : 

public static void saveBooleanSharePrefs(Context mContext,Boolean value,String key)
{
SharedPreferences pref = mContext.getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
editor.putBoolean(key,value);
editor.commit();
}

6. For Fetching Boolean values :

public static Boolean getSaveBooleanSharePrefs(Context mContext,String key)
{
SharedPreferences pref = mContext.getSharedPreferences("MyPref", 0); // 0 - for private mode
return pref.getBoolean(key, false);
}



Cheers!!
happy Coding!!

Tuesday, 7 April 2015

Updating a listview (notifydatasetchange) using an interface when adapter is not in same class or package.




Struture goes like this :



1. MainActivity.this


public class MainActivity extends Activity implements Callback{

ListView mListview;

ArrayList<String>mItems;

ListviewAdapter mAdapter;



@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

intiview();

}



private void intiview() {

mListview=(ListView)findViewById(R.id.mListview);

//preparing list for items here

mItems=new ArrayList<String>();

for(int i=0;i<15;i++){

mItems.add(""+i);

}

mAdapter=new ListviewAdapter(mItems, MainActivity.this);

mListview.setAdapter(mAdapter);

}



@Override

public void onDeleteClick() {

mAdapter.notifyDataSetChanged();

}





}





2. ListviewAdapter.this

public class ListviewAdapter extends BaseAdapter {



ArrayList<String> mItems;

Context mContext;

Callback mCallback;



public ListviewAdapter(ArrayList<String> mItems, Context mContext) {

this.mContext = mContext;

this.mItems = mItems;

mCallback=(Callback) mContext;

}



@Override

public int getCount() {

return mItems.size();

}



@Override

public Object getItem(int position) {

return null;

}



@Override

public long getItemId(int position) {

return 0;

}



@SuppressLint("InflateParams")

@Override

public View getView(final int position, View convertView, ViewGroup parent) {

View mView = convertView;

ViewHolder mHolder; // to reference the child views for later actions

if (mView == null) {

LayoutInflater mInflater = (LayoutInflater) mContext

     .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

mView = mInflater.inflate(R.layout.row_listview, null);

// cache view fields into the holder

mHolder = new ViewHolder();

mHolder.mName = (TextView) mView.findViewById(R.id.name);

mHolder.mDeletebtn = (Button) mView.findViewById(R.id.delbtn);

// associate the holder with the view for later lookup

mView.setTag(mHolder);

} else {

// view already exists, get the holder instance from the view

mHolder = (ViewHolder) mView.getTag();

}



mHolder.mName.setText(mItems.get(position));

mHolder.mDeletebtn.setOnClickListener(new OnClickListener() {



@Override

public void onClick(View v) {

     mItems.remove(position);

    mCallback.onDeleteClick();

}

});

;

return mView;

}



static class ViewHolder {

TextView mName;

Button mDeletebtn;

}



}





3.   Callback.java

public interface Callback {



void onDeleteClick();

}





XML Layouts :

1. 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" >



    <ListView

        android:id="@+id/mListview"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content" >

    </ListView>



</RelativeLayout>



2. row_listview.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="horizontal" >



    <TextView

        android:id="@+id/name"

        android:layout_width="0dp"

        android:layout_height="wrap_content"

        android:layout_weight=".6"

        android:padding="10dp"

        android:text="Name" />



    <Button

        android:id="@+id/delbtn"

        android:layout_width="0dp"

        android:layout_height="wrap_content"

        android:layout_weight=".4"

        android:padding="10dp"

        android:text="Delete Item" />



</LinearLayout>





Output :








Playing Age Restricted youtube videos using YOUTUBE IFRAME API

In this tutorial we will be playing a youtube video using youtube iframe api.I Recently faced this problem in one of my live project.(Tested in Android 4+ and 5+ versions)

So here we will be creating a html page placed in assets folder then displaying that page in the webview. Also to play video full screen i've made bit of adjustments in the div tag of html content.
Since android webview isnt fully javascript enabled in lower versions then 5.0 so using 3rd party customized webview here named videoenabledwebview.

Also android web interface is been implemented here. Android clicks interact with javascript methods in order to play and pause youtube videos.

1. YoutubeActivity.java

public class YoutubeActivity extends ActionBarActivity {

private VideoEnabledWebView webView;

private VideoEnabledWebChromeClient webChromeClient;

Button btn, pause;

InputStream is;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_example);

webView = (VideoEnabledWebView) findViewById(R.id.webView);

View nonVideoLayout = findViewById(R.id.nonVideoLayout);

ViewGroup videoLayout = (ViewGroup) findViewById(R.id.videoLayout);

 WebSettings ws = webView.getSettings();

    ws.setJavaScriptEnabled(true);

    ws.setAllowFileAccess(true);

    if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.ECLAIR) {

        try {

          WebSettings.class.getMethod("setLightTouchEnabled", new Class[]{Boolean.TYPE});

            Log.d("Enabling HTML5-Features", "Enabling HTML5-Features");

            Method m1 = WebSettings.class.getMethod("setDomStorageEnabled", new Class[]{Boolean.TYPE});

            m1.invoke(ws, Boolean.TRUE);



            Method m2 = WebSettings.class.getMethod("setDatabaseEnabled", new Class[]{Boolean.TYPE});

            m2.invoke(ws, Boolean.TRUE);



            Method m3 = WebSettings.class.getMethod("setDatabasePath", new Class[]{String.class});

            m3.invoke(ws, "/data/data/" + getPackageName() + "/databases/");



            Method m4 = WebSettings.class.getMethod("setAppCacheMaxSize", new Class[]{Long.TYPE});

            m4.invoke(ws, 1024*1024*8);



            Method m5 = WebSettings.class.getMethod("setAppCachePath", new Class[]{String.class});

            m5.invoke(ws, "/data/data/" + getPackageName() + "/cache/");



            Method m6 = WebSettings.class.getMethod("setAppCacheEnabled", new Class[]{Boolean.TYPE});

            m6.invoke(ws, Boolean.TRUE);



            Log.d("Enabled HTML5-Features", "Enabled HTML5-Features");

        }

        catch (NoSuchMethodException e) {

            Log.e("Enabled HTML5-Features", "Reflection fail", e);

        }

        catch (InvocationTargetException e) {

            Log.e("Enabled HTML5-Features", "Reflection fail", e);

        }

        catch (IllegalAccessException e) {

            Log.e("Enabled HTML5-Features", "Reflection fail", e);

        }

webView.getSettings().setPluginState(PluginState.ON);

webView.getSettings().setJavaScriptEnabled(true);

View loadingView = getLayoutInflater().inflate(

R.layout.view_loading_video, null);

webChromeClient = new VideoEnabledWebChromeClient(nonVideoLayout,

videoLayout, loadingView, webView)

{

@Override

public void onProgressChanged(WebView view, int progress) {



}

};

webChromeClient

.setOnToggledFullscreen(new VideoEnabledWebChromeClient.ToggledFullscreenCallback() {

@SuppressLint("NewApi")

@Override

public void toggledFullscreen(boolean fullscreen) {

if (fullscreen) {

WindowManager.LayoutParams attrs = getWindow()

.getAttributes();

attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;

attrs.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;

getWindow().setAttributes(attrs);

if (android.os.Build.VERSION.SDK_INT >= 14) {

getWindow()

.getDecorView()

.setSystemUiVisibility(

View.SYSTEM_UI_FLAG_LOW_PROFILE);

}

} else {

WindowManager.LayoutParams attrs = getWindow()

.getAttributes();

attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;

attrs.flags &= ~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;

getWindow().setAttributes(attrs);

if (android.os.Build.VERSION.SDK_INT >= 14) {

getWindow().getDecorView()

.setSystemUiVisibility(

View.SYSTEM_UI_FLAG_VISIBLE);

}

}

}

});

webView.addJavascriptInterface(new WebAppInterface(this), "Android");

webView.setWebChromeClient(webChromeClient);

webView.setWebViewClient(new WebViewClient() {

public void onPageFinished(WebView view, String url) {

new Handler().postDelayed(new Runnable() {

@Override

public void run() {

//webView.loadUrl("javascript:playVideo()");

}

}, 3000);



}

});

btn = (Button) findViewById(R.id.btn);

btn.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

webView.loadUrl("javascript:playVideo()");

}

});

pause = (Button) findViewById(R.id.pause);

pause.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

webView.loadUrl("javascript:pauseVideo()");

}

});

try {



webView.loadUrl("file:///android_asset/example.html");

} catch (IOException e) {

e.printStackTrace();

}

    }

}



public static String convertStreamToString(InputStream is)

throws IOException {

Writer writer = new StringWriter();

char[] buffer = new char[2048];

try {

Reader reader = new BufferedReader(new InputStreamReader(is,

"UTF-8"));

int n;

while ((n = reader.read(buffer)) != -1) {

writer.write(buffer, 0, n);

}

} finally {

is.close();

}

String text = writer.toString();

return text;

}



@Override

public void onBackPressed() {

// Notify the VideoEnabledWebChromeClient, and handle it ourselves if it

// doesn't handle it

if (!webChromeClient.onBackPressed()) {

if (webView.canGoBack()) {

webView.goBack();

} else {

// Standard back button implementation (for example this could

// close the app)

super.onBackPressed();

}

}

}





}





2. VideoEnabledWebChromeClient.java


public class VideoEnabledWebChromeClient extends WebChromeClient implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener

{

    public interface ToggledFullscreenCallback

    {

        public void toggledFullscreen(boolean fullscreen);

    }



    private View activityNonVideoView;

    private ViewGroup activityVideoView;

    private View loadingView;

    private VideoEnabledWebView webView;



    private boolean isVideoFullscreen; // Indicates if the video is being displayed using a custom view (typically full-screen)

    private FrameLayout videoViewContainer;

    private CustomViewCallback videoViewCallback;



    private ToggledFullscreenCallback toggledFullscreenCallback;



    /**

     * Never use this constructor alone.

     * This constructor allows this class to be defined as an inline inner class in which the user can override methods

     */

    @SuppressWarnings("unused")

    public VideoEnabledWebChromeClient()

    {

    }



    /**

     * Builds a video enabled WebChromeClient.

     * @param activityNonVideoView A View in the activity's layout that contains every other view that should be hidden when the video goes full-screen.

     * @param activityVideoView A ViewGroup in the activity's layout that will display the video. Typically you would like this to fill the whole layout.

     */

    @SuppressWarnings("unused")

    public VideoEnabledWebChromeClient(View activityNonVideoView, ViewGroup activityVideoView)

    {

        this.activityNonVideoView = activityNonVideoView;

        this.activityVideoView = activityVideoView;

        this.loadingView = null;

        this.webView = null;

        this.isVideoFullscreen = false;

    }



    /**

     * Builds a video enabled WebChromeClient.

     * @param activityNonVideoView A View in the activity's layout that contains every other view that should be hidden when the video goes full-screen.

     * @param activityVideoView A ViewGroup in the activity's layout that will display the video. Typically you would like this to fill the whole layout.

     * @param loadingView A View to be shown while the video is loading (typically only used in API level <11). Must be already inflated and not attached to a parent view.

     */

    @SuppressWarnings("unused")

    public VideoEnabledWebChromeClient(View activityNonVideoView, ViewGroup activityVideoView, View loadingView)

    {

        this.activityNonVideoView = activityNonVideoView;

        this.activityVideoView = activityVideoView;

        this.loadingView = loadingView;

        this.webView = null;

        this.isVideoFullscreen = false;

    }



    /**

     * Builds a video enabled WebChromeClient.

     * @param activityNonVideoView A View in the activity's layout that contains every other view that should be hidden when the video goes full-screen.

     * @param activityVideoView A ViewGroup in the activity's layout that will display the video. Typically you would like this to fill the whole layout.

     * @param loadingView A View to be shown while the video is loading (typically only used in API level <11). Must be already inflated and not attached to a parent view.

     * @param webView The owner VideoEnabledWebView. Passing it will enable the VideoEnabledWebChromeClient to detect the HTML5 video ended event and exit full-screen.

     * Note: The web page must only contain one video tag in order for the HTML5 video ended event to work. This could be improved if needed (see Javascript code).

     */

    @SuppressWarnings("unused")

    public VideoEnabledWebChromeClient(View activityNonVideoView, ViewGroup activityVideoView, View loadingView, VideoEnabledWebView webView)

    {

        this.activityNonVideoView = activityNonVideoView;

        this.activityVideoView = activityVideoView;

        this.loadingView = loadingView;

        this.webView = webView;

        this.isVideoFullscreen = false;

    }



    /**

     * Indicates if the video is being displayed using a custom view (typically full-screen)

     * @return true it the video is being displayed using a custom view (typically full-screen)

     */

    public boolean isVideoFullscreen()

    {

        return isVideoFullscreen;

    }



    /**

     * Set a callback that will be fired when the video starts or finishes displaying using a custom view (typically full-screen)

     * @param callback A VideoEnabledWebChromeClient.ToggledFullscreenCallback callback

     */

    @SuppressWarnings("unused")

    public void setOnToggledFullscreen(ToggledFullscreenCallback callback)

    {

        this.toggledFullscreenCallback = callback;

    }



    @Override

    public void onShowCustomView(View view, CustomViewCallback callback)

    {

        if (view instanceof FrameLayout)

        {

            // A video wants to be shown

            FrameLayout frameLayout = (FrameLayout) view;

            View focusedChild = frameLayout.getFocusedChild();



            // Save video related variables

            this.isVideoFullscreen = true;

            this.videoViewContainer = frameLayout;

            this.videoViewCallback = callback;



            // Hide the non-video view, add the video view, and show it

            activityNonVideoView.setVisibility(View.INVISIBLE);

            activityVideoView.addView(videoViewContainer, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

            activityVideoView.setVisibility(View.VISIBLE);



            if (focusedChild instanceof android.widget.VideoView)

            {

                // android.widget.VideoView (typically API level <11)

                android.widget.VideoView videoView = (android.widget.VideoView) focusedChild;



                // Handle all the required events

                videoView.setOnPreparedListener(this);

                videoView.setOnCompletionListener(this);

                videoView.setOnErrorListener(this);

            }

            else

            {

                // Other classes, including:

                // - android.webkit.HTML5VideoFullScreen$VideoSurfaceView, which inherits from android.view.SurfaceView (typically API level 11-18)

                // - android.webkit.HTML5VideoFullScreen$VideoTextureView, which inherits from android.view.TextureView (typically API level 11-18)

                // - com.android.org.chromium.content.browser.ContentVideoView$VideoSurfaceView, which inherits from android.view.SurfaceView (typically API level 19+)



                // Handle HTML5 video ended event only if the class is a SurfaceView

                // Test case: TextureView of Sony Xperia T API level 16 doesn't work fullscreen when loading the javascript below

                if (webView != null && webView.getSettings().getJavaScriptEnabled() && focusedChild instanceof SurfaceView)

                {

                    // Run javascript code that detects the video end and notifies the Javascript interface

                    String js = "javascript:";

                    js += "var _ytrp_html5_video_last;";

                    js += "var _ytrp_html5_video = document.getElementsByTagName('video')[0];";

                    js += "if (_ytrp_html5_video != undefined && _ytrp_html5_video != _ytrp_html5_video_last) {";

                    {

                        js += "_ytrp_html5_video_last = _ytrp_html5_video;";

                        js += "function _ytrp_html5_video_ended() {";

                        {

                            js += "_VideoEnabledWebView.notifyVideoEnd();"; // Must match Javascript interface name and method of VideoEnableWebView

                        }

                        js += "}";

                        js += "_ytrp_html5_video.addEventListener('ended', _ytrp_html5_video_ended);";

                    }

                    js += "}";

                    webView.loadUrl(js);

                }

            }



            // Notify full-screen change

            if (toggledFullscreenCallback != null)

            {

                toggledFullscreenCallback.toggledFullscreen(true);

            }

        }

    }



    @Override @SuppressWarnings("deprecation")

    public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) // Available in API level 14+, deprecated in API level 18+

    {

        onShowCustomView(view, callback);

    }



    @Override

    public void onHideCustomView()

    {

        // This method should be manually called on video end in all cases because it's not always called automatically.

        // This method must be manually called on back key press (from this class' onBackPressed() method).



        if (isVideoFullscreen)

        {

            // Hide the video view, remove it, and show the non-video view

            activityVideoView.setVisibility(View.INVISIBLE);

            activityVideoView.removeView(videoViewContainer);

            activityNonVideoView.setVisibility(View.VISIBLE);



            // Call back (only in API level <19, because in API level 19+ with chromium webview it crashes)

            if (videoViewCallback != null && !videoViewCallback.getClass().getName().contains(".chromium."))

            {

                videoViewCallback.onCustomViewHidden();

            }



            // Reset video related variables

            isVideoFullscreen = false;

            videoViewContainer = null;

            videoViewCallback = null;



            // Notify full-screen change

            if (toggledFullscreenCallback != null)

            {

                toggledFullscreenCallback.toggledFullscreen(false);

            }

        }

    }



    @Override

    public View getVideoLoadingProgressView() // Video will start loading

    {

        if (loadingView != null)

        {

            loadingView.setVisibility(View.VISIBLE);

            return loadingView;

        }

        else

        {

            return super.getVideoLoadingProgressView();

        }

    }



    @Override

    public void onPrepared(MediaPlayer mp) // Video will start playing, only called in the case of android.widget.VideoView (typically API level <11)

    {

        if (loadingView != null)

        {

            loadingView.setVisibility(View.GONE);

        }

    }



    @Override

    public void onCompletion(MediaPlayer mp) // Video finished playing, only called in the case of android.widget.VideoView (typically API level <11)

    {

        onHideCustomView();

    }



    @Override

    public boolean onError(MediaPlayer mp, int what, int extra) // Error while playing video, only called in the case of android.widget.VideoView (typically API level <11)

    {

        return false; // By returning false, onCompletion() will be called

    }



    /**

     * Notifies the class that the back key has been pressed by the user.

     * This must be called from the Activity's onBackPressed(), and if it returns false, the activity itself should handle it. Otherwise don't do anything.

     * @return Returns true if the event was handled, and false if was not (video view is not visible)

     */

    @SuppressWarnings("unused")

    public boolean onBackPressed()

    {

        if (isVideoFullscreen)

        {

            onHideCustomView();

            return true;

        }

        else

        {

            return false;

        }

    }



}



3. VideoEnabledWebView.java

public class VideoEnabledWebView extends WebView

{

    public class JavascriptInterface

    {

        @android.webkit.JavascriptInterface @SuppressWarnings("unused")

        public void notifyVideoEnd() // Must match Javascript interface method of VideoEnabledWebChromeClient

        {

            Log.d("___", "GOT IT");

            // This code is not executed in the UI thread, so we must force that to happen

            new Handler(Looper.getMainLooper()).post(new Runnable()

            {

                @Override

                public void run()

                {

                    if (videoEnabledWebChromeClient != null)

                    {

                        videoEnabledWebChromeClient.onHideCustomView();

                    }

                }

            });

        }

    }



    private VideoEnabledWebChromeClient videoEnabledWebChromeClient;

    private boolean addedJavascriptInterface;



    @SuppressWarnings("unused")

    public VideoEnabledWebView(Context context)

    {

        super(context);

        addedJavascriptInterface = false;

    }



    @SuppressWarnings("unused")

    public VideoEnabledWebView(Context context, AttributeSet attrs)

    {

        super(context, attrs);

        addedJavascriptInterface = false;

    }



    @SuppressWarnings("unused")

    public VideoEnabledWebView(Context context, AttributeSet attrs, int defStyle)

    {

        super(context, attrs, defStyle);

        addedJavascriptInterface = false;

    }



    /**

     * Indicates if the video is being displayed using a custom view (typically full-screen)

     * @return true it the video is being displayed using a custom view (typically full-screen)

     */

    @SuppressWarnings("unused")

    public boolean isVideoFullscreen()

    {

        return videoEnabledWebChromeClient != null && videoEnabledWebChromeClient.isVideoFullscreen();

    }



    /**

     * Pass only a VideoEnabledWebChromeClient instance.

     */

    @Override @SuppressLint("SetJavaScriptEnabled")

    public void setWebChromeClient(WebChromeClient client)

    {

        getSettings().setJavaScriptEnabled(true);



        if (client instanceof VideoEnabledWebChromeClient)

        {

            this.videoEnabledWebChromeClient = (VideoEnabledWebChromeClient) client;

        }



        super.setWebChromeClient(client);

    }



    @Override

    public void loadData(String data, String mimeType, String encoding)

    {

        addJavascriptInterface();

        super.loadData(data, mimeType, encoding);

    }



    @Override

    public void loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String historyUrl)

    {

        addJavascriptInterface();

        super.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl);

    }



    @Override

    public void loadUrl(String url)

    {

        addJavascriptInterface();

        super.loadUrl(url);

    }



    @Override

    public void loadUrl(String url, Map<String, String> additionalHttpHeaders)

    {

        addJavascriptInterface();

        super.loadUrl(url, additionalHttpHeaders);

    }



    private void addJavascriptInterface()

    {

        if (!addedJavascriptInterface)

        {

            // Add javascript interface to be called when the video ends (must be done before page load)

            //noinspection all

            addJavascriptInterface(new JavascriptInterface(), "_VideoEnabledWebView"); // Must match Javascript interface name of VideoEnabledWebChromeClient



            addedJavascriptInterface = true;

        }

    }



}





XML Layouts Goes Here :


1. activity_example.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=".YoutubeActivity" >



    <Button

        android:id="@+id/btn"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_centerHorizontal="true"

        android:text="Play" />



    <Button

        android:id="@+id/pause"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_toRightOf="@+id/btn"

        android:text="Pause" />

    <!-- View that will be hidden when video goes fullscreen -->



    <RelativeLayout

        android:id="@+id/nonVideoLayout"

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:layout_below="@+id/btn" >



        <com.example.androidyoutube.VideoEnabledWebView

            android:id="@+id/webView"

            android:layout_width="match_parent"

            android:layout_height="match_parent" />

    </RelativeLayout>



    <!-- View where the video will be shown when video goes fullscreen -->



    <RelativeLayout

        android:id="@+id/videoLayout"

        android:layout_width="match_parent"

        android:layout_height="match_parent" >



             <View

            android:id="@+id/videoLoading"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_centerInParent="true"

            android:visibility="invisible" />

        -->



    </RelativeLayout>



</RelativeLayout>



2. custom_screen.xml

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android">

    <FrameLayout android:id="@+id/fullscreen_custom_content"

        android:visibility="gone"

        android:background="@color/black"

        android:layout_width="match_parent"

        android:layout_height="match_parent"

    />

    <LinearLayout android:orientation="vertical"

        android:layout_width="match_parent"

        android:layout_height="match_parent">



        <LinearLayout android:id="@+id/error_console"

            android:orientation="vertical"

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

        />



        <FrameLayout android:id="@+id/main_content"

            android:layout_width="match_parent"

            android:layout_height="match_parent"

        />

    </LinearLayout>

</FrameLayout>



3. video_loading_progress.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

         android:id="@+id/progress_indicator"

         android:orientation="vertical"

         android:layout_centerInParent="true"

         android:layout_width="wrap_content"

         android:layout_height="wrap_content">



       <ProgressBar android:id="@android:id/progress"

           style="?android:attr/progressBarStyleLarge"

           android:layout_gravity="center"

           android:layout_width="wrap_content"

           android:layout_height="wrap_content" />



       <TextView android:paddingTop="5dip"

           android:layout_width="wrap_content"

           android:layout_height="wrap_content"

           android:layout_gravity="center"

           android:text="loading_video" android:textSize="14sp"

           android:textColor="?android:attr/textColorPrimary" />

 </LinearLayout>



 4.view_loading_video.xml

 <RelativeLayout

    xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:background="#000000" >



    <LinearLayout

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:orientation="vertical"

        android:layout_centerInParent="true" >



        <ProgressBar

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_gravity="center"

            android:indeterminate="true"

            style="?android:attr/progressBarStyleLarge" />



        <TextView

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_marginTop="8dp"

            android:layout_marginBottom="24dp"

            android:textAppearance="?android:attr/textAppearanceMedium"

            android:textColor="#a3a3a3"

            android:text="loading" />



    </LinearLayout>



</RelativeLayout>




5. AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.androidyoutube"

    android:versionCode="1"

    android:versionName="1.0" >



    <uses-sdk

        android:minSdkVersion="11"

        android:targetSdkVersion="21" />

<uses-permission android:name="android.permission.INTERNET" />

    <application

        android:allowBackup="true"

        android:icon="@drawable/ic_launcher"

        android:hardwareAccelerated="true"

        android:label="@string/app_name"

        android:theme="@style/AppTheme" >

        <activity

            android:name=".YoutubeActivity"

            android:screenOrientation="landscape"

            android:label="@string/app_name" >

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />



                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>



</manifest>






HTML FILE PLACED IN ASSETS FOLDER

1.  example.html

<!DOCTYPE html>

<html>



<head>

<head>

  <meta charset="utf-8" />

  <title> Fullscreen Div </title>

  <style>

  .overlay {

    position: fixed;

    width: 100%;

    height: 100%;

    left: 0;

    top: 0;

    background: rgba(51,51,51,0.7);

    z-index: 10;

  }

  </style>

</head>

  <body>

 

    <!-- 1. The <iframe> (and video player) will replace this <div> tag. -->

    <div id="player" class='overlay'></div>



    <script async="true">

var mUrl="";



 var tag = document.createElement('script');



      tag.src = "https://www.youtube.com/iframe_api";

      var firstScriptTag = document.getElementsByTagName('script')[0];

      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);



      // 3. This function creates an <iframe> (and YouTube player)

      //    after the API code downloads.

      var player;

    function showAndroidToast(toast) {

      mUrl=toast;

//onYouTubeIframeAPIReady();

    }

  function showAndroidToastTwo(toast) {

        Android.showToast(toast);

mUrl=toast;

//$("#ytplayer").pauseVideo();

 //document.getElementById('ytplayer').src="http://www.youtube.com/embed/Bm_vnhCpH_M";

 //player.pauseVideo();

    // document.getElementById('ytplayer').pauseVideo();

 //stopVideo();

  player.playVideo();

 // document.getElementById("ytplayer").innerHTML = 'pauseVideo()';

}

 function playVideo() {

   

  player.playVideo();



}

 function pauseVideo() {

   

  player.pauseVideo();



}



 function getcurrentduration() {

   

  player.getcurrentduration();



}

      // 2. This code loads the IFrame Player API code asynchronously. //'Bm_vnhCpH_M', , 'controls': 0

    

      function onYouTubeIframeAPIReady() {

        player = new YT.Player('player', {

          videoId:'SEZbZK4jFLY',         

   playerVars: { 'autoplay': 1},

          events: {

            'onReady': onPlayerReady,

            'onStateChange': onPlayerStateChange

          }

        });

      }



      // 4. The API will call this function when the video player is ready.

      function onPlayerReady(event) {

        //event.target.playVideo();



      }



      // 5. The API calls this function when the player's state changes.

      //    The function indicates that when playing a video (state=1),

      //    the player should play for six seconds and then stop.

      var done = false;

      function onPlayerStateChange(event) {

        if (event.data == YT.PlayerState.PLAYING && !done) {

          //setTimeout(stopVideo, 6000);

          done = true;

        }

      }

      function stopVideo() {

        player.stopVideo();

      }

    </script>

  </body>

</html>





Output :







References for VideoEnableWebView:  https://github.com/cprcrack/VideoEnabledWebView