Sunday, 21 December 2014

Intent Types

 Following are 2 types of intents

1.Explicit Intents

used to call a specific component. When you know which component you want to launch and you do not want to give the user free control over which component to use. For example, you have an application that has 2 activities. Activity A and activity B. You want to launch activity B from activity A. In this case you define an explicit intent targeting activityB and then use it to directly call it.

2.Implicit Intents

used when you have an idea of what you want to do, but you do not know which component should be launched. Or if you want to give the user an option to choose between a list of components to use. If these Intents are send to the Android system it searches for all components which are registered for the specific action and the data type. If only one component is found, Android starts the component directly. For example, you have an application that uses the camera to take photos. One of the features of your application is that you give the user the possibility to send the photos he has taken. You do not know what kind of application the user has that can send photos, and you also want to give the user an option to choose which external application to use if he has more than one. In this case you would not use an explicit intent. Instead you should use an implicit intent that has its action set to ACTION_SEND and its data extra set to the URI of the photo.

An explicit intent is always delivered to its target, no matter what it contains; the filter is not consulted. But an implicit intent is delivered to a component only if it can pass through one of the component's filters 



Examples:

Explicit Intent:  

          Intent explicitIntent = new Intent(ActivityA.this,ActivityB.class);
          startActivity(explicitIntent);




 Implicit Intent:

              Intent contacts = new Intent();
              contacts.setAction(android.content.Intent.ACTION_VIEW);
              contacts.setData(People.CONTENT_URI);
              startActivity(contacts);

            

What is Intent in Android?

An Intent is exactly what it describes. It's an "intention" to do an action.

An Intent is basically a message to say you did or want something to happen. Depending on the intent, apps or the OS might be listening for it and will react accordingly.

Think of it as a blast email to a bunch of friends, in which you tell your friend John to do something. The other folks will ignore the email, but John will react to it.

To listen for an intent (like the phone ringing, or an SMS is received), you implement a broadcast receiver.

If you want to fire off an intent to do something, like pop up the dialer, you fire off an intent saying you will.

Example:

After writing a single activity, there comes a need to transition to another activity to perform another task either with or without information from the first activity.

Android platform allows transition by means of Intent Interface.

In this example there are two activities - IntentActionDemo.java and IntentA.java that both extend the super class Activity. Do not forget to declare any new activity in the AndroidManifest.xml with permission.

I have introduced buttons in both activities which have a listener to allow an intent to transition from one intent to the other activity and vis-versa.
Simple intent example;
Note that optional step 2 was not used in our demo.
Step 1: Intent i = new Intent(context, NameOfClassToTransitionTo.class)

Step 2:(Optional)Intents can take various forms that make it even carry data in key/name pairs iei.putExtra("key1", "My first Info")
i.putExtra("key2", "My second Info")

Step 3: startActivity(i)



IntentActionDemo.java
Code:


package com.intent.example;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class IntentActionDemo extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        Button button = (Button) findViewById(R.id.intentButton);
        button.setOnClickListener(this);
        
    }

    @Override
    public void onClick(View src) {
      Intent i = new Intent(this, IntentA.class);
      startActivity(i);
    }
}


IntentA.java

Code:


package 
com.intent.example;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class IntentA extends Activity implements OnClickListener{

    @Override
    public void onClick(View src) {
      Intent i = new Intent(this, IntentActionDemo.class);
      startActivity(i);
    }
   
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.intenta);
       
        Button button = (Button) findViewById(R.id.ButtonIntentA);
        button.setOnClickListener(this);
    }
}


AndroidManifest.xml
Code:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="
com.intent.example"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".IntentActionDemo"
                  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="IntentA"></activity>
</application>
    <uses-sdk android:minSdkVersion="3" />

</manifest>


string.xml

Code:


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello</string>
    <string name="app_name">IntentActionDemo</string>
<string name="IntentA">Click Next intent</string>
<string name="world">World!</string>
<string name="Intent0">Click to Previous Intent</string>
</resources>


main.xml
Code:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    android:textSize="18sp"/>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/intentButton" android:text="@string/IntentA"></Button>
</LinearLayout>


intenta.xml
Code:


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

<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/TextViewWorld" android:text="@string/world" android:textSize="18sp"></TextView>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/ButtonIntentA" android:text="@string/Intent0"></Button>
</LinearLayout>


How to open a PDF via Intent from SD card

  By starting activity with intent of ACTION_VIEW, for "application/pdf", we can ask the installed       PDF ready to open PDF file from our app.


File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf");

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);

Monday, 21 April 2014

Navigation Menu/Android Sliding Menu Sample

Hello All,

By this post I am gonna explain about how to integrate the Navigation Drawer like Facebook, Gmail, Google+ apps.

First you have to know whats mean by Navigation Drawer:

1. Navigation Drawer: 


The navigation drawer is a panel that displays the app’s main navigation options on the left edge of the screen. It is hidden most of the time, but is revealed when the user swipes a finger from the left edge of the screen or, while at the top level of the app, the user touches the app icon in the action bar.

you can get more info about this here. Good news is its now available in the SupportLibrary itself. 


How to Create the Drawer Layout ? 


To add a navigation drawer, declare your user interface with aDrawerLayout object as the root view of your layout. Inside theDrawerLayout, add one view that contains the main content for the screen (your primary layout when the drawer is hidden) and another view that contains the contents of the navigation drawer.

For example, the following layout uses a DrawerLayout with two child views: a FrameLayout to contain the main content (populated by a Fragment at runtime), and a ListView for the navigation drawer.


<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <!-- The main content view -->
    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <!-- The navigation drawer -->
    <ListView android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#111"/>
</android.support.v4.widget.DrawerLayout>

Here is the code to do in MainActivity.java

public class MainActivity extends Activity {
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;
    ...

    public void onCreate(Bundle savedInstanceState) {
        ...

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerToggle = new ActionBarDrawerToggle(
                this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                R.drawable.ic_drawer,  /* nav drawer icon to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description */
                R.string.drawer_close  /* "close drawer" description */
                ) {

            /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                getActionBar().setTitle(mTitle);
            }

            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                getActionBar().setTitle(mDrawerTitle);
            }
        };

        // Set the drawer toggle as the DrawerListener
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Pass the event to ActionBarDrawerToggle, if it returns
        // true, then it has handled the app icon touch event
        if (mDrawerToggle.onOptionsItemSelected(item)) {
          return true;
        }
        // Handle your other action bar items...

        return super.onOptionsItemSelected(item);
    }

    ...
}


You can load multiple no of Fragments into the NavigationDrawer like as follow 


/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new FindPeopleFragment();
break;
case 2:
fragment = new PhotosFragment();
break;
case 3:
fragment = new CommunityFragment();
break;
case 4:
fragment = new PagesFragment();
break;
case 5:
fragment = new WhatsHotFragment();
break;

default:
break;
}

if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();

// update selected item and title, then close the drawer
// mDrawerList.setItemChecked(position, true);
//mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}


}

Thursday, 26 December 2013

Android Asyc Task Example

Hi all ,

By this post we are going to learn about  Asyc Task.

The AsyncTask executes everything in doInBackground() inside of another thread, which does not have access to the GUI where your views are.

preExecute() and postExecute() offer you access to GUI before and after the heavy lifting occurs in this new thread, you can even pass the result of the long operation to postExecute() to then show any results of processing.

See these lines where you later yout TextView:
TextView txt = (TextView) findViewById(R.id.output);
txt.setText("Executed");

put them in PostExecute()
You will then see you TextView text update after the doInBackground completes.



Here is the sample for Async Task. 

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.System;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;

public class AsyncTaskActivity extends Activity implements OnClickListener {

    Button btn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn = (Button) findViewById(R.id.button1);
        // because we implement OnClickListener we only have to pass "this"
        // (much easier)
        btn.setOnClickListener(this);
    }

    public void onClick(View view) {
        // detect the view that was "clicked"
        switch (view.getId()) {
        case R.id.button1:
            new LongOperation().execute("");
            break;
        }
    }

    private class LongOperation extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {
            TextView txt = (TextView) findViewById(R.id.output);
            txt.setText("Executed"); // txt.setText(result);
            // might want to change "executed" for the returned string passed
            // into onPostExecute() but that is upto you
        }

        @Override
        protected void onPreExecute() {}

        @Override
        protected void onProgressUpdate(Void... values) {}
    }

}

Android how to create the custom Type face.

Hi all,

By this post we are going to learn about how to create/set the custom type face to use particular language or .ttf files in our application.

Just write this line in your application file or needed activity. Its depends upon the project requirement.

 Typeface tamilfont = Typeface.createFromAsset(getAssets(),
"fonts/Bamini.ttf");


Then set the type face to the textview as like the below line. 


textViewTopbar.setTypeface(AthichudiApplication.tamilfont);


Wednesday, 17 July 2013

Android Avoid Showing Last Charecter Typed in PassWord Filed.

Hello Frieds,
By this post we are going to learn about how to Avoid Showing Last Charecter Typed in PassWord Filed.

Use the following code to achieve this.

 To show text as password we should use the following attribute in EditText : android:inputType="textPassword"

To avoid showing last text typed should use the following attribute in Edittext :

android:password="true"

So Completed Edit text will be look like this.

<EditText android:textSize="18.0sp" android:id="@+id/mypassword" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="10.0dip" android:layout_marginRight="10.0dip" android:password="true" android:inputType="textPassword" />

Hope this helps. Happy Coding.

Monday, 8 July 2013

Android PopupWindow example in Listview.

Hi All ,

By this post we are going to learn about how to use Android Popup Window in listview, gridview, Your Custom Alert etc.

Whats mean by Popup Window:
 android.widget.PopupWindow  can be used to display an arbitrary view. The popup window is a floating container that appears on top of the current activity.

I am going to explain how to use popupwindow in list view. For example in listview item you have details button means you can use this popupwindow to show those details in this window. Lets see how to do it.

Step 1 : Main.xml

You can use either list view or any other Composite listviews:

<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" >

    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="right"
        android:orientation="vertical"
        >
      <ListView
          android:id="@+id/listView1"
          android:layout_width="match_parent"
          android:layout_height="wrap_content" >
      </ListView>

      </LinearLayout>

</RelativeLayout>

Step 2 : listviewchild.xml
You can design your own custom view.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linear_item"
    android:layout_width="fill_parent"
    android:layout_height="100dp"   
   
  android:gravity="right"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="15dp"       
        android:layout_toRightOf="@+id/textview_name"
        android:src="@drawable/ic_launcher" />
   
</RelativeLayout>


Step 3 :

Your MainActivity.java

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

public class MainActivity extends Activity {

    String TAG = "MainActivity.java";

    String popUpContents[];
    PopupWindow popupWindowDogs;  
    ListView listView1;

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

        listView1=(ListView)findViewById(R.id.listView1);
        listView1.setAdapter(new MyAddapter(MainActivity.this)); // binding the list view.
        /*
         * initialize pop up window items list
         */
      
        // add items on the array dynamically
        // format is Company Name:: ID
        List<String> dogsList = new ArrayList<String>();
        dogsList.add("Samsung");
        dogsList.add("Google");
        dogsList.add("Yahoo");
        dogsList.add("Microsoft");

        // convert to simple array
        popUpContents = new String[dogsList.size()];
        dogsList.toArray(popUpContents);

        /*
         * initialize pop up window
         */
        popupWindowDogs = popupWindowDogs();

      
    }

    /*
     *
     */
    public PopupWindow popupWindowDogs() {

        // initialize a pop up window type
        PopupWindow popupWindow = new PopupWindow(this);

        // the drop down list is a list view
        ListView listViewDogs = new ListView(this);
      
        // set our adapter and pass our pop up window contents
        listViewDogs.setAdapter(dogsAdapter(popUpContents));
      
        // set the item click listener
        listViewDogs.setOnItemClickListener(new DogsDropdownOnItemClickListener());

        // some other visual settings
        popupWindow.setFocusable(true);
        popupWindow.setWidth(250);
        popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
      
        // set the list view as pop up window content
        popupWindow.setContentView(listViewDogs);

        return popupWindow;
    }

    /*
     * adapter where the list values will be set
     */
    private ArrayAdapter<String> dogsAdapter(String dogsArray[]) {

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dogsArray) {

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {

                // setting the ID and text for every items in the list
                          
                String text = getItem(position);              

                // visual settings for the list item
                TextView listItem = new TextView(MainActivity.this);

                listItem.setText(text);
                listItem.setTag(position);
                listItem.setTextSize(22);
                listItem.setPadding(10, 10, 10, 10);
                listItem.setTextColor(Color.WHITE);
              
                return listItem;
            }
        };
      
        return adapter;
    }
}

Step 4:
Your Adapter class


class MyAddapter extends BaseAdapter {
        Context rContext;
        private LayoutInflater rInflater;
        private Activity activity;

        public MyAddapter(Context c) {

            rInflater = LayoutInflater.from(c);

            rContext = c;

        }     
              
        public MyAddapter(Activity imagebinding) {
            // TODO Auto-generated constructor stub

            activity = imagebinding;       
           
            rContext = imagebinding;
            rInflater = LayoutInflater.from(imagebinding);
            rContext = imagebinding;
            rInflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       

           
        }
       
        @Override
        public int getCount() {
            // TODO Auto-generated method stub   
           
                       
            return 10;
        }

        @Override
        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public View getView(final int position, View convertView,
                ViewGroup parent) {
            // TODO Auto-generated method stub
            convertView = rInflater.inflate(R.layout.child, null);
            final MyDat mydat = new MyDat();   
           
            mydat.imageView1=(ImageView)convertView.findViewById(R.id.imageView1);
            mydat.imageView1.setOnClickListener(new OnClickListener() {
               
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    popupWindowDogs.showAsDropDown(v, -5, 0);
                   
                }
            });
           
            return convertView;
        }
                             
        class MyDat {
           
                   
           
            ImageView imageView1;
           
           
        }

    }
 
Step 5 :
Your Popup Windows items Click listener





You can use this if you want proceed furtherly for activity transitions.

import android.content.Context;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

public class DogsDropdownOnItemClickListener implements OnItemClickListener {
   
    @Override
    public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {

        // get the context and main activity to access variables
        Context mContext = v.getContext();
        MainActivity mainActivity = ((MainActivity) mContext);
       
        // add some animation when a list item was clicked
        Animation fadeInAnimation = AnimationUtils.loadAnimation(v.getContext(), android.R.anim.fade_in);
        fadeInAnimation.setDuration(10);
        v.startAnimation(fadeInAnimation);
       
        // dismiss the pop up
        mainActivity.popupWindowDogs.dismiss();
       
        // get the text and set it as the button text
       
        Toast.makeText(mContext, "Selected Positon is: " + arg2, 100).show();
       
       
    }

}
Screen Shots: 






Hope this helps you. Comments are welcome. Happy coding.       




    


Friday, 5 July 2013

Android How to Set up google map api v2


Hi Friends ,

By this post we are going to learn about how to set up Android Google map V2 .

Important thing in this set up is "Get your SHA1 fingerprint " . So we will see the latest and simplest way .

1. Just  Create one New Android Application .with Latest Google Map Api as the Target.

2.        Import Google Play Services Lib  . Which will be available in below path of your Android SDK

android-sdk\extras\google\google_play_services\libproject\google-play-services_lib

3. Add google play service lib to your project by right clicking on your project  properties\android and you will see little button on the buttom-right "add". Just add the google play service lib and click ok. like below image.

 4.  How to get SHA1 fingerprint KEY
Go to:
Window\Preferences   Android\Build    
 find your SHA1 fingerprint and copy that.See the Reference Image . Copy the SHA1 finger print for future use.

5.  Go to Google Apis Console Window.  See below for Reference.
6.Create New project .See below for Reference.
 

7. Activate the option "Google Maps Android API V2"  See below for Reference. 
8. Click "Create New Android Key" . You will get below Popup.



9. Enter your SHA1 fingerprint(Which you have saved earlier )  followed by '  ; ' and your application package name.

like this . 40:8F:34:9C:F2:FC:7A: ; com.rajesh.map.sample

After pasting click the Create button.

10. The following permission are Must for Map v2 project.

 <permission
        android:name="com.example.osman.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>
<uses-permission android:name="com.example.osman.permission.MAPS_RECEIVE"/>
 
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<!-- The following two permissions are not required to use
     Google Maps Android API v2, but are recommended. -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
 
<uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/> 
 
Along with the you must add the below lines  
      <meta-data
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="YOUR_KEY"/>// the key is which you have got from step 9. 

Add above line right before the </application> tag 


Hope this helps you.  Happy Coding .


Android How to Get Address From Google Services.

Hi All,
By this post we are going to learn about how to get Address from Google Services instead of Default Geo Coder.

Step 1. 
For this we need Internet Permission.

<uses-permission android:name="android.permission.INTERNET"/>

Step 2.
Here is the Class to get The Address from Google Services.


import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


public class FormattedAddress {

    public  String getAddress(String Source, String Destination) {

       
       
        StringBuilder stringBuilder = new StringBuilder();
        String duration_final_value = "";
       
        try {

            Source = Source.replaceAll(" ", "%20");
            Destination = Destination.replaceAll(" ", "%20");

            HttpPost httppost = new HttpPost(
                    "http://maps.googleapis.com/maps/api/geocode/json?latlng="+Source+","+Destination+"&sensor=false");//&mode=walking,driving
            HttpClient client = new DefaultHttpClient();
            HttpResponse response;
            stringBuilder = new StringBuilder();

            response = client.execute(httppost);
            HttpEntity entity = response.getEntity();
            InputStream stream = entity.getContent();
            int b;
            while ((b = stream.read()) != -1) {
                stringBuilder.append((char) b);
            }
        } catch (ClientProtocolException e) {         
        } catch (IOException e) {
        }

       
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject = new JSONObject(stringBuilder.toString()); // first we need to get the full json object which google returns   
           
            JSONArray routes_Array = jsonObject.getJSONArray("results"); // in that first we need to go into the routes array
           
            JSONObject routes_object = (JSONObject) routes_Array.get(0); // in that we need first item
            duration_final_value= routes_object.getString("formatted_address").toString();  // then go into the legs array
           
            System.out.println(" Address " + duration_final_value);
               

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

        return duration_final_value;
    }
}

Step 3:
Just call the above public method from your activity like below by passing the Latitude and Longitude

              FormattedAddress tel=new FormattedAddress();
            foundAddress= tel.getAddress(String.valueOf(latitude), String.valueOf(longitude));
            here latitude, longitude are long values.

hope this helps you.
Happy Coding.

Thursday, 4 July 2013

Custom Font Text view and Button for Android.

Hi All,

By this post we are going to learn about how to implement the custom fornt for textviews and Buttons.  I am going to teach you the very simple method to do it.


Step 1.

Use this class for Custom Font Text view style.
 Download your ttf file and paste it in your assests folder.

import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;

public class CustomFontTextView extends TextView {

    public CustomFontTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public CustomFontTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CustomFontTextView(Context context) {
        super(context);
        init();
    }

    private void init() {
        Typeface tf = Typeface.createFromAsset(getContext().getAssets(),
                                            "your font.ttf");
        setTypeface(tf);
    }

}

Step 2 

then define your text view like below.

<com.example.customfont.CustomFontTextView
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content" 
                        android:text="Custom Font Test"
                        android:textStyle="normal" />

For Button  Your Custom Class should entends Button instead of Text View.
So your code should be something like below.


import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.Button;
import android.widget.TextView;

public class CustomFontButton extends Button {

    public CustomFontButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public CustomFontButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CustomFontButton(Context context) {
        super(context);
        init();
    }

    private void init() {
        Typeface tf = Typeface.createFromAsset(getContext().getAssets(),
                                               "Roboto-Light.ttf");
        setTypeface(tf);
    }

}


There is no need to mention your custom font TextView/Button  any where else . This will work fine. Happy coding.