Thursday, 2 April 2015

Android Material Light (android:Theme.Material.Light) Tutorial


Android L comes with alots of enhancements, One of them is Material design. Now we no longer need to depend on resources for handling action bar designs and all.Without talking much i should share new material designs concept which works with Android L.
   

Structure for values folders goes like this here : 





    Follow these steps and give a new look to your app :
 

1. Inside values-v21 folder in Resources : 

 styles.xml : 


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

    <style name="AppTheme" parent="android:Theme.Material.Light">
        <item name="android:colorPrimary">@color/primary</item>
        <item name="android:colorPrimaryDark">@color/primary_dark</item>
        <item name="android:colorAccent">@color/accent</item>
        <item name="android:textColorPrimary">@color/text_primary</item>
        <item name="android:textColor">@color/text_secondary</item>
        <item name="android:navigationBarColor">@color/primary_dark</item>
        <item name="android:windowBackground">@color/window_background</item>
    </style>
</resources>


2. Inside values folder :

 styles.xml : Define colors as you need

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

    <color name="primary">#673ab7</color>
    <color name="primary_dark">#512da8</color>
    <color name="accent">#ffc400</color>
    <color name="text_primary">#D9FFFFFF</color>
    <color name="text_secondary">#D9000000</color>
    <color name="window_background">#ff0000</color>

</resources>


Define your java Class with xml layout with full functionalities.

To play with material designs you just need to work on these two files.
 I've included style in values-v21 as support is not available for lower sdk's as it throws an error  which say android:Theme.Material.Light requires API 21.


Output  With Color Clarifications here :







 
    

RecyclerView with CardView


Now if we want a Card type listview and we can simply use RecyclerView with cardview.
CardView is another addon in lolipop which make listing fab.

In order to implement simply follow my Last tutorial for RecyclerView and Add these new Code content there and you are done with CardView.



1. row_recyclerview.xml

<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    card_view:cardCornerRadius="10dp"
    android:layout_margin="5dp">

   <RelativeLayout
    android:layout_width="match_parent"
       android:layout_margin="5dp"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/title"
        android:padding="5dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_red_dark"
        android:text="contact det"
        android:gravity="center_vertical"
        android:textColor="@android:color/white"
        android:textSize="14dp"/>

    <TextView
        android:id="@+id/txtName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Name"
        android:gravity="center_vertical"
        android:textSize="10dp"
        android:layout_below="@id/title"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="5dp"/>

    <TextView
        android:id="@+id/txtSurname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Surname"
        android:gravity="center_vertical"
        android:textSize="10dp"
        android:layout_below="@id/txtName"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="5dp"/>

    <TextView
        android:id="@+id/txtEmail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Email"
        android:textSize="10dp"
        android:layout_marginTop="10dp"
        android:layout_alignParentRight="true"
        android:layout_marginRight="150dp"
        android:layout_alignBaseline="@id/txtName"/>

</RelativeLayout>

   </android.support.v7.widget.CardView>




2. RecyclerViewViewHolder.java

public class RecyclerViewViewHolder extends RecyclerView.ViewHolder {

    public TextView txtView;

    public RecyclerViewViewHolder(View itemView) {
        super(itemView);
        txtView = (TextView) itemView.findViewById(R.id.title);
    }
}



3. RecyclerViewAdapter.java

public class RecyclerViewViewHolder extends RecyclerView.ViewHolder {

    public TextView txtView;

    public RecyclerViewViewHolder(View itemView) {
        super(itemView);
        txtView = (TextView) itemView.findViewById(R.id.title);
    }
}




4. build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.example.kamalvaid.recyclerview"
        minSdkVersion 14
        targetSdkVersion 21
        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:21.0.0'
    compile 'com.android.support:recyclerview-v7:21.0.0'
    compile 'com.android.support:cardview-v7:21.+'
}



Output : 


RecyclerView Tutorial


Using RecyclerView, we have to be mind about two important aspects i.e
   
    1. RecyclerView.ViewHolder
    2. RecyclerView.Adapter
 

  My DemoApp Structure goes like this :




We will be using android Studio here.


    And Few properties of RecyclerView which i will discuss after code.
 
    So you might have to write something like this to run RecyclerView.

1. RecyclerViewActivity.java

public class RecyclerViewActivity extends Activity {

    ArrayList<String>mListitems;
    RecyclerView mRecyclerView;

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

    private void initiView(){
        mListitems=new ArrayList<String>();
        for(int i=0;i<125;i++){
            mListitems.add("List Item "+ i);
        }
        mRecyclerView=(RecyclerView) findViewById(R.id.recyclervew);

        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView
        mRecyclerView.setHasFixedSize(true);

       //The LinearLayoutManager is currently the only default implementation of LayoutManager. You can use this class to create either vertical or horizontal lists.

        LinearLayoutManager layoutManager = new LinearLayoutManager(RecyclerViewActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
 
       //Setting up ItemAnimator here
       mRecyclerView.setItemAnimator(new DefaultItemAnimator());

        //setting up the adapter
        RecyclerViewAdapter mAdapter=new RecyclerViewAdapter(RecyclerViewActivity.this,mListitems);
        mRecyclerView.setAdapter(mAdapter);
    }

}


2. RecyclerViewAdapter.java

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewViewHolder> {

      Context mContext;
      ArrayList<String>mListItems;
        public  RecyclerViewAdapter(Context mContext,ArrayList<String>mListItems){
            this.mContext=mContext;
            this.mListItems=mListItems;
        }


    @Override
    public RecyclerViewViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View itemView = LayoutInflater
                .from(viewGroup.getContext())
                .inflate(R.layout.row_recyclerview, viewGroup, false);
        return new RecyclerViewViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(RecyclerViewViewHolder recyclerViewViewHolder, int i) {

        recyclerViewViewHolder.txtView.setText(mListItems.get(i));
    }

    @Override
    public int getItemCount() {
        return mListItems.size();
    }
}


3. RecyclerViewViewHolder.java

public class RecyclerViewViewHolder extends RecyclerView.ViewHolder {

public TextView txtView;

    public RecyclerViewViewHolder(View itemView) {
        super(itemView);
        txtView = (TextView) itemView.findViewById(R.id.title);
    }
}


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

    <android.support.v7.widget.RecyclerView         xmlns:android="http://schemas.android.com/apk/res/android"         xmlns:tools="http://schemas.android.com/tools"         android:id="@+id/recyclervew"         android:layout_width="match_parent"         android:layout_height="wrap_content"        /> </LinearLayout>

2. row_recyclerview.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">     <TextView         android:layout_width="fill_parent"         android:layout_height="wrap_content"         android:id="@+id/txtview"         android:text="Demo recyclerView"         android:padding="10dp"         android:textColor="@android:color/holo_red_dark"         /> </LinearLayout>

Most important file now 
In App folder : build.gradle
Starts from here :>>>>

apply plugin: 'com.android.application'


android {     compileSdkVersion 22     buildToolsVersion "21.1.2"
    defaultConfig {         applicationId "com.example.kamalvaid.recyclerview"         minSdkVersion 14         targetSdkVersion 21         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:21.0.0'     compile 'com.android.support:recyclerview-v7:21.0.0'
}




    Now there are using few properties listed below those purpose should be clear

    1. mRecyclerView.setHasFixedSize(true); => use this setting to improve performance if you know that changes in content do not change the layout size of the RecyclerView

    2. LinearlayoutManager => The LinearLayoutManager is currently the only default implementation of LayoutManager. You can use this class to create either vertical or horizontal lists.
    
       And we are using like this

    LinearLayoutManager layoutManager = new LinearLayoutManager(RecyclerViewActivity.this);
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);            
    layoutManager.setOrientation(LinearLayoutManager.Horizontal);


Also RecyclerView doesn't include Divider property by default, So we have to customize it .


Output : 

      




Happy Coding!!!
Cheers

    

    

Wednesday, 1 April 2015

Creating App for Wearables



# Use Android Studio.(Recommended)
  •  Create Android Project
  •  Select Phone & Wear project
  •  Follow the steps for project creation wizard.
  • Design your layouts for both mobile and wearable in respective projects.

Now Problems that come when working with wearable

Firstly you need to install Android Wear Companion app on your device in order to make the device and wearable communicate.Which you can download from : https://play.google.com/store/apps/details?id=com.google.android.wearable.app

How to test the wearable app :

Now you need not to have a wearable device (Smartwatch) to test your app. You can test your app on the emulator.Create a wearble emulator using AVD.

Now open the android wearable app in the device and make sure your device is connected to system.After this you will see the welcome screen then select connect with emulator option from the action bar.After selecting the option simultaneously run this command inside i.e command prompt in windows or terminal in Mac in order to make device and emulator connected with each other.

adb -d forward tcp:5601 tcp:5601

Now after this you will see device and wearable emulator are connected with each other.Now whenever you install the Signed apk on device it will sync wearable apk for same onto emulator.

And if your app is not syncing to wearable device or emulator then make sure below points are corrected in your project :

Most of us face a common problem i.e apk file is not automatically installed on wearable when installed on Phone.Frankly i was troubled alot with this one.
But i got it right after few mistakes So do perfrom these steps in order to make app automatically installed as done installing on phone.

Step 1 : 

All the permissions defined in the wear app manifest file should be present in the mobile app manifest file.And you need not to put all phone permissions in wearable manifest.

Step 2 : 

Secondly  In build.gradle file of your phone app Confirm this

dependencies {
    wearApp project(':wear') // You should mention the exact name of the wear app folder here
}


Step 3 : 

Package name : In manifest file for both mobile and wear app should be same.
Application ID : (build.gradle file) of mobile and wear app should be same.


Now if you want to test app on wearable device then follow these instructions :
Firstly enable developer options in your wearable device as we do in device.
then enable debuggin over bluetooth in wearable under developer option.


Now On the handheld, open the Android Wear companion app then Tap the menu on the top right and select Settings.
Enable Debugging over Bluetooth. You can see the status :
Host: disconnected // this will be connected when we run the command to connect both device and wearable
Target: connected

To Connect the handheld to your machine over USB and run:

adb forward tcp:4444 localabstract:/adb-hub
adb connect localhost:4444

Then under settings in companion app you will see following status :
Host: connected
Target: connected

You can also check the connected devices in command prompt in Command prompt by using following command :

adb devices

Finally when you are done with the development of the app then you can generate a signed apk which will be installed on phone and automatically installed on wearable device.
Make sure that build generated is Signed then only it will be installed on wearable.

To generate signed apk Android studio provide us the simple wizard to do it. Well there are other ways available to generate the signed apk but prefer this.
Click on Build, Then select the Generate Signed apk option and go through the wizrad And you will get the signed apk.


Sometimes your app may take time to get Synced to wearable after installation on device so be Patience.And you can always sync manually app to wearable by using sync apps to watch option in android companion app under settings section.


Happy coding!!!
Cheers!!!

Android RecyclerView Or Android ListView ?



Read About Android RecyclerView : 


1 .If viewholder not used then Listview

1.1 Shows laggy Results i.e delayed response.
1.2 Major issue raised was finding views by IDs every time.

but this problem is solved in RecyclerView using RecyclerView.ViewHolder.
When implementing the adapter for RecyclerView, providing a ViewHolder is compulsory. So all above issues are not faced

2. Layout Manager

In ListView We can just implement vertical scroll according to its documentation.But recyclerView supports horizontal as well vertical scroll.
RecyclerView supports different lists which is implemented via RecyclerView.LayoutManager class.

ViewHolder : Recycling of views is managed by ViewHolder Class by holding references to all views in a separate view.So it help recyclerview work in a better optimized way.

RecyclerView.LayoutManager class for RecyclerView are :

LinearLayoutManager  : to create both horizontal and vertical scroll lists.
StaggeredGridLayoutManager : to  create staggered lists.
GridLayoutManager : to  display grids like view, like any image gallery or etc.


3.  Item Animator 

We can not apply custom animations to listview items but recyclerView  provides that facility.And can use RecyclerView.ItemAnimator class for handling animations.
We can apply  custom animations on item addition, deletion and move events.by default DefaultItemAnimator is used by android in case of recyclerview if we don't implement any custom animations.

4. OnItemTouchListener : A new addition  as well. In Listview we implemented OnItemClickListener in order to get item clicked. But in recyclerView,  RecyclerView.OnItemTouchListener is there which is  an interface that help us detect touch events in Android RecyclerView.So we can get gestures easily.

 RecyclerView is available in older SDK as support is provided in v7 lib.

So I think we need to use  RecyclerView as its new and will provide many customization, And will provide more in upcoming future.




Facebook Login In Android App




Simple Facebook Login in Android App :


  • Create your app in Developers facebook 


  • Include FacebookSdk Project as lib project in your app or put jar file in libs.


1. AndroidManifest.xml

Include this in AndroidManifest.xml

  <activity
            android:name="com.facebook.LoginActivity"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />

        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/app_id" />

2.  In XML layout create a button which when clicked will help us log with Facebook.


3.  MainActivity.java


public class MainActivity extends ActionBarActivity {



    private static final List<String> PERMISSIONS = Arrays.asList("email",
            "user_about_me", "user_location");
 
    Button mLogin;

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



mLogin=(Button)findViewById(R.id.login);

mLogin.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
loginWithFacebook();

}
});
}



void loginWithFacebook(){

Session.openActiveSession(this, true, new Session.StatusCallback() {

            // callback when session changes state
            @SuppressWarnings("deprecation")
@Override
            public void call(Session session, SessionState state,
                    Exception exception) {
                if (session.isOpened()) {
                    // make request to the /me API
                    List<String> permissions = session.getPermissions();
                    if (!isSubsetOf(PERMISSIONS, permissions)) {
                       // pendingPublishReauthorization = true;
                        Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(
                                MainActivity.this, PERMISSIONS);
                        session.requestNewReadPermissions(newPermissionsRequest);
                        return;
                    }
                    Request.executeMeRequestAsync(session,
                            new Request.GraphUserCallback() {
                        // callback after Graph API response with
                        // user object
                        @Override
                        public void onCompleted(GraphUser user,
                                Response response) {
                            if (user == null) {
                                Toast.makeText(
                                MainActivity.this
                                        .getApplicationContext(),
                                        "Facebook Error",
                                        Toast.LENGTH_LONG).show();

                            } else {
                                Toast.makeText(
                                MainActivity.this
                                        .getApplicationContext(),
                                        user.getName()
                                        + " Logged in Successfully.",
                                        Toast.LENGTH_LONG).show();
                                GraphUser abc = user;
                                Log.e("ID Name", user.getId()+""+user.getFirstName() + ""+                  

                                  user.getLastName()+"" + user.getUsername() );

                         
                            }

                            return;
                        }

                    });

                }
            }
        });
}


Html page and Android App Interaction


Simple Webview controls like html buttons etc interaction with Android app . This Post shows how to create a interface between the andriod app and webview using javascript.

In this post we will be calling method from android i.e placed javascript of html file And Method in android app from javascript in Html File.


1. MainActivity.java


public class MainActivity extends ActionBarActivity {

WebView webview;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview=(WebView)findViewById(R.id.webview);  
webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new WebAppInterface(this), "Android");      
webview.loadUrl("file:///android_asset/example.html");
btn=(Button)findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {

webview.loadUrl("javascript:showAndroidToastTwo(\"Calling From Android\")");
}
});
}
}



2. WebAppInterface.java

import android.content.Context;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

public class WebAppInterface {
    Context mContext;
 
    /** Instantiate the interface and set the context */
    WebAppInterface(Context c) {
        mContext = c;
    }
 
    /** Show a toast from the web page */
    @JavascriptInterface
    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }

}




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

<Button 
    android:id="@+id/btn"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:text="Click Javascript"
    />
    <WebView
        android:id="@+id/webview"
        android:layout_below="@+id/btn"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</RelativeLayout>



Html File To be placed in html for testing goes like this :

1. example.html

<html>
<head>
<script type="text/javascript">
    function showAndroidToast(toast) {
        Android.showToast(toast);
    }
 function showAndroidToastTwo(toast) {
        Android.showToast(toast);
    }
</script>
</head>
<body>
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
</body>



Output :