Creating and Displaying a Custom Dialog in Android

In this post I would like to describe the process of creating and displaying a custom dialog. Though the Android documentation describes pretty well the topic, I faced some problems implementing it, and I would like to share my findings.

The final output should look like this:

Android Custom Dialog

1. The first issue I have encountered was that I was getting a BadTokenException in the onCreateDialog() method where I was instantiating the Dialog: android.view.WindowManager$BadTokenException: Unable to add window — token null is not for an application, 

Context context=getApplicationContext();
Dialog dialog=new Dialog(context);

Well, though the Android documentation suggests to use getApplicationContext(); actually it turns out that this is not the proper way to do it and most likely it will throw an exception. The correct way is to use this, or “ActivityName”.this instead of getApplicationContext(). For example:

Context context=MainActivity.this;
Dialog dialog=new Dialog(context);

 

2. The second issue I was facing was that I wanted to get rid off the standard dialog title.
Normally you would set the Dialog title with this:

dialog.setTitle("Dialog Title");

However, if you don’t want to display a standard title for your dialog, not calling the above line most probably won’t meet your expectations, because it will leave an empty space where the title should be.

Hopefully, this is an easy fix. Just call requestWindowFeature(Window.FEATURE_NO_TITLE); and you are done.

dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

 

To sum up with a concrete working example, below I presented an implementation of a simple custom dialog.

custom_dialog.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="250dp"
   android:layout_height="match_parent"
   android:background="#8F1A3B"
   android:orientation="vertical" >

<TextView
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:layout_marginBottom="20dp"
   android:text="Custom Dialog"
   android:textSize="18dp" />

<Button
   android:id="@+id/restart"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Restart Game" />

</LinearLayout>

 

MainActivity:


public class MainActivity extends Activity {

Dialog dialog;
int DIALOG_GAME_RESTART=100;

@Override
public void onCreate(Bundle savedInstanceState) {
   // ............
}

@Override
protected Dialog onCreateDialog(int id) {
   switch (id) {
   case DIALOG_GAME_RESTART:
     Context context=MainActivity.this;
     dialog=new Dialog(context);
     dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

     dialog.setContentView(R.layout.custom_dialog);

     Button restart=(Button)dialog.findViewById(R.id.restart);

     restart.setOnClickListener(new OnClickListener() {
     @Override
     public void onClick(View v) {
        dialog.dismiss();

        //whatever code you want to execute on restart
     }
     });
   break;

   default: break;
   }
   return dialog;
}
}
Advertisements

ITMoldova – My First Android Application.

Although it has passed awhile since I published my first android application on Google Play, and I published already my second Android App meanwhile, I decided to write about it as well, as almost all my posts from this blog till now are findings and experience gained while I was working on ITMoldova app.

ITMoldova.com is a Moldavian site that provides daily IT News for romanian speaking people. The main purpose of Android application is to check the RSS feed of the site if there are any new articles. If it turns out that new articles have been published on the site, then launch a status bar notification and notify the user. And of course, the user is able to see the most recent articles and read them right from his device.

The application settings provides the ability to set up the desired interval of time, when the application should verify the RSS feed, plus the possibility to Turn On or Off this feature.

ITMoldova Main

ITMoldova

I have some doubts in regards to how many of my readers and visitors of this blog understand Romanian language, but just in case, here’s the Google Play download link: 🙂

Get it on Google Play - ITMoldova

Do you want to build your own RSS Reader Application?

Here are the topics that will help you achieve this:

Creating A Simple RSS Application in Android

Understanding AsyncTask – Once and Forever

How to verify an RSS Feed if New Articles have been published.

Working With Services – IntentService

Showing status bar notifications in Android

How to Create Android Menus

Writing and Reading from SharedPreferences

Detecting Internet Connection

Building a Custom Fancy ListView in Android

After reading (and exercising) the above tutorials, you should be able to build your own Cool RSS Application :).

 

Please visit the Android Tutorials page for more Android tutorials.

GAG Pictures – Have Fun! Spread The Fun!

9gag picturesHello everyone, I would like to introduce you my second Android application published on Google Play  – GAG Pictures. Compared with the first one, this application is intended to bring you much fun.

GAG Pictures is your daily set of funny images! Every time the application is launched it downloads a set of new funny images from the famous site 9gag.com. Every image has a Share button so you can share that hilarious image with your friends. The current version allows you to share only the direct link to image, but in the upcoming releases the ability to send the image itself will be provided.

9gag funny image

Have fun! 🙂

Get it on Google Play - GAG Pictures

Writing and Reading from SharedPreferences

SharedPreferences class allows you to save and retrieve primitive data types in key-value pairs. The data saved using SharedPreferences will be available even after your application is killed. This capability makes SharedPreferences suitable in different situations when user settings needs to be saved for example, or store data that can be used in different activities.
The data types that can be saved are booleans, floats, ints, longs, and strings.

To get an instance of SharedPreferences use the getSharedPreferences(String, int) method. The method takes 2 parameters: the name of the preference settings and the mode. (0 or MODE_PRIVATE for the default operation, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions)

To write values:

  1. Call edit() to get a SharedPreferences.Editor instance
  2. Add values with methods such as putInt() and putString().
  3. Call commit() to save values.

To read values use such methods as getString() and getInt() of SharedPreferences instance.

Here’s a simple usage of SharedPreferences class:


public class SharedPrefsActivity extends Activity {

  public static final String PREFS_NAME = "MyApp_Settings";

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

     SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);

     // Writing data to SharedPreferences
     Editor editor = settings.edit();
     editor.putString("key", "some value");
     editor.commit();

     // Reading from SharedPreferences
     String value = settings.getString("key", "");
     Log.d(TAG, value);
  }
}

Please visit the Android Tutorials page for more tutorials.

Drawing Shapes in Android

In this post I would like to share my findings about defining and using shapes.  A shape is an XML file that defines a geometric shape, including strokes, colors and gradients

Android Shapes

To define a shape:

1. Create a new Android XML file in the folder res/drawable

2. Make sure the root element of the file is <shape >. (If it’s not, then change it manually)

3. Inside the <shape> element, press CTRL + Space to reveal all the available elements you can use to define a shape:

android shapes options

As you can see, the elements are pretty self explanatory. To reveal the attributes of an element, put the cursor inside that element and press CTRL + Space:

android shape corner

4. Once the shape is defined, you can specify it as a background resource to any view: android:background=”@drawable/myshape”

Example:

res/drawable/boxbg.xml:

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

<stroke
  android:width="2dp"
  android:color="#FFFFFF" />

<corners android:radius="5dp" />

<gradient
  android:angle="270"
  android:centerColor="#6E7FFF"
  android:endColor="#142FFC"
  android:startColor="#BAC2FF" />

</shape>

 

res/drawable/box2bg.xml:

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

<solid android:color="#4D9611" />

<stroke
  android:width="4dp"
  android:color="#FFFB00" />

</shape>

 

res/layout/main.xml:

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

<!-- First box, boxbg.xml -->
<LinearLayout
  android:layout_width="match_parent"
  android:layout_height="80dp"
  android:layout_margin="20dp"
  android:background="@drawable/boxbg"
  android:orientation="vertical"
  android:padding="5dp" >

  <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    android:textColor="#000"
    android:textSize="20dp" />
</LinearLayout>

<!-- Second box, box2bg.xml -->
<LinearLayout
  android:layout_width="match_parent"
  android:layout_height="80dp"
  android:layout_margin="20dp"
  android:background="@drawable/box2bg"
  android:orientation="vertical"
  android:padding="7dp" >

  <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    android:textColor="#FFF"
    android:textSize="20dp" />
</LinearLayout>

</LinearLayout>

 

The final output should look like this:

android shape

Working With Services In Android – IntentService

A service is an application component that can perform long-running operations in the background and it does not provide an user interface. For example, a service might handle network transactions, play music, perform file I/O, etc., all from the background.

Usually, there are two classes you can extend to create a service: you extend the Service class and override some callback methods, or extend the IntentService class and all you need to do is implement the onHandleIntent() method where you put all the code that should run in the background.

Extending the IntentService class is the simplest way to create a service. If you don’t need to handle multiple requests simultaneously, then this probably is the best option to choose.

 

In this post we will create a service using the IntentService class.

Well, our service won’t do much. This would be a proof-of-concept application, showing the creation process of a service. The mission of our service would be just to print a message in the LogCat, (pretty simple for a service :)), but in a real application you would write of course more advanced code, like playing music, or performing some I/O operations for example.

1. Create a new project in Eclipse:
Project: ServiceTest
Activity: ServiceTestActivity

2. Create a new class, say MyService, and do as follows:
– Extend the IntentService
– Provide a constructor with no arguments that calls the super constructor, with a name as an argument.
– Override the onHandleIntent(Intent intent); method.


public class MyService extends IntentService{

// No-arg constructor is required
public MyService() {
   super("MyService");
}

@Override
protected void onHandleIntent(Intent intent) {
   Log.d("TAG", "Service started");

   //....
   // The rest of the code that needs to run in the background
   //....

}
}

Note that it’s important that you provide a no-arg constructor, otherwise you may get an exception: InstantiationException

 

3. Register your service

Open the AndroidManifest file and add the following line as a child of <application> tag:


<application ......
   <service android:name=".MyService" />
</application>

 

4. Start the service

To start a service the startService(intent) method is used, which takes as an argument an intent with the specified service.


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

   // Starting the service
   Intent intent =new Intent(this, MyService.class);
   startService(intent);
}

Creating A Simple RSS Application in Android

In this tutorial we will build a simple rss application.

Requirements are:
1) parse an rss feed and display the headlines in a ListView
2) when the user clicks on a headline, open the Android browser and redirect to corresponding web page.


Note: this tutorial is outdated. I would suggest you follow the new tutorial. The new tutorial is more extended, but it addresses few issues present in this example. On the other hand, if you are not looking for a very detailed tutorial and are interested only in XML parsing part, feel free to browse this example.

We will parse the PCWorld‘s rss looking for the latest news: http://feeds.pcworld.com/pcworld/latestnews

The final result will look like in the screenshot below:

android rss app

1. Create a new project in Eclipse:
Project: SimpleRssReader
Activity: SimpleRssReaderActivity

2. Add required permissions to AndroidManifest file.
The application will make use of Internet, so this should be specified in the AndroidManifest file, otherwise an exception will be thrown. Just after the <application> tag, (as a child of <manifest> tag), add the following line:

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

3. Open the main.xml layout file, delete the already existing TextView control, and add instead a ListView with the id “list”. This should should look like this:

<?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="@+android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>

</LinearLayout>

4. Lets create the skeleton of our main activity.
Open the SimpleRSSReaderActivity and make it extend ListActivity, instead of Activity as it  comes by default. We need this in order to display the headlines in the ListView by binding to an array which will hold our data, using the list view adapter.
Add 2 instance variables: “headlines” and “links” of type List.

It should look like this:

public class SimpleRSSReaderActivity extends ListActivity {

	List headlines;
	List links;

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

	}
}

5. In the onCreate() method, just after the setContentView(….) , add following lines:

// Initializing instance variables
headlines = new ArrayList();
links = new ArrayList();

try {
	URL url = new URL("http://feeds.pcworld.com/pcworld/latestnews");

	XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
	factory.setNamespaceAware(false);
	XmlPullParser xpp = factory.newPullParser();

        // We will get the XML from an input stream
	xpp.setInput(getInputStream(url), "UTF_8");

        /* We will parse the XML content looking for the "<title>" tag which appears inside the "<item>" tag.
         * However, we should take in consideration that the rss feed name also is enclosed in a "<title>" tag.
         * As we know, every feed begins with these lines: "<channel><title>Feed_Name</title>...."
         * so we should skip the "<title>" tag which is a child of "<channel>" tag,
         * and take in consideration only "<title>" tag which is a child of "<item>"
         *
         * In order to achieve this, we will make use of a boolean variable.
         */
	boolean insideItem = false;

        // Returns the type of current event: START_TAG, END_TAG, etc..
	int eventType = xpp.getEventType();
	while (eventType != XmlPullParser.END_DOCUMENT) {
		if (eventType == XmlPullParser.START_TAG) {

			if (xpp.getName().equalsIgnoreCase("item")) {
				insideItem = true;
			} else if (xpp.getName().equalsIgnoreCase("title")) {
				if (insideItem)
					headlines.add(xpp.nextText()); //extract the headline
			} else if (xpp.getName().equalsIgnoreCase("link")) {
				if (insideItem)
					links.add(xpp.nextText()); //extract the link of article
			}
		}else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")){
			insideItem=false;
		}

		eventType = xpp.next(); //move to next element
	}

} catch (MalformedURLException e) {
	e.printStackTrace();
} catch (XmlPullParserException e) {
	e.printStackTrace();
} catch (IOException e) {
	e.printStackTrace();
}

// Binding data
ArrayAdapter adapter = new ArrayAdapter(this,
		android.R.layout.simple_list_item_1, headlines);

setListAdapter(adapter);

6. In the onCreate() method we passed an input stream to setInput(): xpp.setInput(getInputStream(url), "UTF_8");
getInputStream() is not a standard Java method, so we should create it. This method should take as an argument the feed url, and return the input stream.


public InputStream getInputStream(URL url) {
   try {
       return url.openConnection().getInputStream();
   } catch (IOException e) {
       return null;
     }
}

7. Finnaly, we want when a title is clicked, the Android browser to be opened and display the corresponding article. This one is simple, we override the onListItemClick() method, get the position of article in the ListView, retrieve the coresponding link, and pass the url of that article to ACTION_VIEW intent which takes care further of displaying the web page.


@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
   Uri uri = Uri.parse(links.get(position));
   Intent intent = new Intent(Intent.ACTION_VIEW, uri);
   startActivity(intent);
}

By this time you should compile and run successfully the application.

Well, if everything went fine and you are done with the simple rss application, the next step to consider is how can you enhance the visual aspect of the application. Adding some style to the ListView, for example alternating between background colors, or displaying an icon next to each headline, can considerably increase the visual aspect, which will make your application look more appealing.
Take a look at this tutorial: Building a Custom Fancy ListView in Android, where I show in details how to achieve this.

This application, however, has one major drawback. Its drawback is that all the parsing and network access is done on the UI thread. As a result, you may notice that when starting the application, it “freezes” for a few seconds and then displays the headlines. To fix this issue, you should put all the parsing functionality in a background thread. In regards how to do that, you definitely should consider this post: Understanding AsyncTask – Once and Forever