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

Monday, 6 April 2015

Generating HMC SHA1 hash in Java Using a Secret Key (Private Key)


Below is the method :

void generateHMCSHA1(){

int counter= 1;
           String privateKey = "0123456789ABCDEF0123456789ABCDEF";
           byte[] result = null;
           MessageDigest md;
try {
md = MessageDigest.getInstance("SHA-1");
byte[] keyBytes = md.digest(privateKey.getBytes("UTF-8"));

           SecretKey sk = new SecretKeySpec(keyBytes, "HmacSHA1");
           Mac mac = Mac.getInstance("HmacSHA1");
           mac.init(sk);
            result = mac.doFinal(String.valueOf(counter).getBytes("US_ASCII"));

           StringBuilder sb = new StringBuilder();
           for (byte b : result) {
               sb.append(String.format("%02X ", b));
           }
         
           System.out.println("      Key: " + privateKey + "\n");
       
           System.out.println("  Results: " +sb );
         
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}           

}


Output :

Key: 0123456789ABCDEF0123456789ABCDEF
 
Results: 38 92 62 29 80 04 C9 83 EE 87 97 B0 C0 FD 77 4C 69 F3 82 

Saturday, 4 April 2015

Delete Items from Listview By ticking them using a checkbox



1. MainActivity.java

public class MainActivity extends ListActivity  {
EditText addtext;
ListView listview;
ArrayList<String> itemlist = new ArrayList<String>();
ArrayAdapter<String> adapter;

Button add,del;

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

}

private void intiViews(){
add = (Button) findViewById(R.id.btnAdd);
del = (Button) findViewById(R.id.btnDel);
addtext = (EditText) findViewById(R.id.txtItem);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, itemlist);

add.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
itemlist.add(addtext.getText().toString());
addtext.setText("");
adapter.notifyDataSetChanged();

}
});

del.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
SparseBooleanArray res = getListView()
.getCheckedItemPositions();
int itemCount = getListView().getCount();

for (int i = itemCount - 1; i >= 0; i--) {
if (res.get(i)) {
adapter.remove(itemlist.get(i));
}
}
res.clear();
adapter.notifyDataSetChanged();
}

});
setListAdapter(adapter);
}

}

2. activity_main.xml

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

    <EditText
        android:id="@+id/txtItem"
        android:layout_width="240dp"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:hint="Enter Country"
    />

    <Button
        android:id="@+id/btnAdd"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Add"
        android:layout_toRightOf="@id/txtItem"
    />

    <TextView
        android:id="@android:id/empty"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/txtItem"
        android:text="empty"
        android:gravity="center_horizontal"
    />

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/txtItem"
        android:choiceMode="multipleChoice" >
    </ListView>

    <Button
        android:id="@+id/btnDel"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="Delete Selected Items" />
</RelativeLayout>

Output :


Dialog to pick a image From Camera Or Gallery


Mostly we require to get an image from camera or gallery in our apps ,So here how to go about it :-
Tested this code on 5.1 android lolipop works fine hope this helps all :-)

1. CameraActivity.java

public class CameraActivity extends Activity {
Uri outputFileUri;
String selectedImagePath = "";
ImageView mUserImage;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
initiViews();
}

private void initiViews() {

mUserImage = (ImageView) findViewById(R.id.mUserImage);

mUserImage.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {

popmenu();
}
});

}

void popmenu() {
final Dialog dialog = new Dialog(CameraActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.cameradialog);
dialog.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
Button mCamerabtn = (Button) dialog.findViewById(R.id.cameradialogbtn);
Button mGallerybtn = (Button) dialog
.findViewById(R.id.gallerydialogbtn);
Button btnCancel = (Button) dialog.findViewById(R.id.canceldialogbtn);

dialog.getWindow().setLayout(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);

mCamerabtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory(),
"test.jpg");

outputFileUri = Uri.fromFile(file);
Log.d("TAG", "outputFileUri intent" + outputFileUri);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, 0);

dialog.cancel();
}
});

mGallerybtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {

Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 1);
dialog.cancel();
}
});

btnCancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.cancel(); // dismissing the popup
}
});

dialog.show();

}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
Log.d("TAG", "outputFileUri RESULT_OK" + outputFileUri);
if (outputFileUri != null) {

Bitmap bitmap;
bitmap = decodeSampledBitmapFromUri(outputFileUri,
mUserImage.getWidth(), mUserImage.getHeight());

if (bitmap == null) {
Toast.makeText(
getApplicationContext(),
"the image data could not be decoded"
+ outputFileUri.getPath(),
Toast.LENGTH_LONG).show();

} else {
selectedImagePath = getRealPathFromURI(CameraActivity.this,outputFileUri);// outputFileUri.getPath().
Toast.makeText(
getApplicationContext(),
"Decoded Bitmap: " + bitmap.getWidth() + " x "
+ bitmap.getHeight()
+ outputFileUri.getPath(),
Toast.LENGTH_LONG).show();
mUserImage.setImageBitmap(bitmap);
}
}
}
break;
case 1:
if (resultCode == RESULT_OK) {
Uri targetUri = data.getData();
Log.d("TAG", "datae" + targetUri);
Bitmap bitmap;
bitmap = decodeSampledBitmapFromUri(targetUri,
mUserImage.getWidth(), mUserImage.getHeight());

if (bitmap == null) {
Toast.makeText(
getApplicationContext(),
"the image data could not be decoded"
+ targetUri.getPath(), Toast.LENGTH_LONG)
.show();

} else {
selectedImagePath = getPath(targetUri);// targetUri.getPath();
Toast.makeText(
getApplicationContext(),
"Decoded Bitmap: " + bitmap.getWidth() + " x "
+ bitmap.getHeight() + targetUri.getPath(),
Toast.LENGTH_LONG).show();
mUserImage.setImageBitmap(bitmap);
}
}
break;

default:
break;
}
}

public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}

public String getRealPathFromURI(Context context, Uri contentUri) {
   Cursor cursor = null;
   try {

       if("content".equals(contentUri.getScheme())) {
           String[] proj = {MediaStore.Images.Media.DATA};
           cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
           int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
           cursor.moveToFirst();
           return cursor.getString(column_index);
       }
       else{
           return contentUri.getPath();
       }


   } finally {
       if (cursor != null) {
           cursor.close();
       }
   }
}  

public Bitmap decodeSampledBitmapFromUri(Uri uri, int reqWidth,
int reqHeight) {

Bitmap bm = null;

try {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver()
.openInputStream(uri), null, options);

// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);

// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(uri), null, options);
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}

return bm;
}

public int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;

if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
return inSampleSize;
}
}



2. camera.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="vertical" >

    <ImageView
        android:id="@+id/mUserImage"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"
        android:src="@drawable/ic_launcher" />

</LinearLayout>


3. cameradialog.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="wrap_content"
    android:layout_gravity="center"
    android:layout_marginLeft="20dp"
    android:layout_marginRight="20dp"
    android:background="@drawable/roundshape"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="@null"
        android:padding="10dp"
        android:text="Blog Box"
        android:textSize="20sp"
        android:textStyle="bold" />

    <View
        android:layout_width="fill_parent"
        android:layout_height="4dp"
        android:layout_marginLeft="4dp"
        android:background="#000000"
        android:layout_marginRight="4dp" />

    <Button
        android:id="@+id/cameradialogbtn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="4dp"
        android:layout_weight=".3"
        android:background="@null"
        android:padding="5dp"
        android:text="Take a picture from camera"
        android:textSize="18sp" >
    </Button>

    <View
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:layout_marginLeft="4dp"
        android:background="#000000"
        android:layout_marginRight="4dp"
         />

    <Button
        android:id="@+id/gallerydialogbtn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="4dp"
        android:layout_weight=".3"
        android:background="@null"
        android:padding="5dp"
        android:text="Choose from gallery"
        android:textSize="18sp" >
    </Button>

    <View
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:background="#000000"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp" />

    <Button
        android:id="@+id/canceldialogbtn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="4dp"
        android:layout_weight=".3"
        android:background="@null"
        android:padding="5dp"
        android:text="No thanks"
        android:textSize="18sp" >
    </Button>

</LinearLayout>


4. Drawable : roundshape.xml


<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <stroke
        android:width="2dp"
        android:color="#FFFFFF" />

    <corners android:radius="10dp" />

    <gradient
        android:angle="270"
        android:centerColor="#FFFFFF"
        android:endColor="#f9d7f2"
        android:startColor="#f9d7f2" />

</shape>


Output : 








Thursday, 2 April 2015

Android Action Bar


When we are targeting 3.0 or above action bar is included in all activities that use the Theme.Holo theme, which is the default theme when either the targetSdkVersion or minSdkVersion attribute is set to "11" or greater.

<manifest ... >
    <uses-sdk android:minSdkVersion="11" ... />
    ...
</manifest>

Now if we are customizing then parent should be "Theme.Holo".

Action bar support is provided for Android 2.1 and above.Include v7 appcompat library in your project to avail this feature.

Once you have the Support Library integrated with your app project:

Update your activity so that it extends ActionBarActivity.

For example:
public class MainActivity extends ActionBarActivity { ... }

In your manifest file, update either the <application> element or individual <activity> elements to use one of the Theme.AppCompat themes.

For example:
<activity android:theme="@style/Theme.AppCompat.Light" ... >

i.e is very important point.If we are targetting lower versions of android then add v7 appcompat library in your project then also in your style file change theme to :

   <style name="AppTheme" parent="Theme.AppCompat.Light">
        <!-- Customize your theme here. -->
    </style>

Else you will face a crash saying : Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.

Once you done all these things right your done with setting up the actionBar using support library so as to make actionbar work in all versions.below is the Code snippet :

1. MainActivity.java

public class MainActivity extends ActionBarActivity {

    android.support.v7.app.ActionBar mActionBar;

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

2. styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light">
        <!-- Customize your theme here. -->
    </style>

</resources>

3. AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.kamalvaid.actionbardemo" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            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>

4. build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "com.example.kamalvaid.actionbardemo"
        minSdkVersion 8
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.+'  // Support lib for actionbar
}

}

output :



Now showing Action Buttons in the actionbar...

If you are targetting version 11 and above then just write in menu.xml :

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <!-- Search, should appear as action button -->
    <item android:id="@+id/action_search"
          android:icon="@drawable/ic_action_search"
          android:title="@string/action_search"
          android:showAsAction="ifRoom" />
    <!-- Settings, should always be in the overflow -->
    <item android:id="@+id/action_settings"
          android:title="@string/action_settings"
          android:showAsAction="never" />
</menu>

but If you are targetting version less then 11 just write in menu.xml i.e if you are using support library:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:com.example.kamalvaid.actionbardemo="http://schemas.android.com/apk/res-auto"
>

    <item android:id="@+id/action_search"
        android:icon="@android:drawable/sym_action_email"
        android:title="action search"
        com.example.kamalvaid.actionbardemo:showAsAction="ifRoom"  />
    <!-- Settings, should always be in the overflow -->
    <item android:id="@+id/action_settings"
        android:title="@string/action_settings"
        com.example.kamalvaid.actionbardemo:showAsAction="ifRoom" />
</menu>

As android:showAsAction="ifRoom" is only available from 3.0 and above so you've to use your app namespace instead android as done above.

Now show inflate your actionbuttons in the action by overidding below (onCreateOptionsMenu) method :

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

Now handling clicks for action button, We need to overide below function in order to do so (onOptionsItemSelected(MenuItem item)):

 @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        switch (item.getItemId()) {
            case R.id.action_settings:
                openSettings();
                return true;
            case R.id.sym_action_email:
                openEmail();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void openSettings(){
        Toast.makeText(MainActivity.this,"Open Settings here",Toast.LENGTH_LONG).show();
    }

    private void openEmail(){
        Toast.makeText(MainActivity.this,"Open Email here",Toast.LENGTH_LONG).show();
    }


output : 



Below is the full code Snippet for Action ActionButtons :

1. MainActivity.java

public class MainActivity extends ActionBarActivity {

    android.support.v7.app.ActionBar mActionBar;

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

    void setupActionBar(){
        //mActionBar=getSupportActionBar();
       // mActionBar.setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        switch (item.getItemId()) {
            case R.id.action_settings:
                openSettings();
                return true;
            case R.id.sym_action_email:
                openEmail();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void openSettings(){
        Toast.makeText(MainActivity.this,"Open Settings here",Toast.LENGTH_LONG).show();
    }

    private void openEmail(){
        Toast.makeText(MainActivity.this,"Open Email here",Toast.LENGTH_LONG).show();
    }
}

2. strings.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light">
        <!-- Customize your theme here. -->
    </style>
   <!-- <style name="CustomActionBarTheme"
        parent="Theme.AppCompat.Light">
        <item name="android:actionBarStyle">@style/MyActionBar</item>
    </style>

    &lt;!&ndash; ActionBar styles &ndash;&gt;
    <style name="MyActionBar"
        parent="Theme.AppCompat.Light">
        <item name="android:background">@android:color/white</item>
    </style>-->
</resources>


3. menu_main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:com.example.kamalvaid.actionbardemo="http://schemas.android.com/apk/res-auto"
>

    <item android:id="@+id/sym_action_email"
        android:icon="@android:drawable/sym_action_email"
        android:title="action search"
        com.example.kamalvaid.actionbardemo:showAsAction="ifRoom"  />
    <!-- Settings, should always be in the overflow -->
    <item android:id="@+id/action_settings"
        android:title="@string/action_settings"
        com.example.kamalvaid.actionbardemo:showAsAction="ifRoom" />
</menu>


4. 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" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView android:text="@string/hello_world" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>


output : 











References : https://developer.android.com/training/basics/actionbar/setting-up.html



Adding Dynamic Views in Linear Layout


How to add dynamic views in a parent view (Can be linear or relative etc.)


Here are the steps :


1. MainActivity.java

public class MainActivity extends ActionBarActivity {


LinearLayout mDynamicLinearLayout;
LayoutInflater __inflater;
Button mAddRow;

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

private void initiViews() {
mDynamicLinearLayout=(LinearLayout)findViewById(R.id.mDynamicLinearLayout);
mAddRow=(Button)findViewById(R.id.mAddRow);
mAddRow.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
addDynamicViews();
}
});
}

private void addDynamicViews() {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View _itemRow = inflater.inflate(R.layout.dynamic_row, null);
final EditText name=(EditText)_itemRow.findViewById(R.id.name);
final EditText password=(EditText)_itemRow.findViewById(R.id.password);
Button mShow=(Button)_itemRow.findViewById(R.id.mShow);
mShow.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, name.getText().toString()+ "pwd "+password.getText().toString(), Toast.LENGTH_LONG).show();
}
});
mDynamicLinearLayout.addView(_itemRow);
}

}



XML layouts goes here : 


1. activity_main.xml 

<LinearLayout 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"
    android:orientation="vertical" >

    <Button
        android:id="@+id/mAddRow"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Add" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <LinearLayout
            android:id="@+id/mDynamicLinearLayout"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >
        </LinearLayout>
    </ScrollView>

</LinearLayout>


2. dynamic_row.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="vertical" >

    <EditText
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:hint="username" />

    <EditText
        android:id="@+id/password"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:hint="password" />

    <Button
        android:id="@+id/mShow"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Show Values" />

</LinearLayout>


Output :