Friday 12 December 2014

RecyclerView Tutorial


Android has introduced a new widget for displaying data collections which is a more advanced and flexible version of ListView. RecyclerView incorporates ListView and ViewHolder reusability concept very efficiently.

RecyclerView is very useful with large data collections whose content changes at runtime.

RecyclerView includes:

  1. Layout managers for positioning items. 
  2. Default animatios for common item operations , such as removal or addition of items.


Custom animation and layout managers can be defined as per the requirement.



Layout Manager:


RecyclerView provides 3 built-in layout managers:

  1. LinearLayoutManager shows items in a vertical or horizontal scrolling list. 
  2. GridLayoutManage shows items in a grid. 
  3. StaggeredGridLayoutManager shows items in a staggered grid. 

For custom layout manager, extend the RecyclerView.LayoutManager class.

Animation:



  1. Animations for adding and removing items are enabled by default.
  2. For custom animation, extend the RecyclerView.ItemAnimator class and use the RecyclerView.setItemAnimator() method.



RecyclerView Demo:

  1. Create a new Android project.
  2. Add the v7 support library, for eclipse follow the link and for gradle add: 
dependencies{
        compile com.android.support:recyclerview-v7:21.0.+
}
     3.  Add RecyclerView in xml:


<android.support.v7.widget.RecyclerView  
     android:id="@+id/recylcer_view"  
     android:layout_width="match_parent"  
     android:layout_height="match_parent"  
     android:scrollbars="vertical" />


   4. Create Adapter file MyRecyclerViewAdapter.java
      by extending RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder>


public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder>{

 private String[] mData;

 public MyRecyclerViewAdapter(String[] mData) {
  this.mData = mData;
 }

 @Override
 public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
  View v = LayoutInflater.from(viewGroup.getContext())
    .inflate(R.layout.list_item_layout, viewGroup, false);

  ViewHolder vh = new ViewHolder(v);
  return vh;

 }

 @Override
 public void onBindViewHolder(ViewHolder viewHolder, int i) {
  viewHolder.mTextView.setText(mData[i]);
 }

 @Override
 public int getItemCount() {
  if (mData != null)
   return mData.length;
  return 0;
 }

 public static class ViewHolder extends RecyclerView.ViewHolder {
  // each data item is just a string in this case
  public TextView mTextView;

  public ViewHolder(View itemView) {
   super(itemView);
   mTextView = (TextView)itemView.findViewById(R.id.txt);;
  }
 }
}


   5. Create Activity MyActivity.java

public class MyActivity extends Activity implements View.OnClickListener{

    private RecyclerView mRecyclerView;
    private MyRecyclerViewAdapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private GridLayoutManager mGridLayoutManager;
    private StaggeredGridLayoutManager mStaggeredGridLayoutManager;

    private String[] mSampleData = {"What is Android Lollipop?", "What is Android 5.0?",                     "What is RecyclerView?", "What is difference between RecyclerView and ListView?", "How does this demo app help?"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);

        mRecyclerView = (RecyclerView) findViewById(R.id.recylcer_view);
        mRecyclerView.setHasFixedSize(true);

        mAdapter = new MyRecyclerViewAdapter(mSampleData);
        mRecyclerView.setAdapter(mAdapter);
        applyLinearLayoutManager();
    }

    private void applyLinearLayoutManager(){
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
    }

    private void applyGridLayoutManager(){
        mGridLayoutManager = new GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(mGridLayoutManager);
    }


    private void applyStaggeredGridLayoutManager(){
        mStaggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(mStaggeredGridLayoutManager);
    }




    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.my, 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.
        int id = item.getItemId();
        if (id == R.id.action_linear)
            applyLinearLayoutManager();
        else if (id == R.id.action_grid)
            applyGridLayoutManager();
        else if (id == R.id.action_staggered)
            applyStaggeredGridLayoutManager();
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        int pos = mRecyclerView.getChildPosition(v);
        Toast.makeText(getApplicationContext(), mSampleData[pos], Toast.LENGTH_LONG).show();
    }
}



Get ready for Jack and Jill !!!

Android is working over new toolchain and it has introduced Jack and Jill available for testing with non-production versions of the apps, at the core of the new toolchain.

JACK - Java Android Compiler Kit

Jack is a new Android toolchain that comprises a compiler from Java programming language source to the Android dex file format. Jack has its own .jack library format and provides most tool chain features as part of a single tool: repackaging, shrinking, obfuscation and multidex.


JILL - Jack Intermediate Library Linker

Jill is a tool that translates existing .jar files to the .jack library format.


Working


With the new tool chain enabled, Jill will translate any libraries you are referencing to a new Jack library file (.jack). This prepares them to be quickly merged with other .jack files. The Android Gradle plugin and Jack collect any .jack library files, along with your source code, and compiles them into a set of dex files. During the process, Jack also handles any requested code minification. The output is then assembled into an APK file as normal. Support for multiple dex files is also included.



Jack using Gradle


Jack and Jill are available in Build Tools version 21.1.1, and greater, via the SDK Manager. Complementary Gradle and Android Studio support is also already available in the Android 1.0.0+ Gradle plugin.

Using Gradle, add useJack in your build config.

android {
    ...
    buildToolsRevision '21.1.1'
    defaultConfig {
      // Enable the experimental Jack build tools.
      useJack = true
    }
    ...
}


Official Blog: http://android-developers.blogspot.in/2014/12/hello-world-meet-our-new-experimental.html

Tool Doc: http://tools.android.com/tech-docs/jackandjill


Tuesday 11 November 2014

App Indexing for Google Search

Websites have a lot way of getting it's content searched via search engine i.e google but mobile apps are not accessible for such search.

Smartphone users have tons of information on their phones, but the tools to find that information are rudimentary at best.

Your favorite restaurants, for example, might be stored in any number of apps, such as Foursquare or Yelp. Likewise, travel plans might be stored in an airline app or a travel app, such as Expedia or Orbitz. Finding that information requires first that you remember which app you used, since today’s search engines can’t penetrate the walls set up around each mobile application.

App Indexing allows you to connect pages from your website with specific content within your smartphone app. This enables smartphone users who have your app installed to open it directly from relevant mobile search results on Google.

Recently, a number of methods have emerged for finding information within applications. Such approaches are known as deep linking because they point not just to the right app, but to the specific place within an app’s structure where the information is stored.

App Indexing helps you drive usage of your app through Google. Deep links to your app appear in Google Search results on Android so users can get to your native mobile experience quickly and easily.

Follow this Google doc for implementing app indexing.

Apps with or without corresponding webpages can use the App Indexing API to notify Google of their deep links.

Along with Google, facebook is also providing API called App Links for app indexing.

Other companies are also providing their solutions, check below links:

http://appurl.org/
http://urx.com/

Sunday 9 November 2014

Link your app with Google Voice Search

Google with Version 3.5 has come extended it's voice search functionality to include device apps in its search result.

Now Activate Google voice search by saying "OK Google" from anywhere within your app or from anywhere within the device.

You are only required to add few lines of code in your manifest file.

<activity android:name=".SearchableActivity">
    <intent-filter>
        <action android:name="com.google.android.gms.actions.SEARCH_ACTION"/>
        <category android:name="android.intent.category.DEFAULT"/>
    </intent-filter>
</activity>
Once manifest changes are done, your app will receive the SEARCH_ACTION intent containing the SearchManager.QUERY extra with the search expression.

Assuming your app as MyApp. You can:
Activate Google: Say "OK Google"
Start Search: Say "search xyz on MyApp" or "Search for hotels in India on MyApp".

Inside your activity, you get the search string i.e xyz, hotels :
String query = getIntent().getExtras().getString(SearchManager.QUERY);

This feature is available on English locale Android devices running Jelly Bean and above with the Google app v3.5 or greater.

Check this OK Google from any screen and also check official post.

Saturday 25 October 2014

Android Studio Shortcuts for Windows

Using shortcuts make a developer more productive. Eclipse provides keyboard shortcuts for the most common actions so does Android Studio. Android Studio will be official development IDE and this tutorial will help in migrating from Eclipse to Android Studio.

    1) Quick Access
Action
Android Studio Key Command
To quickly open any class
CTRL + N
To quickly open any file
CTRL + SHIFT + N
Toggle tools (maximize/minimize code window).
CTRL + SHIFT + F12
To find all places where a particular class, method or variable is used in the whole project by positioning the caret at the symbol's name or at its usage in code.
ALT + F7


    2) Editing
Action
Android Studio Key Command
Basic code completion
CTRL + SPACE
Smart code completion
CTRL + SHIFT + SPACE
Parameter Info
CTRL + P
Quick documentation
CTRL + Q
External doc
SHIFT + F1
Generate code... (Getters, Setters, constructors etc)
ALT + INSERT
Override methods
CTRL + O
Surround with… (if..else, try..catch, for, synchronized, etc.)
CTRL + ALT + T
Comment/Uncomment single line
CTRL + /
Comment/Uncomment block code
CTRL + SHIFT + /
Select successively increasing code blocks
CTRL + W
Decrease current selection to previous state
CTRL + SHIFT + W
Reformat code
ALT + CTRL + L
Optimize imports
ALT + CTRL + O
Auto indent lines
ALT + CTRL + I
Duplicate current line/selected block
CTRL + D
Delete current line
CTRL + Y
Close active editor
CTRL + F4
Highlight usage in file
CTRL + SHIFT + F7
Find usages / Find usages in file
ALT + F7/ CTRL + F7
Show usages
ALT + CTRL + F7
Rename
SHIFT + F6
Change signature
CTRL + F6
Extract method
ALT + CTRL + M
Search everywhere
Double shift
Find
CTRL + F
Find next/previous
F3/SHIFT + F3
Replace
CTRL + R
Find in path
CTRL + SHIFT + F
Replace in path
CTRL + SHIFT + R

    3) Navigation
Action
Android Studio Key Command
Go to symbol
ALT + CTRL + SHIFT + N
Next/previous editor tab
ALT + RIGHT/LEFT
Previous tool window
F12
Editor from tool window
ESC
Hide active/last active window
SHIFT + ESC
Go to line
CTRL + G
Recent file
CTRL + E
Go to declaration
CTRL + B/ CTRL + CLICK
Go to implementation
ALT + CTRL + B
Open quick definition lookup
CTRL + SHIFT + I
Go to type declaration
CTRL + SHIFT + B
Go to super-method/class
CTRL + U
Go to previous/next method
CTRL + ARROW UP/DOWN
File structure pop up
CTRL + F12
Type hierarchy
CTRL + H
Method hierarchy
CTRL + SHIFT + H
Call hierarchy
ALT + CTRL + H
Edit/View source
F4/ CTRL + ENTER
Navigation Bar
ALT + HOME
Toggle bookmark
F11
Show bookmark
SHIFT + F11
Jump to source
F4
Command look-up (autocomplete command name)
CTRL + SHIFT + A

    4) Build/Debug/Run
Action
Android Studio Key Command
Build
CTRL + F9
Build and run
SHIFT + F10
Debug
SHIFT + F9
Toggle project visibility
ALT + 1
Navigate open tabs
ALT + left-arrow; ALT + right-arrow
View recent changes
ALT + SHIFT + C
Step over
F8
Step into
F7
Smart step into
SHIFT + F7
Step out
SHIFT + F8
Resume program
F9
Toggle breakpoint
CTRL + F8
View breakpoints
CTRL + SHIFT + F8

Shortcuts on Mac OS:
The above description uses the shortcuts based on Windows and Linux. Mac OS uses the Cmd key frequently instead of the Ctrl key.

Note:                                                    
View/Edit Keymap shortcuts - File -> Settings ->  Keymap
Check this link for migrating from Eclipse to Android Studio.