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.

Wednesday 5 June 2013

Android Get Current Location And Address

If you are developing any location based or map application, to get location automatically you can use this.

In this post i have explained about how to switch on and off the GPS from our app. And also have explained about how to stop the location listener update after fetching the location.

You can Find location using either GPS_PROVIDER or NETWORK_PROVIDER

1.  In your AndroidManifest.xml file you have to add the below permissions.

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

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

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

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

above permissions are used to get location and addresses.

2. Your Complete manifest file will be look like below.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.getcurrentlocation"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.getcurrentlocation.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>

3. Your Activity Class

package com.example.getcurrentlocation;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity { 
    TextView textView2,textView3,textView1;
    Button button1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);  

        textView2=(TextView)findViewById(R.id.textView2);// text to show latitude
        textView3=(TextView)findViewById(R.id.textView3);// text to show longitude
        textView1=(TextView)findViewById(R.id.textView1);// text to show addresses
        button1=(Button)findViewById(R.id.button1); // button     

// click the below to get the current location and address.
        button1.setOnClickListener(new OnClickListener() {        

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

                 turnGPSOn(); // method to turn on the GPS if its in off state.
                getMyCurrentLocation();            

            }
        });     

    }

/** Method to turn on GPS **/

    public void turnGPSOn(){
        try
        {    

        String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);   

        if(!provider.contains("gps")){ //if gps is disabled
            final Intent poke = new Intent();
            poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
            poke.addCategory(Intent.CATEGORY_ALTERNATIVE);            poke.setData(Uri.parse("3"));
            sendBroadcast(poke);
        }
        }
        catch (Exception e) {          

        }
    }

// Method to turn off the GPS
    public void turnGPSOff(){
        String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        if(provider.contains("gps")){ //if gps is enabled

            final Intent poke = new Intent();
            poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
            poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
            poke.setData(Uri.parse("3"));
            sendBroadcast(poke);
        }
    } 

    // turning off the GPS if its in on state. to avoid the battery drain.

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        turnGPSOff();
    }

  

    /** Check the type of GPS Provider available at that instance and  collect the location informations
     @Output Latitude and Longitude
    * */
    void getMyCurrentLocation() {   

        LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        LocationListener locListener = new MyLocationListener(); 
         try{gps_enabled=locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}           try{network_enabled=locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}
            //don't start listeners if no provider is enabled

            //if(!gps_enabled && !network_enabled)

                //return false;

            if(gps_enabled){
                locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);             

            }


            if(gps_enabled){
                location=locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

            }         

            if(network_enabled && location==null){

                locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);            

            } 
            if(network_enabled && location==null)    {
                location=locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

            }

        if (location != null) {         

            MyLat = location.getLatitude();
            MyLong = location.getLongitude();
        } else {
            Location loc= getLastKnownLocation(this);
            if (loc != null) { 
                MyLat = loc.getLatitude();
                MyLong = loc.getLongitude();
            }
        }

        locManager.removeUpdates(locListener); // removes the periodic updates from location listener to avoid battery drainage. If you want to get location at the periodic intervals call this method using pending intent.

        try
        {
// Getting address from found locations.
        Geocoder geocoder; 
        List<Address> addresses;
        geocoder = new Geocoder(this, Locale.getDefault());
         addresses = geocoder.getFromLocation(MyLat, MyLong, 1);
        StateName= addresses.get(0).getAdminArea();
        CityName = addresses.get(0).getLocality();
        CountryName = addresses.get(0).getCountryName();
        // you can get more details other than this . like country code, state code, etc.     
        System.out.println(" StateName " + StateName);
        System.out.println(" CityName " + CityName);
        System.out.println(" CountryName " + CountryName);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        textView2.setText(""+MyLat);
        textView3.setText(""+MyLong);
        textView1.setText(" StateName " + StateName +" CityName " + CityName +" CountryName " + CountryName);
    } 

    // Location listener class. to get location.
    public class MyLocationListener implements LocationListener {
        public void onLocationChanged(Location location) {
            if (location != null) {
            }
        }        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub
        }

        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub
        }
    }

  

    private boolean gps_enabled=false;
    private boolean network_enabled=false;
    Location location;
    Double MyLat, MyLong;
    String CityName="";
    String StateName="";
    String CountryName="";


// below method to get the last remembered location. because we don't get locations all the times .At some instances we are unable to get the location from GPS. so at that moment it will show us the last stored location.

    public static Location getLastKnownLocation(Context context)

    {
        Location location = null;
        LocationManager locationmanager = (LocationManager)context.getSystemService("location");
        List list = locationmanager.getAllProviders();
        boolean i = false;
        Iterator iterator = list.iterator();
        do
        {
            //System.out.println("---------------------------------------------------------------------");
            if(!iterator.hasNext())
                break;
            String s = (String)iterator.next();
            //if(i != 0 && !locationmanager.isProviderEnabled(s))
            if(i != false && !locationmanager.isProviderEnabled(s))
                continue;
           // System.out.println("provider ===> "+s);
            Location location1 = locationmanager.getLastKnownLocation(s);
            if(location1 == null)
                continue;
            if(location != null)
            {
                //System.out.println("location ===> "+location);
                //System.out.println("location1 ===> "+location);
                float f = location.getAccuracy();
                float f1 = location1.getAccuracy();
                if(f >= f1)
                {
                    long l = location1.getTime();
                    long l1 = location.getTime();
                    if(l - l1 <= 600000L)
                        continue;
                }
            }
            location = location1;
           // System.out.println("location  out ===> "+location);
            //System.out.println("location1 out===> "+location);
            i = locationmanager.isProviderEnabled(s);
           // System.out.println("---------------------------------------------------------------------");
        } while(true);
        return location;    }}

Source
You can download the source from this link
https://github.com/ItsRajesh4uguys/GetCurrentLocationAndAddress




Hyperlink in Android TextView tutorial

By this post i am  gonna teach about How to set Hyperlink effect in Android Text View.


Design Code (XML)


<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
        android:id="@+id/mywidget"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />
</RelativeLayout>
Activity Code. 

public class MainActivity extends Activity {
   
   

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        TextView tvMessage = (TextView) findViewById(R.id.textview1);
       
        tvMessage.setText(Html.  
                fromHtml("www.google.com"));
        Linkify.addLinks(tvMessage, Linkify.ALL);

 Hope this helps . Happy Coding.

Marquee effect in TextView tutorial

By this post i am gonna teach about How to set Marquee effect in Android Text View.

Design Code (XML)

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
        android:id="@+id/mywidget"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:lines="1"
        android:singleLine="true"
        android:ellipsize="marquee"
        android:fadingEdge="horizontal"
        android:marqueeRepeatLimit="marquee_forever"
        android:scrollHorizontally="true"
        android:textColor="#ff4500"
        android:text="Simple application that shows how to use marquee, with a long text" />
</RelativeLayout>
Activity Code. 
public class TextViewMarquee extends Activity {
    private TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView) this.findViewById(R.id.tv);  
        tv.setSelected(true);  // Set focus to the textview

// in case if you want to do it this in problematically means please use the below lines.
        textview.setText("your long text");
       
textview.setSelected(true);
       
textview.setEllipsize(TruncateAt.MARQUEE);
       
textview.setSingleLine(true);
    }
}
 Hope this helps . Happy Coding.

Wednesday 22 May 2013

Sectioned List View/ List with Headers in Android

In this post we are going to learn about how to create simple sectioned adapter.

 Additionally we should not do any extra ordinary things. Its an ordinary one with one additional task that's it.

 This sample is not like other sample to set just an simple text view alone. You can use Seperate Header design page for section.

 1. Your Main.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" >

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

</LinearLayout>

  2. Your Header.xml  // in this file You can design whatever you want.


<TextView 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/list_header_title" 
    android:layout_width="fill_parent"  
    android:layout_height="wrap_content" 
    android:paddingTop="2dip" 
    android:paddingBottom="2dip" 
    android:background="#008000"
    android:textColor="@android:color/white"
    android:paddingLeft="5dip" 
    style="?android:attr/listSeparatorTextViewStyle" /> 


3. Your List Childs  // As you peoples know this is also your custom.


<?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:descendantFocusability="blocksDescendants"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />
   
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

   

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

</LinearLayout>


your MainActivity.java file



package com.example.mysectionadapter;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {       
   
    ListView listView1;
    Context context;
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.homepage);
       
        context=this;
       
        listView1=(ListView)findViewById(R.id.listView1);// list view finding
        // Adding data to array lists
        ArrayList<String> S1 = new ArrayList<String>();
       
        for (int i = 0; i < 10; i++) {
           
            S1.add("S1 item"+i);
        }
       
ArrayList<String> S2 = new ArrayList<String>();
       
        for (int i = 0; i < 10; i++) {
           
            S2.add("S2 item"+i);
        }
       
ArrayList<String> S3 = new ArrayList<String>();
       
        for (int i = 0; i < 10; i++) {
           
            S3.add("S3 item"+i);
        }
       
       
       
       
        // create our list and custom adapter
        SeparatedListAdapter adapter = new SeparatedListAdapter(this);
        adapter.addSection("Header 1 ", new ListAdapter(context,S1));    // this is your first adapter which contains the data related to first header    
        adapter.addSection("Header 2", new ListAdapterTest(context,S2));// this is your second adapter which contains the data related to first header
        adapter.addSection("Header 3 ", new ListAdapter(context,S3));// this is your third adapter which contains the data related to first header        
       
        // the thing is you can set above three adapters as single adapter.. or to differenciate your every single adapter you can use different adapters.
          //if you use different adapters you can use separate design files it will give different look to your ListView.
        // one more thing everything will work under single Scroll.

       
        listView1.setAdapter(adapter);
       
       
        listView1.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                // TODO Auto-generated method stub
                arg2=arg2-1;
               
                Toast.makeText(context, ""+arg2, 1000).show();  
                System.out.println(" TTTTTTTTTTTT " + arg2);
            }
        });

    }

}



SeparatedListAdapter .java  
// this is the master adapter which binds all the adapters as a single adapter with headers.

package com.example.mysectionadapter;

import java.util.LinkedHashMap;
import java.util.Map;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;

public class SeparatedListAdapter extends BaseAdapter {
   
    public final Map<String,Adapter> sections = new LinkedHashMap<String,Adapter>();
    public final ArrayAdapter<String> headers;
    public final static int TYPE_SECTION_HEADER = 0;
   
    public SeparatedListAdapter(Context context) {

        headers = new ArrayAdapter<String>(context, R.layout.header); // this is the header desing page.

    }
   
    public void addSection(String section, Adapter adapter) {
        this.headers.add(section);
        this.sections.put(section, adapter);
    }
   
    public Object getItem(int position) {
        for(Object section : this.sections.keySet()) {
            Adapter adapter = sections.get(section);
            int size = adapter.getCount() + 1;
           
            // check if position inside this section
            if(position == 0) return section;
            if(position < size) return adapter.getItem(position - 1);

            // otherwise jump into next section
            position -= size;
        }
        return null;
    }

    public int getCount() {
        // total together all sections, plus one for each section header
        int total = 0;
        for(Adapter adapter : this.sections.values())
            total += adapter.getCount() + 1;
        return total;
    }

    public int getViewTypeCount() {
        // assume that headers count as one, then total all sections
        int total = 1;
        for(Adapter adapter : this.sections.values())
            total += adapter.getViewTypeCount();
        return total;
    }
   
    public int getItemViewType(int position) {
        int type = 1;
        for(Object section : this.sections.keySet()) {
            Adapter adapter = sections.get(section);
            int size = adapter.getCount() + 1;
           
            // check if position inside this section
            if(position == 0) return TYPE_SECTION_HEADER; 
            if(position < size) return type + adapter.getItemViewType(position - 1);

            // otherwise jump into next section
            position -= size;
            type += adapter.getViewTypeCount();
        }
        return -1;
    }
   
    public boolean areAllItemsSelectable() {
        return false;
    }

    public boolean isEnabled(int position) {
        return (getItemViewType(position) != TYPE_SECTION_HEADER);
    }
   
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        int sectionnum = 0;
        for(Object section : this.sections.keySet()) {
            Adapter adapter = sections.get(section);
            int size = adapter.getCount() + 1;
           
            // check if position inside this section
            if(position == 0) return headers.getView(sectionnum, convertView, parent); // this is where your header names will get bind. correctly.
            if(position < size) return adapter.getView(position - 1, convertView, parent);

            // otherwise jump into next section
            position -= size;
            sectionnum++;
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

}


Adapter files


for sample purpose i have used two adapters. they are as follows.


package com.example.mysectionadapter;
import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class ListAdapter extends BaseAdapter {
    Context ctx;
    LayoutInflater lInflater;

    ArrayList<String> Datastring=new ArrayList<String>();
   
    public ListAdapter(Context context,ArrayList<String> Items) {
        ctx = context;       
        Datastring.addAll(Items);
        lInflater = (LayoutInflater) ctx
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       
    }

    @Override
    public int getCount() {
        return Datastring.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
       
        if (convertView == null) {
            convertView = (View) lInflater.inflate(R.layout.list, parent, false);           
        }
        TextView text=(TextView)convertView.findViewById(R.id.textView1);
        text.setText(Datastring.get(position));
       
        return convertView;
    }

   
   

}

Adapter file 2



package com.example.mysectionadapter;
import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class ListAdapterTest extends BaseAdapter {
    Context ctx;
    LayoutInflater lInflater;

    ArrayList<String> Datastring=new ArrayList<String>();
   
    public ListAdapterTest(Context context,ArrayList<String> Items) {
        ctx = context;       
        Datastring.addAll(Items);
        lInflater = (LayoutInflater) ctx
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       
    }

    @Override
    public int getCount() {
        return Datastring.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
       
        if (convertView == null) {
            convertView = (View) lInflater.inflate(R.layout.list, parent, false);           
        }
        TextView text=(TextView)convertView.findViewById(R.id.textView1);
        text.setText(Datastring.get(position));
       
        return convertView;
    }

   
   

}

Manifest file . // this is as usual one.



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mysectionadapter"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        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.mysectionadapter.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>


Hope this post will help to some beginners . happy coding.