Android Posts Now On how-to-develop-android-apps.com
From now on, all Android related posts will be found on http://how-to-develop-android-apps.com. I’ll keep the posts that I’ve already made here for reference, but no new Android programming tutorials will be found here.
How to Make a Toast in Android
A Toast in Android is just a quick popup message to the user. It is useful for quickly notifying the user of something that has taken place since it will automatically disappear after a set amount of time. Here’s how to do it:
main.xml:
<?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"> </LinearLayout>
SogacityActivity.java:
package com.sogacity;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class SogacityActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toast.makeText(SogacityActivity.this, "This is a long Toast!", Toast.LENGTH_LONG).show();
}
}
One thing that I always forget is to add the .show() at the end, very easy to miss. Also, the time can be changed from Toast.LENGTH_LONG to Toast.LENGTH_SHORT. I’ve seen a lot of people use this for debugging, so PLEASE DO NOT BE ONE OF THOSE PEOPLE. Use LogCat for all debugging and keep Toasts for user notifications! Here’s how it looks:

How to Create an AlertDialog in Android
Sometimes you will need to prompt the user to make a choice. An AlertDialog is perfect for this and very easy to create. Here’s an example:
main.xml:
<?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:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Save"></Button> </LinearLayout>
SogacityActivity.java:
package com.sogacity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class SogacityActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
//Create alert dialog
AlertDialog alert;
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(SogacityActivity.this);
alertBuilder.setTitle("Profile");
//Give Alert Dialog custom view and create close button
alertBuilder.setMessage("This is a sample Alert Dialog!");
//Create positive button
alertBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(SogacityActivity.this, "OK!", Toast.LENGTH_LONG).show();
}
});
//Create negative button
alertBuilder.setNegativeButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(SogacityActivity.this, "Close!", Toast.LENGTH_LONG).show();
}
});
//Display alert dialog
alert = alertBuilder.create();
alert.show();
}
});
}
}
Now let me explain. First you must create an AlertDialog builder. This is what actually makes the dialog. Setting a title will change the title text and same with the message. setPositiveButton() is used to create a button that is meant to do something, or have a positive result in the Activity. setNegativeButton() is used for canceling out of the AlertDialog. Once your AlertDialog is created, call the create() method on the builder and then show the alert! Here’s what it looks like:
After clicking ‘Save’:

A toast pops up with the correct selection!:

View my article on using Toast for more information: http://sogacity.com/how-to-make-a-toast-in-android/
Using Shared Preferences in Android
Sometimes, you will want to pass information between activities. For instance, you might create a Preference or Configuration activity where the user tweaks the app to their liking. You could store their tweaks with Shared Preferences. In the following example, I’ll demonstrate how to pass a String from one activity to another.
main.xml:
<?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"> <EditText android:id="@+id/textBox" android:layout_width="fill_parent" android:layout_height="wrap_content"></EditText> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Save"></Button> </LinearLayout>
Just a simple EditText with a Button.
SogacityActivity.java:
package com.sogacity;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class SogacityActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button);
final EditText textBox = (EditText) findViewById(R.id.textBox);
button.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
SharedPreferences app_preferences =
PreferenceManager.getDefaultSharedPreferences(SogacityActivity.this);
SharedPreferences.Editor editor = app_preferences.edit();
String text = textBox.getText().toString();
editor.putString("key", text);
editor.commit();
Intent myIntent = new Intent(SogacityActivity.this,SharedPreference.class);
startActivity(myIntent);
}
});
}
}
Here I create a Button OnClickListener. When the Button is clicked I grab the text from the EditText, store the value in a Shared Preference, and then start a new Intent to the next activity. Don’t forget to call “editor.commit()” as that is what actually tells the editor to store the values.
main2.xml:
<?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"> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView> </LinearLayout>
Very basic layout with just one TextView that will be changed to the value of our Shared Preference.
SharedPreference.java:
package com.sogacity;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.TextView;
public class SharedPreference extends Activity{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
TextView textView = (TextView) findViewById(R.id.text);
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
String text = app_preferences.getString("key", "null");
textView.setText(text);
}
}
Here I get the Shared Preference and set the TextView to it. The most important part is “app_preferences.getString(“key”, “null”);” where “key” is the key that I stored the SharedPreference as and “null” is the default option in case the key doesn’t exist.
Also, don’t forget to add the new Activity SharedPreference to your AndroidManifest.xml file! Here’s how to do it: http://sogacity.com/add-new-activity-to-android-manifest-file/
Here’s what it looks like:

And after clicking “Save”:

You can see that it correctly changed the TextView to “test”.
Add New Activity to Android Manifest File
Whenever you create a new Java class that extends Activity you need to add that activity to the Android Manifest File. Don’t worry, it is very easy and I’ll show you how to do it. Forgetting to add it to the Android Manifest File can cause quite a few headaches when debugging.
Open AndroidManifest.xml
![]()
First, start by opening up AndroidManifest.xml. This will open up a nice GUI editor within Eclipse for you. You also have the option of editing by XML if you prefer that (sometimes helpful).
Click on the Application Tab
![]()
At the bottom is a list of tabs to help you navigate through the Manifest file. Click on the ‘Application’ tab. As mentioned before, clicking on the ‘AndroidManifest.xml’ tab will let you edit the XML directly.
Add a new Activity
![]()
In the bottom left panel, select ‘Add’. When prompted, select ‘Activity’ and click ‘OK’.
Name your Activity
![]()
Once created, select the Activity in the list. It should be named ‘Activity’. On the bottom right panel, enter the name of the Java class in the ‘Name*’ field. Save the AndroidManifest.xml file and you’re done!
The Elder Scrolls V: Skyrim Characters Released
Bethesda Softworks released some pictures of the characters in Skyrim. Crazy to think of how I was blown away with Oblivion’s graphics. Cannot wait for this game to come out!
Top Android Apps
The Android Marketplace is pretty intimidating for a newcomer. After owning an Android phone for a few months, here’s what I use the most:
Advanced Task Killer
Sometimes an Android App will freeze, or your phone will get slow. Personally, I don’t think that Android gives enough control to the user on which apps are running. This app will let you kill an app that is running with no questions asked. Very easy to use.
Angry Birds
Fun time killer. Lots of levels to play and you can just jump in to play for a few minutes, or be on your phone for hours.
Barcode Scanner
Sort of a novelty since I’ve never extensively used it in a store, but still really cool! Will show you where you can get the product the cheapest.
c:geo
For the geolocators out there, this app will show you some nearby spots to investigate. You can rate the difficulty of it afterwards and even leave feedback.
Car Panel (Pre-Installed)
I did away with my old and clunky GPS. Now my phone runs this whenever I’m in the car to have all the useful car features in one place.
Flashlight (Pre-Installed)
The camera light on my phone is bright, and I mean BRIGHT! Better than a normal flashlight and can be used to blind friends…
Evernote
Probably the best app for storing notes out there. You can easily take text notes, picture notes, audio notes, etc. and have them linked to your account that you can view anywhere with an internet connection.
Facebook
I actually prefer the mobile site version better than the app, but for convenience I put this here. The chat never works for me, but it is useful for checking messages and my stream.
Mint.com
The best app for checking your finances. Will add all of your bank accounts together (even if from different banks) to see them all in one spot, and lets you set budgets and track your spending for them.
My Tracks
Cool app to use when you go for a run. Uses GPS to draw the route you ran on Google Maps and tells you the distance and time it took.
Google Maps
Contains Google’s free GPS Navigator. Better than the GPS I was using in my car. Getting directions anywhere is pretty sweet too.
Pandora
Everybody loves Pandora internet radio. Supposedly they have added a 40 hour listening limit, but I haven’t come close to it yet.
reddit is fun
For those who Reddit out there, this app is very well done. The Reddit mobile site is very nice too.
Scanner Radio
Just neat to listen to some police radios, especially for Detroit!
ESPN ScoreCenter
Lets you follow your favorite teams for the major sports. Can check the box scores for all the games too. Must have for sports fans.
TED Air
I just recently got into watching TED talks, and this is their official app. Very interesting videos on here!
TinyShark
The mobile app for the internet streaming music service GrooveShark. More like iTunes than an internet radio.
How to Make a Lazy Loader ArrayAdapter
This will be building off of the following articles so make sure that you have all the code:
http://sogacity.com/how-to-make-a-custom-arrayadapter-for-listview
http://sogacity.com/how-to-dynamically-add-to-arrayadapter-in-listview/
If you are dynamically adding content to your ListView then it is better to load things in pieces. If you are loading 100 row entries from the internet, then it would make sense to load 10 at a time. When the user scrolls to the bottom of the screen, then load another 10. Loading this way (called Lazy Loading) will save the user power on their phone as well as bandwidth. With tight phone plans, a user will be angry to download all 100 entries when they only read 15 of them! Here’s how to implement such a thing:
main.xml:
<?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"> <ListView android:id="@+id/listview" android:layout_height="wrap_content" android:layout_width="fill_parent"> </ListView> </LinearLayout>
I removed the button from the previous example since it wasn’t necessary.
SogacityActivity.java:
package com.sogacity;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
public class SogacityActivity extends Activity {
private ListView lv;
private CustomAdapter adapter;
private ArrayList<Custom> fetch = new ArrayList<Custom>();
private int counter = 0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView) findViewById(R.id.listview);
generateEntries();
adapter = new CustomAdapter(SogacityActivity.this,
R.id.listview,
fetch);
lv.setAdapter(adapter);
lv.setOnScrollListener(new OnScrollListener(){
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if(firstVisibleItem + visibleItemCount == totalItemCount){
generateEntries();
adapter.notifyDataSetChanged();
}
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
});
}
private void generateEntries(){
for(int x = counter; x < counter + 10; x++){
Custom temp = new Custom("Big" + x,"Small" + x);
fetch.add(temp);
}
counter += 10;
}
}
The first thing that I did was add an OnScrollListener to my ListView, and then add the unimplemented methods for it. The OnScroll method is called when the user is actually scrolling. firstVisibleItem is the position of the first row shown on the screen. visibleItemCount is the number of rows being displayed on the screen. Finally, totalItemCount is the total number of rows in the ListView. To find out if the last row is being displayed (so that we know to load more), simply add firstVisibleItem and visibleItemCount to see if they equal totalItemCount. For example, say that the totalItemCount is 10 (so really 9 since it is 0 indexed). If the first row visible on my screen is row 4 (really 3 with 0 index) and there are 6 rows being displayed, then I know that I can see the last item because 3+6=9. With this determined, I can call my method generateEntries to get some more rows added. Here’s what it looks like:

And now after scrolling to the bottom:

Notice that the scrollbar is a lot smaller so you can tell there are more entries!
How to Dynamically Add to ArrayAdapter in ListView
This article will be building off of this article so make sure you have all the code before starting:
Typically you want your ListView to be dynamic so that you can add or remove data and have the ListView reflect the changes. Luckily, this is very simple. I’m going to start off by adding a button that once clicked will add an item to the ListView. Here is the code:
main.xml:
<?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"> <ListView android:id="@+id/listview" android:layout_height="wrap_content" android:layout_width="fill_parent"> </ListView> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Add Row"> </Button> </LinearLayout>
All that was added was the button.
SogacityActivity.java:
package com.sogacity;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
public class SogacityActivity extends Activity {
private ListView lv;
private CustomAdapter adapter;
private ArrayList<Custom> fetch = new ArrayList<Custom>();
private Button button;
int counter = 0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView) findViewById(R.id.listview);
button = (Button) findViewById(R.id.button);
adapter = new CustomAdapter(SogacityActivity.this,
R.id.listview,
fetch);
lv.setAdapter(adapter);
button.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
Custom temp = new Custom("Big" + counter,"Small" + counter);
fetch.add(temp);
counter++;
adapter.notifyDataSetChanged();
}
});
}
}
For this I added an OnClickListener to the Button. Once clicked, a new Custom object is created and added to the ArrayAdapter

Using Arduino with Android!
Thought this was pretty neat. Will definitely have to try something like this once school starts.

