Thursday, 12 December 2013

How to get user location in android.

Here we learn how to get user location , how to get latitude and longitude and also the address.


As there are two ways by which we can get user location :
  1. Using GPS
  2. Using Network

Pros and Cons:

  • GPS is most accurate, it quickly consumes battery power, and doesn't return the location as quickly as users want.
  • Network Location Provider determines user location using cell tower and Wi-Fi signals, providing location information in a way that works indoors and outdoors, responds faster, and uses less battery power.
Here we get location using network provider. Later on we will discuss about how to get location using GPS.


In order to get location we use the "LocationManager" class by calling "requestLocationUpdates()".
We also need to implement the "LocationListener" interface. This provide us the latitude and longitude.
If you want to get the location by name , use Geocoder class . In this class we pass the latitude and longitude and the address of that position.
To get the location in application , we need to add following permissions to the AndroidMainfest.xml file.
ACCESS_COARSE_LOCATION:
Allows an app to access approximate location derived from network location sources such as cell towers and Wi-Fi.
ACCESS_FINE_LOCATION:
Allows an app to access precise location from location sources such as GPS, cell towers, and Wi-Fi.
INTERNET:
Allows applications to open network sockets


Create a project with the following details:
  • ProjectName: LocationDemo
  • PackageNamesat.tuts4mobile.locationdemo
  • ActivityNameMainActivity
In the MainActivity.java file, copy the following code

package sat.tuts4mobile.locationdemo;

import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity implements LocationListener{

    protected LocationManager locationManager;
    TextView text;
    String data = "";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        text = (TextView) findViewById(R.id.textview1);
            
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
        
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        String addressline = "";
        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        Geocoder geocoder = new Geocoder(MainActivity.this,Locale.getDefault());
        try {
            
            List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
            if(addresses.size() ==  1)
            {
                Address address = addresses.get(0);
                String aline = "";
                for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
                {
                    aline = aline + address.getAddressLine(i) + "\n";
                }
                addressline = "Address Line : " + aline ;
                            
            }
            
        } catch (Exception e) {
            // TODO: handle exception
        }
        String temp = "Latitude:" + location.getLatitude() + "\nLongitude:" + location.getLongitude() + "\n" + addressline + "\n";
        data = data + temp;
        text.setText(data);
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
        
    }

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

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

}

In the activity_main.xml file, copy the following code:

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

    <ScrollView
        android:id="@+id/sl"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/textview1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/hello_world" />
    </ScrollView>

</RelativeLayout>

In the AndroidMainfest.xml file, copy the following code:

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="14" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="sat.tuts4mobile.locationdemo.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>
    
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET"/>

</manifest>

Note:
Please test this application in real device(mobile phone) , not in emulator.
If you are running this Android app with emulator, you need to send the latitude and longitude explicitly for the emulator. How to send latitude and longitude to android emulator -
  1. Open DDMS perspective in Eclipse (Window -> Open Perspective)
  2. Select your emulator device
  3. Select the tab named emulator control
  4. In ‘Location Controls’ panel, ‘Manual’ tab, give the Longitude and Latitude as input and ‘Send’.
When you run the application you see the following screens:

After some time when location changes , its gives you new location details.


Saturday, 31 August 2013

Acitvity LifeCycle of Android Application


This tutorial explains how android activity lifecycle works. Activity is a window that contains the user interface of your application.


To create an activity your class need to extends Activty base class.An Application has more than on activity . Activity base class contains events that governs the life cycle of an activity.

  • onCreate () : Called when the activity is first created.
  • onStart(): Called when the activity become visible to the user.
  • onResume(): Called when the activity start interacting with the user.
  • onPause(): Called when the current activity is being paused and the previous activity is being resumed.
  • onStop(): Called when the activity is no longer visible to the user.
  • onDestroy(): Called before the activity is destroyed by the system.
  • onRestart(): Called when the activity has been stoped and is restarting again.



Step 1:
Create a project with the following details:
ProjectName      :            LifeCycle
PackageName    :            sat.tuts4mobile.lifecycle
ActivityName        :                LifeCycleActivity  

Step 2:
In the LifeCycleActivity.java file , add the following code:

package sat.tuts4mobile.lifecycle;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class LifeCycleActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        Toast.makeText(LifeCycleActivity.this,"ON CREATE", Toast.LENGTH_SHORT).show();
       
    }
   
    @Override
    protected void onStart() {
       // TODO Auto-generated method stub
       super.onStart();
      
        Toast.makeText(LifeCycleActivity.this,"ON START", Toast.LENGTH_SHORT).show();
    }
   
    @Override
    protected void onResume() {
       // TODO Auto-generated method stub
       super.onResume();
   
        Toast.makeText(LifeCycleActivity.this,"ON RESUME", Toast.LENGTH_SHORT).show();

    }
   
    @Override
    protected void onPause() {
       // TODO Auto-generated method stub
       super.onPause();
   
        Toast.makeText(LifeCycleActivity.this,"ON PAUSE", Toast.LENGTH_SHORT).show();

    }
   
    @Override
    protected void onRestart() {
       // TODO Auto-generated method stub
       super.onRestart();
      
        Toast.makeText(LifeCycleActivity.this,"ON RESTART", Toast.LENGTH_SHORT).show();

    }
   
    @Override
    protected void onStop() {
       // TODO Auto-generated method stub
       super.onStop();
      
        Toast.makeText(LifeCycleActivity.this,"ON STOP", Toast.LENGTH_SHORT).show();

    }
   
    @Override
    protected void onDestroy() {
       // TODO Auto-generated method stub
       super.onDestroy();
      
        Toast.makeText(LifeCycleActivity.this,"ON DESTROY", Toast.LENGTH_SHORT).show();

    }
   
}


Step 3:
When you run the following code , you see when the application starts there are three toast messages comes after one another.
First is ON CREATE , second is ON START and third is ON RESUME.

When you press the home button from the emulator , ON PAUSE and ON STOP methods call.

And when you opens the application again ON RESTART , ON START and ON RESUME methods call.

And in last when you press the back button from emulator , ON PAUSE , ON STOP and ON DESTROY method calls

Click here to download source code of application.

Monday, 26 August 2013

How to use SharedPreference to store information in key-value pair in Android.


This tutorial explains how to store small amount of information using SharedPreferences APIs, and how to retrieve their values.


Here we take an example of login form. When user enter their login credentials, and checked the checkbox (i.e. Remember), the credentials store in the application, and when user opens that application again, user not need to enter their login information again. To store information we write:


SharedPreferences preferences = getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("username", username.getText().toString());
editor.putString("password", password.getText().toString());
editor.putString("logged", "logged");
editor.commit();

Here we set Context.MODE_PRIVATE, so the file is accessible by only your application.

If you want to reset your preferences .

SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();


Saturday, 8 December 2012

Android ListView with image and text (using BaseAdapter)

This tutorial is about creating a ListView which contains image and text as listitem .Here we create a custom listview item  by extend BaseAdapter class.

Following are the steps  to create a project.

Step 1:
Create a project with the following details:
ProjectName     :               CustomListView
PackageName    :               sat.tuts4mobile.customlistview
ActivityName     :               ListViewActivity  

Step 2:
Paste the following code in main.xml .
This is a main xml layout file which contains a listview.

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

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

Step 3:
Create a new xml file name listlayout.xml which is used for create a listitem layout .
Paste this code in this 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" >
      
       <LinearLayout
        android:id="@+id/ll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="2dip"
        android:background="#336699" >

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="50dip"
            android:layout_height="50dip"
            android:src="@drawable/ic_launcher" />
             
              <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dip"
            android:layout_marginTop="8dip"
            android:text="Medium Text"
            android:textAppearance="?android:attr/textAppearanceMedium" />

    </LinearLayout>

</LinearLayout>

Step 4:
Create a new class name ListItemDetails which is used as a setter or getter .
Paste this code in this file:

package sat.tuts4mobile.customlistview;
public class ListItemDetails {
      
       private String name;
       private int image;
      
       public String getName()
              {
              return name;
              }
       public void setName(String name)
              {
              this.name = name;
              }
       public int getImage()
              {
              return image;
              }
       public void setImage(int image)
              {
              this.image = image;
              }
}

Step 5:
Create a new class name CustomListAdapter extends BaseAdapter to bind data to listview item .
Paste this code in this file:

package sat.tuts4mobile.customlistview;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomListAdapter extends BaseAdapter {
               
                private static ArrayList<ListItemDetails> itemDetailsrrayList;
               
                LayoutInflater layoutInflator;
                String[] countryName;
                int[] countryFlag;
                Context context;
               
public CustomListAdapter(ArrayList<ListItemDetails> result , Context c) {
                                // TODO Auto-generated constructor stub
                                itemDetailsrrayList = result;
                                context = c;
                }

                public int getCount() {
                                // TODO Auto-generated method stub
                                return itemDetailsrrayList .size();
                }

                public Object getItem(int arg0) {
                                // TODO Auto-generated method stub
                                return itemDetailsrrayList .get(arg0);
                }

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

                public View getView(int position, View convertView, ViewGroup parent) {
                                // TODO Auto-generated method stub
                               
        layoutInflator  =    
        LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);                               
        View row = layoutInflator.inflate(R.layout.listlayout, parent,false);
                               
        TextView textview = (TextView) row.findViewById(R.id.textView1);
        ImageView imageview = (ImageView) row.findViewById(R.id.imageView1);

        textview.setText(itemDetailsrrayList .get(position).getName());
        imageview.setImageResource(itemDetailsrrayList .get(position).getImage());

        return (row);
                }
 }

Step 6: 
At last paste this code in ListViewActitivty.java :

package sat.tuts4mobile.customlistview;
import java.util.ArrayList;
import android.app.Activity;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;

public class ListViewActivity extends Activity {
               
                String[] text = { "Afghanistan", "Algeria", "Australia", "Bermuda", "Bhutan", "Canada", "China","India","Japan","Kuwait", "Malaysia", "Mexico" };

                int[] image = { R.drawable.afghanistan, R.drawable.algeria, R.drawable.australia,
            R.drawable.bermuda, R.drawable.bhutan, R.drawable.canada, R.drawable.china,
            R.drawable.india, R.drawable.japan, R.drawable.kuwait, R.drawable.malaysia, R.drawable.mexico };

                ListItemDetails item_details;
                /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        ArrayList<ListItemDetails> result = GetSearchResults();
        ListView lv = (ListView)findViewById(R.id.listView1);
        lv.setAdapter(new CustomListAdapter(result,getApplicationContext()));
       
    }
                private ArrayList<ListItemDetails> GetSearchResults() {
                                // TODO Auto-generated method stub
                                ArrayList<ListItemDetails> results = new ArrayList<ListItemDetails>();
                                 
                                for(int i=0;i<text.length;i++)
                                {
                                                item_detailsnew ListItemDetails();
                                                item_details.setName(text[i]);
                                                item_details.setImage(image[i]);
                                                results.add(item_details);
                                }
                               
                                return results;
                }
}

When you run the project it looks like :