Thursday, February 7, 2013

Disabling highlight on ListView items on click

If you want list-view for only showing items in android then add following code to your list-view


<ListView
 android:listSelector="@android:color/transparent"
android:cacheColorHint="@android:color/transparent"
/>


By adding above code in XML it disables default color in list-view.

Wednesday, February 6, 2013

Read Primary email id from android

The following code is used for read primary email id from android device

import android.os.Bundle;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;

public class ReadAccount extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.read_account_activity);
        getEmail(this);
    }
    static String getEmail(Context context) {
        AccountManager accountManager = AccountManager.get(context);
        Account account = getAccount(accountManager);

        if (account == null) {
            return null;
        } else {
            return account.name;
        }
    }

    private static Account getAccount(AccountManager accountManager) {
        Account[] accounts = accountManager.getAccountsByType("com.google");
        Account account;
        if (accounts.length > 0) {
            account = accounts[0];    
        } else {
            account = null;
        }
        return account;
    }
}       

If device has multiple account then also above code retrieved email id
You need to add certain permission in to manifest

<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
    <uses-permission android:name="android.permission.READ_OWNER_DATA" />
    <uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />


Tuesday, February 5, 2013

Generate Google map API key Android

Generate Google map API key Android (JDK 1.7)


 For Generating Map Key:

Require debug.keystore which is located in "C:\Users\<username>\.android\debug.keystore".


Open command prompt provide jdk path i.e "C:\Program Files\Java\jdk1.7.0_03\bin" 

command:- cd/ then press enter and type command cd "Program Files\Java\jdk1.7.0_03\bin" press enter. Thats the setting java path for running keytool.

Now enter following command :

keytool -v -list -keystore C:\Users\<username>\.android\debug.keystore
Enter keystore password:-android

Now you have MD5 Certificate fingerprints.

For generating google map key Goto link: Google Maps Android v1 API Key Signup

Enter MD5 fingerprint Generate API key

You will get map key use this in mapview in layout file



Monday, February 4, 2013

Implicitly using the default locale is a common source of bugs

Locale represents a language/country/variant combination. Locales are used to alter the presentation of information such as numbers or dates to suit the conventions in the region they describe.

When you call toLowerCase(), internally toLowerCase(Locale.getDefault()) is getting called.

Calling str.toLowerCase() str.UpperCase without specifying explicit local is common sourse of bug. The reason is that those method uses the current locale of that device ex in Turkish uppercase replacement of "i" is not "I".

You can set locale by using:

Locale.setDefault(new Locale("US"));

You can get locale by using:

Locale loc = Locale.getDefault();

Now you can use custom/default locale:

String class toLowerCase(Locale locale) method example. This example shows you how to use toLowerCase(Locale locale)method.This method Converts all of the characters in this String to lower case using the rules of the given Locale. 

import java.util.Locale;

public class UpperLowerCase
{
    public static void main(String[] args)
    {
        String str = "String to Upper or lower Based on Locale";

        // Get user's default locale
        Locale loc = Locale.getDefault();
        // Convert to lower case
        String s1 = str.toLowerCase(loc);
        // Convert to Upper case
        String s2 = str.toUpperCase(loc);

        System.out.println("old = " + str);
        System.out.println("lowercase = " + s1);
        System.out.println("uppercase= " + s2);
    }
}

Error in running android application: InstrumentationTestRunner

Application does not specify a android.test.InstrumentationTestRunner instrumentation or does not declare uses-library android.test.runner in its AndroidManifest.xml?

This error comes cause you have run application as Android JUnit Test In the Run Configuration:






In the Run Configuration chose Android Application and Run.

Custom Title Bar in Android

For Adding custom Title Bar in Android you should have:

  • Default title bar enabled.
  • Create res->layout->custom_title.xml
  • Adding Code to Activity.
If you are disabled default title bar for adding custom title then this will not work. Activity throws AndroidRuntimeException (You cannot combine custom titles with other title features) so enable Default title bar.

Create custom_title.xml:

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

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:scaleType="fitXY"
        android:src="@drawable/image_title" />

</RelativeLayout>

Add the Following Code to activity:

@Override
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.main);  
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
}

Also you can set title-bar size by adding following line in res->values->styles.xml:

<resources>

    <style name="AppTheme" parent="android:Theme.Black">
        <item name="android:windowTitleSize">35dip</item>
        <item name="android:windowTitleBackgroundStyle">@style/CustomTitleBarBackground</item>
    </style>

    <style name="CustomTitleBarBackground">
        <item name="android:background">#323331</item>
    </style>

</resources>

 And in manifest:

<application
         android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <uses-library android:name="com.google.android.maps" />

        <activity android:name=".Activity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
</application>


That's all Now your activity contains custom title bar.Later you can add/design as per your application requirement.

Reference: How to Create Custom Window Title in Android

Use GPS and Network Provider to Retrieve location

Build an application which retrieve current position But How to switch or use GPS as well as Network provider in application.
There are 3 location providers in Android Which to use  Depend on accuracy and availability of network.

Initialize LocationManager and LocationListener:

LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();

Now Check for GPS. GPS provides most accurate distance.If GPS is enabled then use GPS other wise Network.

if(manager.isProviderEnabled( LocationManager.GPS_PROVIDER))
{
            manager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
 }
else
{
            manager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, mlocListener);
 }

This checks for GPS if enabled then provide accurate distance .


Location listener class is

public class MyLocationListener implements LocationListener
    {
        public void onLocationChanged(Location location)
        {
                     Toast.makeText(getBaseContext(), "Current loc latitute: "+location.getLatitude() +"longitute: "+location.getLongitude(), Toast.LENGTH_LONG).show();
        }

        public void onProviderDisabled(String provider){}

        public void onProviderEnabled(String provider){}

        public void onStatusChanged(String provider, int status, Bundle extras){}
    }

You will get current location Latitude and Longitude.

Android Location Providers – gps, network, passive

There are 3 location providers in Android.


GPS–> (GPS, AGPS): Name of the GPS location provider. This provider determines location using satellites. Depending on conditions, this provider may take a while to return a location fix. Requires the permission android.permission.ACCESS_FINE_LOCATION.

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,time,distance,listener);

Network –> (AGPS, CellID, WiFi MACID): Name of the network location provider. This provider determines location based on availability of cell tower and WiFi access points. Results are retrieved by means of a network lookup. Requires either of the permissions android.permission.ACCESS_COARSE_LOCATION or android.permission.ACCESS_FINE_LOCATION.

locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,time,distance,listener);

Passive –> (CellID, WiFi MACID): A special location provider for receiving locations without actually initiating a location fix. This provider can be used to passively receive location updates when other applications or services request them without actually requesting the locations yourself. This provider will return locations generated by other providers. Requires the permission android.permission.ACCESS_FINE_LOCATION, although if the GPS is not enabled this provider might only return coarse fixes. This is what Android calls these location providers, however, the underlying technologies to make this stuff work is mapped to the specific set of hardware and telco provided capabilities (network service).

<receiver android:name=".PassiveLocationChangedReceiver" android:enabled="true"/>

Alsoyou can Get Location using Following:

Cached GPS: Most Androids have the ability to store the last know GPS location. This is typically used when an application first starts up, and you can retrieve the timestamp, latitude, longitude and accuracy.

locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);


Cached Network: Android devices can also store the last known location as determined by the cellular carrier’s network location provider. The provider gathers information from the cell network and WiFi, if it’s turned on, then sends that off to a remote server-side process that crunches the information and sends back an approximate location. This is not available in all countries.  Just like the GPS, you’ll typically retrieve the timestamp, latitude, longitude and accuracy.

locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

NMEA: Although it’s not human readable, you can get access to the raw NMEA strings. Typically these strings are used for programmatic access and would only make sense to a developer or engineer. This data is often used in maritime apps. The data is only available once the GPS has warmed up, which is a concept discussed in more detail below.

addNmeaListener(GpsStatus.NmeaListener);


The best way is to use the “network” or “passive” provider first, and then fallback on “gps”, and depending on the task, switch between providers. This covers all cases, and provides a lowest common denominator service (in the worst case) and great service (in the best case).


  • Fine-grained location provider like the GPS provider with an accuracy of less than 100 m.
  • Coarse-grained location provider like the network location provider with an accuracy of 100 – 500 m

Hide keyboard from activity

If there is no need of keyboard then you can hide by adding following lines in to manifest


<activity
            android:name=".ActivityName"
            android:label="@string/name"
            android:windowSoftInputMode="stateAlwaysHidden" />


Also You can use InputMethodManager, calling hideSoftInputFromWindow


getWindow().setSoftInputMode(
      WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

OR

InputMethodManager imm = (InputMethodManager)getSystemService(
      Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(customEditText.getWindowToken(), 0);

Rotating device loose data

When a user types into the editText  or loads data from database and rotates the phone the text/data is lost.To overcome this add following lines in manifest in your activity

<activity
            android:name=".Activity"
            android:configChanges="orientation"
            android:label="@string/name" />


Remove title bar through XML and programmatically

Some times we require title bar but for some activity there is no need of title bar .

There is  two way to remove title bar in android
  1. Modifying manifest i.e XML.
  2. By programmatically.
 1. Modifying manifest i.e XML:

<activity android:name=".ActivityName"
android:label="@string/app_name"
android:theme="@android:style/Theme.Black.NoTitleBar">
</activity>

 2. By programmatically.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
      requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
}


If you want NoTitleBar for application then use following:

 <application
        android:allowBackup="true"
       android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/android:Theme.Black.NoTitleBar" >
      
        <activity android:name=".ActivityName" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
 </application>


Friday, February 1, 2013

dalvikvm-heap: external allocation too large for this process.

This error is for heap size .Your trying to run application with low heap size or your app may require larger heap size.

Increase heap sizes of emulator.


Use 128 or 256 MB heap size.

No compatible target were found?

This is because your project built target miss match.Your using google library (android:name="com.google.android.maps") in project and not changed emulator target setting.

Check emulator target setting



Change Android 2.3.3 - API Level 10 to Google - APIs(Google Inc.) - API Level 10


 If this doesn't solves then create new AVD Targeting version will same as the version included in manifest.


Not targeting the latest versions of Android?

Lint warning about target latest version of android:

Not targeting the latest versions of Android; compatibility modes apply. Consider testing and updating this   version. Consult the android.os.Build.VERSION_CODES javadoc for details.

This is because the target version you used in manifest



<uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="15" />



API 14: Android 4.0 (IceCreamSandwich); 
API 15: Android 4.0.3 (IceCreamSandwich);  
API 16: Android 4.1 (Jelly Bean); 
API 17: Android 4.2 (Jelly Bean); 

.
.
.

Use the latest  android:targetSdkVersion="$$" to avoid this LINT mark.

Different types of layout android

Android basics:layouts


When you create a new project, you might see a folder “layout” in the res folder (/res/layout). This directory contains the xml files needed for your application. You can create as much of xml file needed for your application.  You can arrange widgets such as buttons, TextView, edit text and more and more in these xml files.For layout also Gravity, Padding ,Weight.

How to call layout in activity?



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

Types of layout:

  1.   Linear Layout  
  2.   Relative Layout
  3.   Table Layout
  4.   Frame Layout
  5.   Absolute layout
Linear Layout-Horizontal & Vertical:

Layout is used for arrage views in vertical or horizontal manner.
Vertical layout snippet
<LinearLayout android:orientation="vertical"> .... </LinearLayout>
Horizontal layout snippet
     <LinearLayout android:orientation="horizontal"> .... </LinearLayout>

  •  Vertical Layout

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

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

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

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

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

</LinearLayout>

  • Horizontal Layout

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

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

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

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

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

</LinearLayout>


Relative Layout


In Android, RelativeLayout let you position your component base on the nearby (relative or sibling) component’s position. It’s the most flexible layout, that allow you to position your component to display in anywhere you want
In RelativeLayout, you can use “above, below, left and right” to arrange the component position, for example, display a “button1″ below “button2″, or display “button3″ on right of the “button1″.


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

    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:text="Button" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button4"
        android:layout_alignBottom="@+id/button4"
        android:layout_alignParentLeft="true"
        android:text="Button" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="Button" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button3"
        android:layout_alignParentBottom="true"
        android:text="Button" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:src="@drawable/marker_sky" />

</RelativeLayout>


Table Layout


 In Android, TableLayout let you arranges components in rows and columns, just like the standard table layout in HTML,<tr> and <td>.



<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/TableLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <TableRow>

        <Button
            android:id="@+id/button4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Button" />

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

    <TableRow>

        <Button
            android:id="@+id/button4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Button" />

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

    <TableRow>

        <Button
            android:id="@+id/button4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Button" />

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

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

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

</TableLayout>

Frame Layout


One of the simple layouts used to hold a section of the screen blank, for displaying an item at run time. One best example for frame layout is tab view. In tab view, we use frame layout to display different screens.



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

    <ImageView
        android:id="@+id/ImageView01"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:scaleType="fitXY"
        android:src="@drawable/color" >
    </ImageView>

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Top"
        android:textColor="#fff"
        android:textSize="40dp" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:gravity="right"
        android:text="Bottom"
        android:textColor="#fff"
        android:textSize="50dp" />

</FrameLayout>


Absolute layout 

 AbsoluteLayout is the layout that you may want if you want to specify the x and y, in html its position:absolute, and the x(top) and y(left) is android:layout_x and android:layout_y.

 

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/AbsoluteLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="118dp"
        android:layout_y="44dp"
        android:text="Button" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="127dp"
        android:layout_y="154dp"
        android:text="Button" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="138dp"
        android:layout_y="258dp"
        android:text="Button" />

    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="154dp"
        android:layout_y="364dp"
        android:text="Button" />

</AbsoluteLayout>

You can use combination of layout as per requirement for one layout file (main.xml).