Archive for the ‘Android’ Category

Android – INSTALL_FAILED_INSUFFICIENT_STORAGE

Monday, January 23rd, 2012

If you work with the Android Emulator and deploy to it for a while you may receive the following error message in the LogCat View.

Installation error: INSTALL_FAILED_INSUFFICIENT_STORAGE

The reason for this is that the emulator default to 64MB for internal storage.

You can override this in the Eclipse launch configuration for your Android application with the additional parameter -partition-size 1024.

Alternative you can add the following line to the “config.ini” file of you AVD definition. This file is stored in the user folder in .android/avd and then under your specific device definition. For example:

hw.lcd.density=160
sdcard.size=200M
skin.name=HVGA
skin.path=platforms/android-15/skins/HVGA
hw.cpu.arch=arm
abi.type=armeabi-v7a
hw.cpu.model=cortex-a8
vm.heapSize=48
snapshot.present=true
hw.ramSize=512
image.sysdir.2=system-images/android-15/armeabi-v7a/
image.sysdir.1=add-ons/addon-google_apis-google_inc_-15/images/armeabi-v7a/
disk.dataPartition.size=1024

I hope this helps. I have also ask the Android development team to increase the default value: Bug report.

Android SQLite and ContentProvider Book available for the Kindle

Wednesday, January 18th, 2012

Today I released my new Android SQLite and ContentProvider book for the Kindle device.

This book demonstrates how you can develop Android applications using the integrated SQLite database. It also demonstrates how to use and create ContentProvider for accessing data. ContentProviders are Java classes which allow to share data between applications. They also provide a structured interface to access data. The tutorials of this book have been developed and tested with Android 4.0.3, API Level 15.

The book assumes that you are already familiar with the Android Development Tools for Eclipse and with creating simple Android applications.

You find the book in all Amazon stores:

Android SQLite and ContentProvider Book in Amazon USA
Android SQLite and ContentProvider Book in Amazon Germany
Android SQLite and ContentProvider Book in Amazon UK
Android SQLite and ContentProvider Book in Amazon France
Android SQLite and ContentProvider Book in Amazon ES
Android SQLite and ContentProvider Book in Amazon IT

Content Description:

The first chapter gives an introduction into SQLite and using SQlite on Android.

The second chapter introduces the main SQLite classes and how to use them. It also gives examples how to create and run queries to your database.

The third chapter contains a tutorial in which you create a new Android project which uses SQLite to store its data. In the tutorial you will use a wrapper class (data access object) which handles the access to the database.

In the fourth chapter we look at ContentProviders. It explains what a ContentProvider is, how you can access existing ones and how to define your own one.

In this chapter you also learn how to define a ContentProviders only visible to your application and learn about threading safety with ContentProvider.

The next chapter is a tutorial which shows how to access an existing ContentProvider. You create an Android application which access the data from the “People” application .

The sixth chapter explains the Loader API which was introduced in Android 3.0. Loader loads the data asynchronously. Activities should use this new API to manage their database connection (Cursor).

The seventh chapter is a tutorial in which you create an application to manage your tasks. You create your own ContentProvider for accessing the SQLite database and use the Loader API for accessing and managing the database Cursor.

Accessing the SQLite database directly on the command line is part of the eighth chapter.

The content of the book is similar to the online version.

I’m again surprised how much work it is to convert my website content into a book format. I hope you like this book.

Making the Android SDK source code available in Eclipse

Tuesday, January 10th, 2012

As of Android 4.0 the integration of the Android SDK source code is much easier.

You can just download the source code via the Android SDK Manager. The sources are downloaded to the source directory located in “path_to_android_sdk/sources/android-xx”. xx is the api level number (15 for 4.0.3). You can then add the source code as a source attachment to your android.jar.

I included this info in my Android Tutorial.

Thanks to Ed Burnette for pointing that out on Google+.

Kudos also the the ADT team which made this great improvement in development experience.

Automatically starting Services in Android after booting

Sunday, December 11th, 2011

To start Services automatically after the Android system starts you can register a BroadcastReceiver to the Android android.intent.action.BOOT_COMPLETED system event.

In the onReceive() method the corresponding BroadcastReceiver would then start the service.

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		Intent service = new Intent(context, WordService.class);
		context.startService(service);
	}
}

If you application is installed on the SD card, then it is not available after the android.intent.action.BOOT_COMPLETED event. Register yourself in this case for the android.intent.action.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE event.

Also note that as of Android 3.0 the user needs to have started the application at least once before your application can receive android.intent.action.BOOT_COMPLETED events.

You find more on Services in my Android Service and BroadcastReceiver Tutorial.

I hope this helps. You find me also on Twitter. My Google+ profile can be found Lars Vogels Profile.

vogella.de goes Creative Commons CC BY-NC-SA 3.0 licence

Friday, December 2nd, 2011

Recently I received lots of requests for translating my tutorials into other languages or if my tutorials can be used in Universitity classes. In general I’m fine with that as long as the usage is non-commercial and attribution is given.

I decided to select a official licence for usage of my content so that others have better information on how they can use it. As far as I can tell the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Germany (CC BY-NC-SA 3.0) looks like the right licence to me.

Therefore, unless otherwise stated in the tutorials, I put the tutorials on http://www.vogella.de under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Germany (CC BY-NC-SA 3.0) licence.

Attribution for a translation or reproduction which is available on the web would be a link to the original article as well as mentioning me as the original author. This attribution should be clearly visible at the beginning of the article.

If you use the material in a non-web form an attribution should be given in the same spirit. For example if you print the material for your university class you would include a page which states the original author as well as the link to the content on the web.

Neil Barlett suggested to clarify the non-commercial part. My understanding is that this means that you cannot earn money by replicating or translating the content, e.g. via advertisements, selling books, etc.

Also a big thanks to Jovan Kostovski and Kai Toedter at Google+ for lots of consulting and tips on the licence.

I hope this help other to translate my tutorials and to spread the word about Eclipse, Android and other Java related programming around the non perfectly english speaking world.

Plurals in Android

Tuesday, November 22nd, 2011

Android supports Plurals. Plurals are XML based resources which allow to handle different quantities. This way you can select the right text based on the quantity. In your XML file you specify values for the quantities “zero”, “one”, “two”, “many”, “few”, “many”, “other” and in your code you use the method getQuantityString() to get the correct value. You can also format strings. If now Strings are formated then you pass in the plural resources and the number. If Objects should be used for formating you pass them as additional parameters.

For example the following will define a plural. This file needs to be in the “res/values” directory and in this example it is called “plurals”.


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <plurals
        name="tutorials">
        <item quantity="zero">no Tutorial </item>
        <item quantity="one">one Tutorial </item>
        <item quantity="other">%d  Tutorials</item>
    </plurals>
</resources>

The correct value can then be select via the following coding:


// number is defined somewhere before this
// number =....
// Get the Resources
Resources res = getResources();
// Get the
String quantityString = res.getQuantityString(R.plurals.tutorials,
	number, number);
// Do something with it...

From the Android development guide: Note that the selection is made based on grammatical necessity. A string for zero in English will be ignored even if the quantity is 0, because 0 isn’t grammatically different from 2, or any other number except 1 (“no tutorial”, “one tutorial”, “two tutorials”, and so on).

Thanks to mohammad dabbour and Kirill Grouchnikov for clarifying a question on this in Google+.

I hope this blog entry helps. You find me also on Twitter. My Google+ profile can be found Lars Vogels Profile.

Distributed Version Control with Git available for the Kindle

Tuesday, November 15th, 2011

Today I released my first book for the Kindle platform: Distributed Version Control with Git.



Git is popular, especially in my main focus areas, Eclipse and Android.

Since a while I’m working in converting my tutorials into offline versions. The Git tutorial is the first one because it has no images. To my surprise it was still a huge amount of work. I hope the second book will be easier, as I learned a lot about epub, mobipocket, design, DocBook, XSLT transformations, Apache Ant, Inkscape and other tools.

You find the Git Book in all Amazon Stores:

Git Book in Amazon Germany
Git Book in Amazon UK
Git Book in Amazon France
Git Book in Amazon USA

Just to set the right expectations, the Distributed Version Control with Git has the same content related material as the online version. I hope that having this material also available for the Kindle is helpful. Is also allows you to read the online version before deciding if you want to get the book offline.

A big thanks goes to Alex Blewitt for writing the foreword and for providing feedback. I would especially thank Jennifer Nerlich de Vogel for their intensive spell checking exercises. Wolfgang Schell who is a power Kindle user gave important feedback for improving the structure of the book to optimize it for the Kindle.

I also got many suggestions or corrections from my readers and other people involved with Git and would I would like to express my deepest gratitude to their contribution including Robert Konigsberg, Elke Schaper, Appaholics, Michael Wiedmann, Joshy Cyriac, Peter Kahle, Jon Svede, Henning Hoefer, Matthias Sohn, Chris Aniszczyk, Stefan Lay, Edwin Kempin, Sasa Zivkov, David Carver.

Also a big thank you to Ralf Ebert who seeded the idea to publish on the Kindle platform.

Now I’m hoping for positve reviews at Amazon. :-)

Android – How to get an image via an intent

Tuesday, September 13th, 2011

Android allows to re-use components from other applications. Lets see how you can use the Photo Gallery to pick a photo for your application.

First create a layout with a Button and an ImageView.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	<Button android:text="Button" android:id="@+id/button1"
		android:onClick="pickImage" android:layout_width="wrap_content"
		android:layout_height="wrap_content"></Button>
	<ImageView android:id="@+id/result" android:src="@drawable/icon"
		android:layout_width="match_parent" android:layout_height="match_parent"></ImageView>
</LinearLayout>

The following Activity will allow you to pick an image after pressing the button and after selecting a picture this picture will be set as background for your ImageView.

package de.vogella.android.imagepick;

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

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

public class ImagePickActivity extends Activity {
	private static final int REQUEST_CODE = 1;
	private Bitmap bitmap;
	private ImageView imageView;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		imageView = (ImageView) findViewById(R.id.result);
	}

	public void pickImage(View View) {
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		startActivityForResult(intent, REQUEST_CODE);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
			try {
				// We need to recyle unused bitmaps
				if (bitmap != null) {
					bitmap.recycle();
				}
				InputStream stream = getContentResolver().openInputStream(
						data.getData());
				bitmap = BitmapFactory.decodeStream(stream);
				stream.close();
				imageView.setImageBitmap(bitmap);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		super.onActivityResult(requestCode, resultCode, data);
	}
}

Updated: recycle() call to bitmap added

I hope this blog entry helps. You find me also on Twitter. My profile can be found .

I also offer Android Trainings.

Android – Going down with Style

Tuesday, August 16th, 2011

Android allows to use styles and themes to define the appearance of the user interface. This blog entry will demonstrate how to use styles in your application.

First create a new Android project “de.vogella.android.styles.simple” with the following main.xml layout file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	<TableLayout android:layout_height="wrap_content"
		android:stretchColumns="1" android:id="@+id/tableLayout1"
		android:layout_width="fill_parent">
		<TableRow android:id="@+id/tableRow1" android:layout_width="wrap_content"
			android:layout_height="wrap_content">
			<TextView android:text="User" android:id="@+id/textView1"
				android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
			<EditText android:id="@+id/editText1" android:layout_width="wrap_content"
				android:layout_height="wrap_content">
				<requestFocus></requestFocus>
			</EditText>
		</TableRow>
		<TableRow android:id="@+id/tableRow2" android:layout_width="wrap_content"
			android:layout_height="wrap_content">
			<TextView android:text="Password" android:id="@+id/textView2"
				android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
			<EditText android:id="@+id/editText2" android:layout_width="wrap_content"
				android:layout_height="wrap_content"></EditText>
		</TableRow>
	</TableLayout>
</LinearLayout>

This gives us the following wounderful UI.

Lets make the UI a bit nicer. The typical way would be to set attributes to the elements in the UI until we are fine with the result. In addition to this approach you can also define styles which you can assign to the elements. This way you only have to set common attributes once and can later change the look in one central place.

To start create the XML file “styles.xml” under /res/xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="text">
        <item name="android:padding">4dip</item>
        <item name="android:textAppearance">?android:attr/textAppearanceLarge</item>
        <item name="android:textColor">#000000</item>
    </style>
    <style name="layout">
        <item name="android:background">#C0C0C0</item>
    </style>
</resources>

You now assign the style attribute to your elements, for example to the text elements via style=”@style/text”.

If you apply the style to your text elements and layout you receive.

I hope this helps.

You find me also on Twitter and Google+.

How to check if network connection is available in Android?

Tuesday, August 2nd, 2011

Android allows to check if the network is available. Here is a code snippet to check this:


public boolean isNetworkAvailable() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    // if no network is available networkInfo will be null, otherwise check if we are connected
    if (networkInfo != null && networkInfo.isConnected()) {
        return true;
    }
    return false;
}

Your application requires also the uses-permission “android.permission.ACCESS_NETWORK_STATE” to check for the network state.

Hope this helps.


Switch to our mobile site