Android Archives

New Apps for the Pebble Watch

It’s just a watch, isn’t it? Well, not really! The Pebble Smart Watch is so much more than just a regular watch. The fact that it is both iOS and Android ready is what makes it appealing to developers this year, and we aren’t to be left out.

Made the Show!

This is the watch that made headlines this year at the world’s largest innovation event. Why? Because it is app ready. This is a watch anyone can customize for their needs. So what makes this special to us as app designers and teachers. This makes the Pebble Smart Watch our new tech toy (really more than a toy) of the year. It means we have a whole new app world available, one in which we can create some pretty amazing apps to work for consumers.
Actually, the Pebble is ideal because it offers users a 1.26 inch display with an incredible resolution of 144 x 168; meaning consumers can get a clear view of their messages, favorite apps and interface options even in the dark of night. We are amazed by this watch because of it’s ability to connect to any Android or iOS device through its Bluetooth 4.0 BLE connectivity and long lasting battery life.

The Aha Moment Comes to App Designers

We finally see the greatness of the Pebble, especially because it currently has more tech abilities than the apps that have so far been designed for it. In particular, it has a three-axis accelerometer and Bluetooth LE. Add this to the newly announced 2.0 SDK and we really have something exciting. This means developers can now access the Pebble’s built-in technology and designed apps can now access data even when not connected to a phone. It can pull data from the phone’s Internet connection. This means new future fitness app possibilities, standalone weather and transit apps too, even a few more useful apps, depending on the developer’s creativity. This is truly an important event, because it offers apps that the Pebble has lacked until now.

This New Pebble with SDK is Available Now

But that doesn’t necessarily mean the apps are ready. We still have to develop them. That’s where the fun begins. The future of the Pebble certainly looks brighter and much more useful to the average person, especially if the next killer app for Pebble becomes available.

Serializing an Object in Java

Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object’s data as well as information about the object’s type and the types of data stored in the object.

After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.

The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo program instantiates an Employee object and serializes it to a file.


//Employee class

class Employee implements java.io.Serializable
{
public String name;
public String address;
public String city;
public int id;
}

import java.io.*;

public class SerializeDemo
{
public static void main(String [] args)
{
Employee emp = new Employee();
emp.name = "Rajeev Pillai";
emp.address = "292, PTP Nagar";
emp.city = "Trivandrum";
emp.id = 1000;

//Serialize
try {
ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream("employee.ser"));
out.writeObject(emp);
out.close();
System.out.printf("Serialized data is saved");

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

samsung-gs4-gpe-new-logo
Google and Samsung agreeing to a 10 year patent licensing deal was good news for Android. But that might only be the tip of the iceberg. According to a report from Re/code the two are working together on a broader initiative that will bring the Samsung version of Android more inline with Google’s vision. The talks appear to have started at CES following the reveal of Galaxy Tab Pro and Note Pro lines, which featured a new skin called Magazine UX. The interface was not only a dramatic departure from the familiar TouchWiz, but from the very core of Android itself. In fact, the panel-based home screen looks a lot more like Windows 8 than Mountain View’s mobile OS. But Re/code’s sources say that future Samsung devices will either feature a drastically scaled back version of Magazine UX or lose the interface all together. Obviously, keeping the Android experience as consistent as possible across devices and brands is good for Google, but it could also help Samsung, which is now looking at maintaining three different Android-based tablet skins.

Google has been pressuring companies to minimize the tweaks to the Android UI (with varying degrees of success) for sometime now. So it balking at Magazine UX should come as no surprise. The more interesting part of the deal reportedly involves Samsung’s in-house apps. For years now the South Korean giant has been promoting its own (often lackluster) products that replicate functions of Google’s core Play Services. For example, WatchON, ChatON and the mSpot-enhanced Media Hub. Sammy has apparently agreed to instead shift focus to the Play store, Newsstand, Hangouts and other Google-built apps. Again, this will bring additional consistency to the Android universe and, considering the size of Samsung’s market share, will broaden the reach of Mountain View’s services.

Courtesy – Engadget

In this example we are using ListUtils.union() function to join two lists

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections.ListUtils;

public class JoinListsExample2 {

public static void main(String[] args) {

List<String> listA = new ArrayList<String>();
listA.add("One");
listA.add("two");
listA.add("three");
listA.add("four");
listA.add("five");

List<String> listB = new ArrayList<String>();
listB.add("Six");
listB.add("Seven");
listB.add("eight");
listB.add("nine");
listB.add("ten");

List<String> listAB = ListUtils.union(listA, listB);

System.out.println("listA : "  + listA);
System.out.println("listB : "  + listB);
System.out.println("listAB : " + listAB);

}

}

How to convert String to InputStream in Java

A simple Java program to convert a String to InputStream, and use BufferedReader to read and display the converted InputStream.

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class StringToInputStreamExample {
public static void main(String[] args) throws IOException {

String line;
String str = "Welcome to Schogini Systems";

// convert String into InputStream
InputStream is = new ByteArrayInputStream(str.getBytes());

// read it with BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(is));

while ((line = br.readLine()) != null) {
System.out.println(line);
}

br.close();
}
}

How to convert array of bytes into File in Java

The Java.io.FileOutputStream can used to convert an array of bytes into a file. In this example, you read a file from “C:\\myfile1.txt”, and convert it into an array of bytes, and write it into another file “C:\\myfile2.txt”.
package com.schogini.arrayByteToFile

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class ArrayOfBytesToFile
{
public static void main ( String[] args )
{
FileInputStream fileInputStream = null;

File file = new File ( "C:\\myfile1.txt" );

byte[] bFile = new byte [ (int) file.length() ];

try {
//convert file into array of bytes
fileInputStream = new FileInputStream ( file );
fileInputStream.read ( bFile );
fileInputStream.close();

//convert array of bytes into file
FileOutputStream fileOuputStream =
new FileOutputStream ( "C:\\myfile2.txt" );
fileOuputStream.write ( bFile );
fileOuputStream.close();

System.out.println ( "Completed" );
} catch ( Exception e ) {
e.printStackTrace();
}
}
}

Android Drag and Drop

Android drag/drop framework allows your users to move data from one View to another View in the current layout using a graphical drag and drop gesture. The framework includes following three important components to support drag & drop functionality:

  • Drag event class:
  • Drag listeners:
  • Helper methods and classes:

The Drag/Drop Process

There are basically four steps or states in the drag and drop process:

  • Started: This event occurs when you start dragging an item in a layout, your application callsstartDrag() method to tell the system to start a drag. The arguments inside startDrag() method provide the data to be dragged, metadata for this data, and a callback for drawing the drag shadow.

    The system first responds by calling back to your application to get a drag shadow. It then displays the drag shadow on the device.

    Next, the system sends a drag event with action type ACTION_DRAG_STARTED to the registered drag event listeners for all the View objects in the current layout.

    To continue to receive drag events, including a possible drop event, a drag event listener must return true, If the drag event listener returns false, then it will not receive drag events for the current operation until the system sends a drag event with action type ACTION_DRAG_ENDED.

  • Continuing: The user continues the drag. System sends ACTION_DRAG_ENTERED action followed by ACTION_DRAG_LOCATION action. to the registered drag event listener for the View where dragging point enters. The listener may choose to alter its View object’s appearance in response to the event or can react by highlighting its View.

    The drag event listener receives a ACTION_DRAG_EXITED action after the user has moved the drag shadow outside the bounding box of the View.

  • Dropped: The user releases the dragged item within the bounding box of a View. The system sends the View object’s listener a drag event with action type ACTION_DROP.
  • Ended: Just after the action type ACTION_DROP, the system sends out a drag event with action type ACTION_DRAG_ENDED to indicate that the drag operation is over.

The DragEvent Class

The DragEvent represents an event that is sent out by the system at various times during a drag and drop operation. This class provides few Constants and important methods which we use during Drag/Drop process.

CONSTANTS

Following are all constants integers available as a part of DragEvent class.

S.N. Constants & Description
1 ACTION_DRAG_STARTED
Signals the start of a drag and drop operation.
2 ACTION_DRAG_ENTERED
Signals to a View that the drag point has entered the bounding box of the View.
3 ACTION_DRAG_LOCATION
Sent to a View after ACTION_DRAG_ENTERED if the drag shadow is still within the View object’s bounding box.
4 ACTION_DRAG_EXITED
Signals that the user has moved the drag shadow outside the bounding box of the View.
5 ACTION_DROP
Signals to a View that the user has released the drag shadow, and the drag point is within the bounding box of the View.
6 ACTION_DRAG_ENDED
Signals to a View that the drag and drop operation has concluded.

METHODS

Following are few important and most frequently used methods available as a part of DragEvent class.

S.N. Constants & Description
1 int getAction()
Inspect the action value of this event..
2 ClipData getClipData()
Returns the ClipData object sent to the system as part of the call to startDrag().
3 ClipDescription getClipDescription()
Returns the ClipDescription object contained in the ClipData.
4 boolean getResult()
Returns an indication of the result of the drag and drop operation.
5 float getX()
Gets the X coordinate of the drag point.
6 float getY()
Gets the Y coordinate of the drag point.
7 String toString()
Returns a string representation of this DragEvent object.

Listening for Drag Event

If you want any of your views within a Layout should respond Drag event then your view either implements View.OnDragListener or setup onDragEvent(DragEvent) callback method. When the system calls the method or listener, it passes to them a DragEvent object explained above. You can have both a listener and a callback method for View object. If this occurs, the system first calls the listener and then defined callback as long as listener returns true.

The combination of the onDragEvent(DragEvent) method and View.OnDragListener is analogous to the combination of the onTouchEvent() and View.OnTouchListener used with touch events in old versions of Android.

Starting a Drag Event

You start with creating a ClipData and ClipData.Item for the data being moved. As part of the ClipDataobject, supply metadata that is stored in a ClipDescription object within the ClipData. For a drag and drop operation that does not represent data movement, you may want to use null instead of an actual object.

Next either you can extend extend View.DragShadowBuilder to create a drag shadow for dragging the view or simply you can use View.DragShadowBuilder(View) to create a default drag shadow that’s the same size as the View argument passed to it, with the touch point centered in the drag shadow.

Example

Following example shows the functionality of a simple Drag & Drop using aView.setOnLongClickListener() event listener along with View.OnDragEventListener().

Step Description
1 You will use Eclipse IDE to create an Android application and name it as DragNDropDemounder a package com.example.dragndropdemo. While creating this project, make sure youTarget SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2 Modify src/MainActivity.java file and add the code to define event listeners as well as a call back methods for the logo image used in the example.
3 Copy image logo.png in res/drawable-* folders. You can use images with different resolution in case you want to provide them for different devices.
4 Modify layout XML file res/layout/activity_main.xml to define default view of the logo images.
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 filesrc/com.example.dragndropdemo/MainActivity.java. This file can include each of the fundamental lifecycle methods.

package com.example.dragndropdemo;

import android.os.Bundle;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipDescription;
import android.util.Log;
import android.view.DragEvent;
import android.view.View;
import android.view.View.DragShadowBuilder;
import android.view.View.OnDragListener;
import android.widget.*;

public class MainActivity extends Activity{
   ImageView ima;
   private static final String IMAGEVIEW_TAG = "Android Logo";
   String msg;

   private android.widget.RelativeLayout.LayoutParams layoutParams;

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

      ima = (ImageView)findViewById(R.id.iv_logo);
      // Sets the tag
      ima.setTag(IMAGEVIEW_TAG);

      ima.setOnLongClickListener(new View.OnLongClickListener() {
         @Override
         public boolean onLongClick(View v) {
            ClipData.Item item = new ClipData.Item((CharSequence)v.getTag());

            String[] mimeTypes = {ClipDescription.MIMETYPE_TEXT_PLAIN};
            ClipData dragData = new ClipData(v.getTag().toString(), 
            mimeTypes, item);

            // Instantiates the drag shadow builder.
            View.DragShadowBuilder myShadow = new DragShadowBuilder(ima);

            // Starts the drag
            v.startDrag(dragData,  // the data to be dragged
            myShadow,  // the drag shadow builder
            null,      // no need to use local data
            0          // flags (not currently used, set to 0)
            );
            return true;
         }
      });

      // Create and set the drag event listener for the View
      ima.setOnDragListener( new OnDragListener(){
         @Override
         public boolean onDrag(View v,  DragEvent event){
         switch(event.getAction())                   
         {
            case DragEvent.ACTION_DRAG_STARTED:
               layoutParams = (RelativeLayout.LayoutParams) 
               v.getLayoutParams();
               Log.d(msg, "Action is DragEvent.ACTION_DRAG_STARTED");
               // Do nothing
               break;
            case DragEvent.ACTION_DRAG_ENTERED:
               Log.d(msg, "Action is DragEvent.ACTION_DRAG_ENTERED");
               int x_cord = (int) event.getX();
               int y_cord = (int) event.getY();  
               break;
            case DragEvent.ACTION_DRAG_EXITED :
               Log.d(msg, "Action is DragEvent.ACTION_DRAG_EXITED");
               x_cord = (int) event.getX();
               y_cord = (int) event.getY();
               layoutParams.leftMargin = x_cord;
               layoutParams.topMargin = y_cord;
               v.setLayoutParams(layoutParams);
               break;
            case DragEvent.ACTION_DRAG_LOCATION  :
               Log.d(msg, "Action is DragEvent.ACTION_DRAG_LOCATION");
               x_cord = (int) event.getX();
               y_cord = (int) event.getY();
               break;
            case DragEvent.ACTION_DRAG_ENDED   :
               Log.d(msg, "Action is DragEvent.ACTION_DRAG_ENDED");
               // Do nothing
               break;
            case DragEvent.ACTION_DROP:
               Log.d(msg, "ACTION_DROP event");
               // Do nothing
               break;
            default: break;
            }
            return true;
         }
      });
   }
}

Following will be the content of res/layout/activity_main.xml file:

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

    <ImageView
		android:id="@+id/iv_logo" 
    	android:layout_width="wrap_content" 
    	android:layout_height="wrap_content"
    	android:src="@drawable/logo"
    	android:contentDescription="@string/drag_drop"  />

</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">DragNDropDemo</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="drag_drop">Click on the image to drag and drop</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.guidemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.guidemo.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 DragNDropDemo application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project’s activity files and click Run  icon from the toolbar. Eclipse 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

BufferedReader example in JDK 7

In JDK 7, can use new feature try-with-resources to close file automatically.

package com.schogini.bufferedReaderExample;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReaderExample {

public static void main(String[] args) {

try (BufferedReader br = new BufferedReader(new FileReader("C:\\myfile.txt")))
{

String sCurrentLine;

while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}

} catch (IOException e) {
e.printStackTrace();
}

}
}

Simple use of Shared Preference

Here is a very simple implementation of Shared Preferences in Android Development.

Step 1:   Create a Shared preferences object prefs from file “com.sagar.prefs”.

SharedPreferences prefs = getSharedPreferences(“com.sagar.prefs”, Context.MODE_PRIVATE );// this code is enough for creating the file and getting its object.

Step 2. Write some value in the shared preferences

copy this method in your code:

private void setPreferences(String key_str, String value_str){

          Editor editor = prefs.edit();
           editor.putString(key_str, value_str);
           editor.commit();
}

and use this to save any value in shared preferences  setPreferences(“name”, “value”); // this will save the value for this name.

Step 3: Get data from shared preferences:

String str = prefs.getString(“name”, “d”);  // where d is the default value which will be return if there is no value for the given “name” in the shared preferences.

Android User Interface

The basic building block for user interface is a View object which is created from the View class and occupies a rectangular area on the screen and is responsible for drawing and event handling. View is the base class for widgets, which are used to create interactive UI components like buttons, text fields, etc.

The ViewGroup is a subclass of View and provides invisible container that hold other Views or other ViewGroups and define their layout properties.

At third level we have different layouts which are subclasses of ViewGroup class and a typical layout defines the visual structure for an Android user interface and can be created either at run time usingView/ViewGroup objects or you can declare your layout using simple XML file main_layout.xml which is located in the res/layout folder of your project.

This tutorial is more about creating your GUI based on layouts defined in XML file. A layout may contain any type of widgets such as buttons, labels, textboxes, and so on. Following is a simple example of XML file having LinearLayout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="fill_parent" 
	android:layout_height="fill_parent" 
	android:orientation="vertical" >
	<TextView android:id="@+id/text"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:text="This is a TextView" />
	<Button android:id="@+id/button"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:text="This is a Button" />

	<!-- More GUI components go here  -->

</LinearLayout>

Once your layout is defined, you can load the layout resource from your application code, in yourActivity.onCreate() callback implementation as shown below:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

Android Layout Types

There are number of Layouts provided by Android which you will use in almost all the Android applications to provide different view, look and feel.

S.N. Layout & Description
1 Linear Layout
LinearLayout is a view group that aligns all children in a single direction, vertically or horizontally.
2 Relative Layout
RelativeLayout is a view group that displays child views in relative positions.
3 Table Layout
TableLayout is a view that groups views into rows and columns.
4 Absolute Layout
AbsoluteLayout enables you to specify the exact location of its children.
5 Frame Layout
The FrameLayout is a placeholder on screen that you can use to display a single view.
6 List View
ListView is a view group that displays a list of scrollable items.
7 Grid View
GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid.

Layout Attributes

Each layout has a set of attributes which define the visual properties of that layout. There are few common attributes among all the layouts and their are other attributes which are specific to that layout. Following are common attributes and will be applied to all the layouts:

Attribute Description
android:id This is the ID which uniquely identifies the view.
android:layout_width This is the width of the layout.
android:layout_height This is the height of the layout
android:layout_marginTop This is the extra space on the top side of the layout.
android:layout_marginBottom This is the extra space on the bottom side of the layout.
android:layout_marginLeft This is the extra space on the left side of the layout.
android:layout_marginRight This is the extra space on the right side of the layout.
android:layout_gravity This specifies how child Views are positioned.
android:layout_weight This specifies how much of the extra space in the layout should be allocated to the View.
android:layout_x This specifies the x-coordinate of the layout.
android:layout_y This specifies the y-coordinate of the layout.
android:layout_width This is the width of the layout.
android:layout_width This is the width of the layout.
android:paddingLeft This is the left padding filled for the layout.
android:paddingRight This is the right padding filled for the layout.
android:paddingTop This is the top padding filled for the layout.
android:paddingBottom This is the bottom padding filled for the layout.

Here width and height are the dimension of the layout/view which can be specified in terms of dp (Density-independent Pixels), sp ( Scale-independent Pixels), pt ( Points which is 1/72 of an inch), px( Pixels), mm ( Millimeters) and finally in (inches).

You can specify width and height with exact measurements but more often, you will use one of these constants to set the width or height:

  • android:layout_width=wrap_content tells your view to size itself to the dimensions required by its content.
  • android:layout_width=fill_parent tells your view to become as big as its parent view.

Gravity attribute plays important role in positioning the view object and it can take one or more (separated by ‘|’) of the following constant values.

Constant Value Description
top 0×30 Push object to the top of its container, not changing its size.
bottom 0×50 Push object to the bottom of its container, not changing its size.
left 0×03 Push object to the left of its container, not changing its size.
right 0×05 Push object to the right of its container, not changing its size.
center_vertical 0×10 Place object in the vertical center of its container, not changing its size.
fill_vertical 0×70 Grow the vertical size of the object if needed so it completely fills its container.
center_horizontal 0×01 Place object in the horizontal center of its container, not changing its size.
fill_horizontal 0×07 Grow the horizontal size of the object if needed so it completely fills its container.
center 0×11 Place the object in the center of its container in both the vertical and horizontal axis, not changing its size.
fill 0×77 Grow the horizontal and vertical size of the object if needed so it completely fills its container.
clip_vertical 0×80 Additional option that can be set to have the top and/or bottom edges of the child clipped to its container’s bounds. The clip will be based on the vertical gravity: a top gravity will clip the bottom edge, a bottom gravity will clip the top edge, and neither will clip both edges.
clip_horizontal 0×08 Additional option that can be set to have the left and/or right edges of the child clipped to its container’s bounds. The clip will be based on the horizontal gravity: a left gravity will clip the right edge, a right gravity will clip the left edge, and neither will clip both edges.
start 0×00800003 Push object to the beginning of its container, not changing its size.
end 0×00800005 Push object to the end of its container, not changing its size.

View Identification

A view object may have a unique ID assigned to it which will identify the View uniquely within the tree. The syntax for an ID, inside an XML tag is:

android:id="@+id/my_button"

Following is a brief description of @ and + signs:

  • The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and expand the rest of the ID string and identify it as an ID resource.
  • The plus-symbol (+) means that this is a new resource name that must be created and added to our resources. To create an instance of the view object and capture it from the layout, use the following:
Button myButton = (Button) findViewById(R.id.my_button);
Page 1 of 6412345...102030...Last »
We Can Build Your App for You. Lets Get Started !