Thursday, September 22, 2016

Google Allo

                          Image result for google allo
Introducing Google Allo, a smart messaging app that helps you say more and do more. Express yourself better with stickers, doodles, and HUGE emojis & text. Allo also brings you the Google Assistant, preview edition.

Respond without typing, in your style.

Smart Reply lets you keep the conversation moving with a single tap by suggesting text and emoji responses based on your personality. For example, it learns if you're more of a “haha” or “lol” person so the more you use Google Allo, the more “you” the suggestions become.

Shout, or whisper it, to get your point across.

Add more meaning to your words by adjusting the size of your text. When you need more than ALL CAPS to get your point across, simply slide up to shout, and down to whisper.

 Image result for google allo

Turn any photo into a work of art.

Get creative with the photos you send by doodling on them or adding text. Draw a smiley face, turn your friends into memes, and mix in some color.


Say it all with the perfect sticker.

Stickers in Google Allo are designed by independent artists and studios from around the world. From Drama Llama to Food Party, add some fun to the conversation when words aren't enough.
 
 

Get help from your Google Assistant without leaving the conversation.

Your Assistant can suggest restaurants nearby or movies to check out, right in your conversation. Find videos to share, get directions, and seek answers together with your friends. Just add @google, and your Assistant is ready to help.

Chat one-on-one with your Google Assistant, whenever you need it.

Get the latest scores from the game. Find out how far you are from the airport, and when your flight leaves. You decide what to share with your Assistant, and the more you use it, the more useful it gets

Say it privately in Incognito mode.

Start an incognito chat to send a message with end-to-end encryption. Incognito mode also comes with expiring chats so you can control how long your messages stick around and private notifications to help keep your chats more discreet.

Chat in private with Incognito mode

By chatting in Incognito mode, you can have a more private and secure conversation with another person in Google Allo

Start a chat in Incognito mode

  1. Open Allo.
  2. Tap New Chat New chat and then Start incognito chat Incognito mode.
  3. From the Contacts list, tap the person's name you want to start a chat with. You can also search for the person's name or number.

What happens in Incognito mode

  • You won't be able to preview your message in the Allo conversation list. You'll just see that you or the other person "sent a message."
  • Notifications won't display who sent the message or its content. If you want to turn off notifications entirely, go to Menu Menu and then Settings and then Notifications.
  • Your chats are end-to-end encrypted and can only be seen by you and the person you're chatting with. Google can't read any of your messages, so you won't see any Smart Reply or Google Assistant features.
  • When you receive a sticker from a sticker pack that you don’t have, Allo will download it securely from Google’s servers, but without using end-to-end encryption.

Set messages to expire

In incognito mode, you can set the messages to disappear after a period of time. The default period is 1 hour, but you can change it.
  1. Open Allo.
  2. Tap New Chat New chat and then Start incognito chat Incognito mode.
  3. In the top right corner, tap the timerTimer.
  4. You can choose to never expire your messages. Or choose after how long you want your messages to disappear: Never, 5 seconds, 10 seconds, 30 seconds, 1 minute, 1 hour, 1 day, or 1 week.
    • For the sender: The timer starts when the message is sent.
    • For the receiver: The timer starts when the message is read.
Within the same chat, you and the recipient share the same timer setting. But you can set a different timer each time you start a new chat.
Important: Allo users who receive your messages can use other ways to save them, like taking a screenshot or by taking a photo.

.




Friday, September 16, 2016

Why Node.js ?

Why Node.js ?
Hottest new technology.
-> Node.js is JavaScript running on the Server.
-> Runs on Chrome V8 JavaScript engine.
-> Its Non blocking and Event driven.
-> Faster than PHP.
-> Does not need additional Server stack such as Apache or NGINX, It has inbuilt http module.
-> JavaScript is easier to learn.
-> Inbuilt Package Manager to install modules.
-> JSON is easier to Use. Android Login Registration System with Node.js and MongoDB

Teleprompter

  • A teleprompter is a display device that prompts the person speaking with an electronic visual text of a speech or script. Using a teleprompter is similar to using cue cards. The screen is in front of, and usually below, the lens of a professional video camera, and the words on the screen are reflected to the eyes of the presenter using a sheet of clear glass or a specially prepared beam splitter. Light from the performer passes through the front side of the glass into the lens, while a shroud surrounding the lens and the back side of the glass prevents unwanted light from entering the lens.

  • Because the speaker does not need to look down to consult written notes, he appears to have memorized the speech or to be speaking spontaneously, looking directly into the camera lens. Cue cards, on the other hand, are always placed away from the lens axis, making the speaker look at a point beside the camera, which leaves an impression of distraction.

     

  • The word TelePrompTer, with internal capitalization, originated as a trade name used by the TelePrompTer Company, which first developed the device in the 1950s; it is now a genericized trademark. Autocue, a United Kingdom manufacturer of teleprompters, also finds its trademark used in a generic fashion in Commonwealth countries and some European countries.

  • Modern teleprompters for news programs consist of a personal computer, connected to video monitors on each professional video camera. In certain systems, the PC connects to an external scroll device over IP to offer greater flexibility in setup, distances and cabling. The monitors are often black-and-white monochrome and have the scanning reversed to compensate for the reflection of the mirror. A peripheral device attached to the serial port has a knob that can be turned to speed up, slow down, or even reverse the scrolling of the text. The text is usually displayed in white letters on a black background for the best readability, while cues are in inverse video (black on white). Difficult words (mainly international names) are spelled out phonetically,[8] as are other particulars like "Nine-eleven" (to specify that the event 9/11 should not be pronounced "nine-one-one", for example).

  • With the development of inexpensive teleprompter software applications as well as free Web-based teleprompter applets, many different disciplines are now using teleprompters to help them deliver sermons, deliver speeches, and to create quality audio recordings. Unlike their more advanced counterparts, these entry level products work on desktop computers, laptop computers, and even tablet computers to enable the speaker to control the rate and flow of their speech. They are also used by many different organizations and schools to deliver prewritten information by relative novices. They are usually called "personal teleprompters."

Thursday, September 15, 2016

Apple's iOS 10


Apple's iOS 10 can be downloaded for free on a wide range of devices. Don't forget to backup your iOS device before you download and install iOS 10. It will be available in India at 10.30pm on September 13. If you live elsewhere, check out our post on the full list of iOS 10 release times across the world.

While iOS 10 public beta 7 and the release candidate version have been quite stable for us, the final version could have a few bugs that will be fixed in later updates. If you'd rather wait for that, then stop reading now. However if you are like us and always prefer updating to the latest version as soon as it is released, read on.

Will my iPhone, iPad, or iPod touch get iOS 10?
Apple has announced iOS 10 updates for the following devices:

iPhone 6s
iPhone 6s Plus
iPhone 6
iPhone 6 Plus
iPhone SE
iPhone 5s
iPhone 5c
iPhone 5
iPad Pro 12.9-inch
iPad Pro 9.7-inch
iPad Air 2
iPad Air
iPad 4th generation
iPad mini 4
iPad mini 3
iPad mini 2
iPod touch 6th generation
If you have any of these devices, you can install iOS 10. The iPhone 7 and iPhone 7 Plus ship with iOS 10. Follow the steps below to install iOS 10 on your iOS device.




How to download and install iOS 10
If you have enough free space on your iOS device you can update easily via these steps.

Go to Settings > General > Software Update.
Tap Download and Install.
When the download is complete, tap Install and tap Agree when Apple shows you its Terms and Conditions.
Your iOS device will restart and iOS 10 will be installed.
Download iOS 10 via iTunes
If you don't have enough free space on your iOS device, you can install the update via iTunes. Here's how.

If you don't have iTunes installed on your PC, first download and install it.
Open iTunes.
Connect the iOS device to your PC or Mac.
In iTunes select your device's icon on the top bar.
Click the Summary tab and then click Check for update.
Now click Download and update.
Follow the simple on-screen instructions to install iOS 10.Photo

Android - Fragments

A Fragment is a piece of an activity which enable more modular activity design. It will not be wrong if we say, a fragment is a kind of sub-activity.
Following are important points about fragment −
  • A fragment has its own layout and its own behaviour with its own life cycle callbacks.
  • You can add or remove fragments in an activity while the activity is running.
  • You can combine multiple fragments in a single activity to build a multi-plane UI.
  • A fragment can be used in multiple activities.
  • Fragment life cycle is closely related to the life cycle of its host activity which means when the activity is paused, all the fragments available in the activity will also be stopped.
  • A fragment can implement a behaviour that has no user interface component.
  • Fragments were added to the Android API in Honeycomb version of Android which API version 11.
You create fragments by extending Fragment class and You can insert a fragment into your activity layout by declaring the fragment in the activity's layout file, as a <fragment> element.
Prior to fragment introduction, we had a limitation because we can show only a single activity on the screen at one given point in time. So we were not able to divide device screen and control different parts separately. But with the introduction of fragment we got more flexibility and removed the limitation of having a single activity on the screen at a time. Now we can have a single activity but each activity can comprise of multiple fragments which will have their own layout, events and complete life cycle.
Following is a typical example of how two UI modules defined by fragments can be combined into one activity for a tablet design, but separated for a handset design.
Android Fragment The application can embed two fragments in Activity A, when running on a tablet-sized device. However, on a handset-sized screen, there's not enough room for both fragments, so Activity A includes only the fragment for the list of articles, and when the user selects an article, it starts Activity B, which includes the second fragment to read the article.

Fragment Life Cycle

Android fragments have their own life cycle very similar to an android activity. This section briefs different stages of its life cycle.
Fragment

Fragment lifecycle

Here is the list of methods which you can to override in your fragment class −
  • onAttach()The fragment instance is associated with an activity instance.The fragment and the activity is not fully initialized. Typically you get in this method a reference to the activity which uses the fragment for further initialization work.
  • onCreate() The system calls this method when creating the fragment. You should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed.
  • onCreateView() The system calls this callback when it's time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View component from this method that is the root of your fragment's layout. You can return null if the fragment does not provide a UI.
  • onActivityCreated()The onActivityCreated() is called after the onCreateView() method when the host activity is created. Activity and fragment instance have been created as well as the view hierarchy of the activity. At this point, view can be accessed with the findViewById() method. example. In this method you can instantiate objects which require a Context object
  • onStart()The onStart() method is called once the fragment gets visible.
  • onResume()Fragment becomes active.
  • onPause() The system calls this method as the first indication that the user is leaving the fragment. This is usually where you should commit any changes that should be persisted beyond the current user session.
  • onStop()Fragment going to be stopped by calling onStop()
  • onDestroyView()Fragment view will destroy after call this method
  • onDestroy()onDestroy() called to do final clean up of the fragment's state but Not guaranteed to be called by the Android platform.

How to use Fragments?

This involves number of simple steps to create Fragments.
  • First of all decide how many fragments you want to use in an activity. For example let's we want to use two fragments to handle landscape and portrait modes of the device.
  • Next based on number of fragments, create classes which will extend the Fragment class. The Fragment class has above mentioned callback functions. You can override any of the functions based on your requirements.
  • Corresponding to each fragment, you will need to create layout files in XML file. These files will have layout for the defined fragments.
  • Finally modify activity file to define the actual logic of replacing fragments based on your requirement.

Wednesday, September 14, 2016

Android Grid View

Android GridView shows items in two-dimensional scrolling grid (rows & columns) and the grid items are not necessarily predetermined but they automatically inserted to the layout using a ListAdapter
Grid View

Grid view

An adapter actually bridges between UI components and the data source that fill data into UI Component. Adapter can be used to supply the data to like spinner, list view, grid view etc.
The ListView and GridView are subclasses of AdapterView and they can be populated by binding them to an Adapter, which retrieves data from an external source and creates a View that represents each data entry.

GridView Attributes

Following are the important attributes specific to GridView −
Attribute Description
android:id This is the ID which uniquely identifies the layout.
android:columnWidth This specifies the fixed width for each column. This could be in px, dp, sp, in, or mm.
android:gravity Specifies the gravity within each cell. Possible values are top, bottom, left, right, center, center_vertical, center_horizontal etc.
android:horizontalSpacing Defines the default horizontal spacing between columns. This could be in px, dp, sp, in, or mm.
android:numColumns Defines how many columns to show. May be an integer value, such as "100" or auto_fit which means display as many columns as possible to fill the available space.
android:stretchMode Defines how columns should stretch to fill the available empty space, if any. This must be either of the values −
  • none: Stretching is disabled.
  • spacingWidth: The spacing between each column is stretched.
  • columnWidth: Each column is stretched equally.
  • spacingWidthUniform: The spacing between each column is uniformly stretched..
android:verticalSpacing Defines the default vertical spacing between rows. This could be in px, dp, sp, in, or mm.

Example

This example will take you through simple steps to show how to create your own Android application using GridView. Follow the following steps to modify the Android application we created in Hello World Example chapter −
Step Description
1 You will use Android studio IDE to create an Android application and name it as HelloWorld under a package com.example.helloworld as explained in the Hello World Example chapter.
2 Modify the detault content of res/layout/activity_main.xml file to include GridView content with the self explanatory attributes.
3 No need to change string.xml, Android studio takes care of defaults strings which are placed at string.xml
4Let's put few pictures in res/drawable-hdpi folder. I have put sample0.jpg, sample1.jpg, sample2.jpg, sample3.jpg, sample4.jpg, sample5.jpg, sample6.jpg and sample7.jpg.
5 Create a new class called ImageAdapter under a package com.example.helloworld that extends BaseAdapter. This class will implement functionality of an adapter to be used to fill the view.
6 Run the application to launch Android emulator and verify the result of the changes done in the application.
Following is the content of the modified main activity file src/com.example.helloworld/MainActivity.java. This file can include each of the fundamental lifecycle methods.
package com.example.helloworld;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.GridView;

public class MainActivity extends Activity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      GridView gridview = (GridView) findViewById(R.id.gridview);
      gridview.setAdapter(new ImageAdapter(this));
   }
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   }
}
Following will be the content of res/layout/activity_main.xml file −
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/gridview"
   android:layout_width="fill_parent" 
   android:layout_height="fill_parent"
   android:columnWidth="90dp"
   android:numColumns="auto_fit"
   android:verticalSpacing="10dp"
   android:horizontalSpacing="10dp"
   android:stretchMode="columnWidth"
   android:gravity="center"
/>
Following will be the content of res/values/strings.xml to define two new constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="app_name">HelloWorld</string>
   <string name="action_settings">Settings</string>
</resources>
Following will be the content of src/com.example.helloworld/ImageAdapter.java file −
package com.example.helloworld;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class ImageAdapter extends BaseAdapter {
   private Context mContext;
   
   // Constructor
   public ImageAdapter(Context c) {
      mContext = c;
   }
   
   public int getCount() {
      return mThumbIds.length;
   }

   public Object getItem(int position) {
      return null;
   }

   public long getItemId(int position) {
      return 0;
   }
   
   // create a new ImageView for each item referenced by the Adapter
   public View getView(int position, View convertView, ViewGroup parent) {
      ImageView imageView;
      
      if (convertView == null) {
         imageView = new ImageView(mContext);
         imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
         imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
         imageView.setPadding(8, 8, 8, 8);
      } 
      else 
      {
         imageView = (ImageView) convertView;
      }
      imageView.setImageResource(mThumbIds[position]);
      return imageView;
   }
   
   // Keep all Images in array
   public Integer[] mThumbIds = {
      R.drawable.sample_2, R.drawable.sample_3,
      R.drawable.sample_4, R.drawable.sample_5,
      R.drawable.sample_6, R.drawable.sample_7,
      R.drawable.sample_0, R.drawable.sample_1,
      R.drawable.sample_2, R.drawable.sample_3,
      R.drawable.sample_4, R.drawable.sample_5,
      R.drawable.sample_6, R.drawable.sample_7,
      R.drawable.sample_0, R.drawable.sample_1,
      R.drawable.sample_2, R.drawable.sample_3,
      R.drawable.sample_4, R.drawable.sample_5,
      R.drawable.sample_6, R.drawable.sample_7
   };
}
Let's try to run our modified Hello World! application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android Studio, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −
Android gridView Layout

Sub-Activity Example

Let's extend the functionality of above example where we will show selected grid image in full screen. To achieve this we need to introduce a new activity. Just keep in mind for any activity we need perform all the steps like we have to implement an activity class, define that activity in AndroidManifest.xml file, define related layout and finally link that sub-activity with the main activity by it in the main activity class. So let's follow the steps to modify above example −
Step Description
1 You will use Android studio IDE to create an Android application and name it as HelloWorld under a package com.example.helloworld as explained in the Hello World Example chapter.
2 Create a new Activity class as SingleViewActivity.java under a package com.example.helloworld as shown below.
3 Create new layout file for the new activity under res/layout/ folder. Let's name this XML file as single_view.xml.
4 Define your new activity in AndroidManifest.xml file using <activity.../> tag. An application can have one or more activities without any restrictions.
5Run the application to launch Android emulator and verify the result of the changes done in the application.
Following is the content of the modified main activity file src/com.example.helloworld/MainActivity.java. This file can include each of the fundamental life cycle methods.
package com.example.helloworld;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

public class MainActivity extends Activity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      GridView gridview = (GridView) findViewById(R.id.gridview);
      gridview.setAdapter(new ImageAdapter(this));
      
      gridview.setOnItemClickListener(new OnItemClickListener() {
         public void onItemClick(AdapterView<?> parent, View v, int position, long id){
            // Send intent to SingleViewActivity 
            Intent i = new Intent(getApplicationContext(), SingleViewActivity.class);
            
            // Pass image index
            i.putExtra("id", position);
            startActivity(i);
         }
      });
   }
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   }
}
Following will be the content of new activity file src/com.example.helloworld/SingleViewActivity.java file −
package com.example.helloworld;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;

public class SingleViewActivity extends Activity {
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.single_view);
      
      // Get intent data
      Intent i = getIntent();
      
      // Selected image id
      int position = i.getExtras().getInt("id");
      ImageAdapter imageAdapter = new ImageAdapter(this);
      
      ImageView imageView = (ImageView) findViewById(R.id.SingleView);
      imageView.setImageResource(imageAdapter.mThumbIds[position]);
   }
}
Following will be the content of res/layout/single_view.xml file −
<?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/SingleView"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"/>
 
</LinearLayout>
Following will be the content of AndroidManifest.xml to define two new constants −
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.helloworld"
   android:versionCode="1"
   android:versionName="1.0" >
   
   <uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="22" />
      
   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name="com.example.helloworld.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>
   
      <activity android:name=".SingleViewActivity"></activity>
   
   </application>
</manifest>
Let's try to run our modified Hello World! application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −
Android gridView Layout Now if you click on either of the images it will be displayed as a single image, for example−
Android Single GridView Layout
Kindly note above mentioned images have been taken from Android official website.

Tuesday, September 13, 2016

REST:Representational state transfer

What is REST ?

REST stands for REpresentational State Transfer. REST is web standards based architecture and uses HTTP Protocol for data communication. It revolves around resource where every component is a resource and a resource is accessed by a common interface using HTTP standard methods. REST was first introduced by Roy Fielding in 2000.
In REST architecture, a REST Server simply provides access to resources and REST client accesses and presents the resources. Here each resource is identified by URIs/ global IDs. REST uses various representations to represent a resource like text, JSON and XML. Now a days JSON is the most popular format being used in web services.

HTTP Methods

Following well known HTTP methods are commonly used in REST based architecture.
  • GET - Provides a read only access to a resource.
  • PUT - Used to create a new resource.
  • DELETE - Used to remove a resource.
  • POST - Used to update a existing resource or create a new resource.
  • OPTIONS - Used to get the supported operations on a resource.

RESTFul Web Services

A web service is a collection of open protocols and standards used for exchanging data between applications or systems. Software applications written in various programming languages and running on various platforms can use web services to exchange data over computer networks like the Internet in a manner similar to inter-process communication on a single computer. This interoperability (e.g., between Java and Python, or Windows and Linux applications) is due to the use of open standards.
Web services based on REST Architecture are known as RESTful web services. These web services use HTTP methods to implement the concept of REST architecture. A RESTful web service usually defines a URI, Uniform Resource Identifier a service, provides resource representation such as JSON and set of HTTP Methods.

Creating RESTFul Web Service

This tutorial will create a web service say user management with following functionalities:
Sr. No.HTTP MethodURIOperationOperation Type
1GET/UserService/usersGet list of usersRead Only
2GET/UserService/users/1Get User with Id 1Read Only
3PUT/UserService/users/2Insert User with Id 2Idempotent
4POST/UserService/users/2Update User with Id 2N/A
5DELETE/UserService/users/1Delete User with Id 1Idempotent
6OPTIONS/UserService/usersList the supported operations in web serviceRead Only

Basic MVC Architecture

Model View Controller or MVC as it is popularly called, is a software design pattern for developing web applications. A Model View Controller pattern is made up of the following three parts:
  • Model - The lowest level of the pattern which is responsible for maintaining data.
  • View - This is responsible for displaying all or a portion of the data to the user.
  • Controller - Software Code that controls the interactions between the Model and View.
MVC is popular as it isolates the application logic from the user interface layer and supports separation of concerns. Here the Controller receives all requests for the application and then works with the Model to prepare any data needed by the View. The View then uses the data prepared by the Controller to generate a final presentable response. The MVC abstraction can be graphically represented as follows.
Struts MVC

The model

The model is responsible for managing the data of the application. It responds to the request from the view and it also responds to instructions from the controller to update itself.

The view

A presentation of data in a particular format, triggered by a controller's decision to present the data. They are script based templating systems like JSP, ASP, PHP and very easy to integrate with AJAX technology.

The controller

The controller is responsible for responding to user input and perform interactions on the data model objects. The controller receives the input, it validates the input and then performs the business operation that modifies the state of the data model.

Monday, September 12, 2016

List View -OnItemClickListener - Example

In this android example creating a simple listview to display a array values.

activity_list_view_android_example.xml File

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
 
         <ListView
              android:id="@+id/list"
              android:layout_height="wrap_content"
              android:layout_width="match_parent">
         </ListView>
 
</LinearLayout>

Explanation :
Define ListView in xml file


   <ListView
        android:id="@+id/list"
        android:layout_height="wrap_content"
        android:layout_width="match_parent">
    </ListView>


=========================================================================================

ListViewAndroidExample.java File

    public class ListViewAndroidExample extends Activity {
        ListView listView ;
        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_list_view_android_example);
            
            // Get ListView object from xml
            listView = (ListView) findViewById(R.id.list);
            
            // Defined Array values to show in ListView
            String[] values = new String[] { "Android List View", 
                                             "Adapter implementation",
                                             "Simple List View In Android",
                                             "Create List View Android", 
                                             "Android Example", 
                                             "List View Source Code", 
                                             "List View Array Adapter", 
                                             "Android Example List View" 
                                            };
    
            // Define a new Adapter
            // First parameter - Context
            // Second parameter - Layout for the row
            // Third parameter - ID of the TextView to which the data is written
            // Forth - the Array of data
    
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
              android.R.layout.simple_list_item_1, android.R.id.text1, values);
    
    
            // Assign adapter to ListView
            listView.setAdapter(adapter); 
            
            // ListView Item Click Listener
            listView.setOnItemClickListener(new OnItemClickListener() {
 
                  @Override
                  public void onItemClick(AdapterView<?> parent, View view,
                     int position, long id) {
                    
                   // ListView Clicked item index
                   int itemPosition     = position;
                   
                   // ListView Clicked item value
                   String  itemValue    = (String) listView.getItemAtPosition(position);
                      
                    // Show Alert 
                    Toast.makeText(getApplicationContext(),
                      "Position :"+itemPosition+"  ListItem : " +itemValue , Toast.LENGTH_LONG)
                      .show();
                 
                  }
    
             }); 
        }
    
    }
 
Explanation:
 
 Adapters are used to provide the data to the ListView
 
   Parameters:
 
       simple_list_item_1 :  Android internal layout view
       android.R.id.text1    :  In Android internal layout view already defined text fields to show data
        values                       :  User defined data array.
 
 
           ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
          android.R.layout.simple_list_item_1, android.R.id.text1, values);
 
           // Assign adapter to ListView
          listView.setAdapter(adapter); 
 
When Click on list item then onItemClick method in ListView Item Click Listener called

         listView.setOnItemClickListener(new OnItemClickListener() {
 
                      @Override
                      public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                        
                       // ListView Clicked item index
                       int itemPosition     = position;
                       
                       // ListView Clicked item value
                       String  itemValue    = (String) listView.getItemAtPosition(position);
                          
                        // Show Alert 
                        Toast.makeText(getApplicationContext(),
                          "Position :"+itemPosition+"  ListItem : " +itemValue , Toast.LENGTH_LONG)
                          .show();
                     
                      }
              });  

Android - Event Handling

Events are a useful way to collect data about a user's interaction with interactive components of Applications. Like button presses or screen touch etc. The Android framework maintains an event queue as first-in, first-out (FIFO) basis. You can capture these events in your program and take appropriate action as per requirements.
There are following three concepts related to Android Event Management −
  • Event Listeners − An event listener is an interface in the View class that contains a single callback method. These methods will be called by the Android framework when the View to which the listener has been registered is triggered by user interaction with the item in the UI.
  • Event Listeners Registration − Event Registration is the process by which an Event Handler gets registered with an Event Listener so that the handler is called when the Event Listener fires the event.
  • Event Handlers − When an event happens and we have registered an event listener for the event, the event listener calls the Event Handlers, which is the method that actually handles the event.

Event Listeners & Event Handlers

Event Handler Event Listener & Description
onClick() OnClickListener() This is called when the user either clicks or touches or focuses upon any widget like button, text, image etc. You will use onClick() event handler to handle such event.
onLongClick() OnLongClickListener() This is called when the user either clicks or touches or focuses upon any widget like button, text, image etc. for one or more seconds. You will use onLongClick() event handler to handle such event.
onFocusChange() OnFocusChangeListener() This is called when the widget looses its focus ie. user goes away from the view item. You will use onFocusChange() event handler to handle such event.
onKey() OnFocusChangeListener() This is called when the user is focused on the item and presses or releases a hardware key on the device. You will use onKey() event handler to handle such event.
onTouch() OnTouchListener() This is called when the user presses the key, releases the key, or any movement gesture on the screen. You will use onTouch() event handler to handle such event.
onMenuItemClick() OnMenuItemClickListener() This is called when the user selects a menu item. You will use onMenuItemClick() event handler to handle such event.
onCreateContextMenu() onCreateContextMenuItemListener() This is called when the context menu is being built(as the result of a sustained "long click)
There are many more event listeners available as a part of View class like OnHoverListener, OnDragListener etc which may be needed for your application. So I recommend to refer official documentation for Android application development in case you are going to develop a sophisticated apps.

Event Listeners Registration

Event Registration is the process by which an Event Handler gets registered with an Event Listener so that the handler is called when the Event Listener fires the event. Though there are several tricky ways to register your event listener for any event, but I'm going to list down only top 3 ways, out of which you can use any of them based on the situation.
  • Using an Anonymous Inner Class
  • Activity class implements the Listener interface.
  • Using Layout file activity_main.xml to specify event handler directly.
Below section will provide you detailed examples on all the three scenarios −

Touch Mode

Users can interact with their devices by using hardware keys or buttons or touching the screen.Touching the screen puts the device into touch mode. The user can then interact with it by touching the on-screen virtual buttons, images, etc.You can check if the device is in touch mode by calling the View class’s isInTouchMode() method.
Event

Touch Event

Focus

A view or widget is usually highlighted or displays a flashing cursor when it’s in focus. This indicates that it’s ready to accept input from the user.
  • isFocusable() – it returns true or false
  • isFocusableInTouchMode() – checks to see if the view is focusable in touch mode. (A view may be focusable when using a hardware key but not when the device is in touch mode)
android:foucsUp="@=id/button_l"

onTouchEvent()

public boolean onTouchEvent(motionEvent event){
   switch(event.getAction()){
      case TOUCH_DOWN:
      Toast.makeText(this,"you have clicked down Touch button",Toast.LENTH_LONG).show();
      break();
   
      case TOUCH_UP:
      Toast.makeText(this,"you have clicked up touch button",Toast.LENTH_LONG).show();
      break;
   
      case TOUCH_MOVE:
      Toast.makeText(this,"you have clicked move touch button"Toast.LENTH_LONG).show();
      break;
   }
   return super.onTouchEvent(event) ;
}

Event Handling Examples

Event Listeners Registration Using an Anonymous Inner Class

Here you will create an anonymous implementation of the listener and will be useful if each class is applied to a single control only and you have advantage to pass arguments to event handler. In this approach event handler methods can access private data of Activity. No reference is needed to call to Activity.
But if you applied the handler to more than one control, you would have to cut and paste the code for the handler and if the code for the handler is long, it makes the code harder to maintain.
Following are the simple steps to show how we will make use of separate Listener class to register and capture click event. Similar way you can implement your listener for any other required event type.
Step Description
1 You will use Android studio IDE to create an Android application and name it as myapplication under a package com.example.myapplication as explained in the Hello World Example chapter.
2 Modify src/MainActivity.java file to add click event listeners and handlers for the two buttons defined.
3 Modify the detault content of res/layout/activity_main.xml file to include Android UI controls.
4 No need to declare default string constants.Android studio takes care default constants.
5 Run the application to launch Android emulator and verify the result of the changes done in the aplication.
Following is the content of the modified main activity file src/com.example.myapplication/MainActivity.java. This file can include each of the fundamental lifecycle methods.
package com.example.myapplication;

public class MainActivity extends ActionBarActivity {
   private ProgressDialog progress;
   Button b1,b2;
   
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      progress = new ProgressDialog(this);
      
      b1=(Button)findViewById(R.id.button);
      b2=(Button)findViewById(R.id.button2);
      b1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            TextView txtView = (TextView) findViewById(R.id.textView);
            txtView.setTextSize(25);
         }
      });
      
      b2.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            TextView txtView = (TextView) findViewById(R.id.textView);
            txtView.setTextSize(55);
         }
      });
   }
   
   @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.
      
      int id = item.getItemId();
      
      //noinspection SimplifiableIfStatement
      if (id == R.id.action_settings) {
         return true;
      }
      return super.onOptionsItemSelected(item);
   }
}
Following will be the content of res/layout/activity_main.xml file −
<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=".MainActivity">
   
   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Event Handling "
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:textSize="30dp"/>
      
   <TextView
      android:id="@+id/textView2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point "
      android:textColor="#ff87ff09"
      android:textSize="30dp"
      android:layout_above="@+id/imageButton"
      android:layout_centerHorizontal="true"
      android:layout_marginBottom="40dp" />
      
   <ImageButton
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageButton"
      android:src="@drawable/abc"
      android:layout_centerVertical="true"
      android:layout_centerHorizontal="true" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Small font"
      android:id="@+id/button"
      android:layout_below="@+id/imageButton"
      android:layout_centerHorizontal="true" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Large Font"
      android:id="@+id/button2"
      android:layout_below="@+id/button"
      android:layout_alignRight="@+id/button"
      android:layout_alignEnd="@+id/button" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Hello World!"
      android:id="@+id/textView"
      android:layout_below="@+id/button2"
      android:layout_centerHorizontal="true"
      android:textSize="25dp" />
      
</RelativeLayout>
Following will be the content of res/values/strings.xml to define two new constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="app_name">myapplication</string>
   <string name="action_settings">Settings</string>
</resources>
Following is the default content of AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.myapplication"
   android:versionCode="1"
   android:versionName="1.0" >
   
   <uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="22" />
      
   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name="com.example.myapplication.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>
Let's try to run your myapplication application. I assume you had created your AVD while doing environment setup. To run the app from Android Studio, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Android Studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −
Android Event Handling Now you try to click on two buttons, one by one and you will see that font of the Hello World text will change, which happens because registered click event handler method is being called against each click event.