ADB Basic Commands and Setup Tutorial

Recently, I was asked to flash a custom ROM to several Android devices that Samsung seems to forget to update. These devices include:

1. Galaxy Tab 10.1 (GT-P7500) – Upgraded from Android 3.2 Honeycomb to 4.2 Jelly Bean

2. Galaxy Tab 8.9 (GT-P7300) – Upgraded from Android 3.2 Honeycomb to 4.2 Jelly Bean

3. Galaxy Mini (GT-S5570) – Upgraded from Android 2.3 Froyo to 4.1 Jelly Bean

I was delighted seeing these old devices run with the Jelly Bean OS.

Please note that I actually have no plans of posting how to root and upgrade certain devices here in our blog. (But if many of you insists, I may change my mind haha!)

This is because there are already a lots of resources on other sites, especially in the XDA-Developers forum.

In my experience, rooting and flashing a custom ROM to your device may take a lot of trial and error. One blog post may not work for you, so you have to look on other blog post or forums and maybe combine their instructions or installation files for your device to work.

So, this tutorial will just cover some ADB commands that I learned and can be useful when doing such tasks. This list can be your reference too!

This ADB basic commands and setup tutorial post covers following:

1.0 What is ADB?
2.0 Where can I get ADB?
3.0 How to run the ADB?

3.1 Open Command Prompt
3.2 Find adb.exe

4.0 ADB Basic Commands

4.1 adb
4.2 adb devices

4.2.1 adb kill-server
4.2.2 adb start-server

4.3 adb shell

4.3.1 ls
4.3.2 exit
4.3.3 cd
4.3.4 rm
4.3.5 cp

4.4 adb push
4.5 adb pull
4.6 adb install
4.7 adb reboot
4.8 adb reboot recovery
4.9 adb logcat

1.0 What is ADB?

First off, for those who have no idea what ADB is, ADB stands for Android Debug Bridge. Basically, it is a command line interface that lets you communicate from PC to your Android device or emulator.

On windows, it is an .exe file where you can execute some commands (see section 4.0 below) with the help of command prompt (cmd.exe).

2.0 Where can I get ADB?

I used the ADB from the Android ADT Bundle we installed, yes it is with the Android developmenet environment files. I actually wrote a post regarding its installation. You can find it in the path: YourADT_Folder > sdk > platform-tools > adb.exe

3.0 How To Run The ADB?

Easy, just follow the steps below:

3.1. Open your command prompt.

On windows, you can type on the search box “cmd.exe” and then press enter. It will pop up a really cool black window.

adb basic commands

3.2 Find your adb.exe

Go to your ADT folder > sdk > platform-tools

Copy the path, go back to the black window, right click then paste it there. After pasting, press enter. See screenshots below:

adb adt folder

adb.exe location on my PC.

adb cmd paste

To paste the path, just do a right click and select “Paste”

adb directory

After pasting, press you enter key. Now you’re insde the adb directory. Enjoy the ADB commands below. :D

4.0 ADB Basic Commands

4.1 Make sure ADB is working by typing the “adb” command (see the yellow underline below). The output will look like this:

adb command basic

4.2 Know what Android devices were attached on your computer by typing the “adb devices” command.

adb devices

4.2.1 If it can’t connect to your device, first, you have to do an adb kill-server command

4.2.2 And then, do an adb start-server command, and re-execute adb devices

4.3 Begin a shell connection with your Android device by typing the “adb shell” command. More about shell here.

adb shell command

4.3.1 Know what files and directories are in your Android device by typing the “ls” command

adb ls command

4.3.2 If you think you’re done with the shell connection, you can exit it by typing the “exit” command, and now you’re out of the shell mode.

adb shell exit command

4.3.3 Change directories by using the “cd” command. Sample use:

cd /sdcard/my_folder

4.3.4 If you want to remove a file from your device, here’s the “rm” command. Sample use:

rm /sdcard/my_folder/my_text_file.txt

4.3.5 copy file from one directory to another with the “cp” command. Sample use:

cp /sdcard/my_old_folder/my_text_file.txt /sdcard/my_new_folder/my_text_file.txt

4.4 Copy file from PC to android device using the “adb push”

file to be pushed

File to be pushed.

Execute the command.

Execute the command.

File were pushed on the Android device.

File were pushed on the Android device.

4.5 Get file from Android device to your PC by using the “adb pull” command. Sample use:

adb pull /sdcard/my_file.zip c:\my_file.zip

4.6 If you have an APK installer file in your PC, you can also install it using the ADB via “adb install” command. Sample use:

adb install c:\your_app.apk

4.7adb reboot command will simply reboot your Android device.

4.8adb reboot recovery will reboot your device in recovery mode.

4.8adb logcat is useful when you’re making an app and debugging. Eclipse also provide this functionality.

If you think I missed something important that should be on this list, please feel free to leave a comment below, I’m more than willing to udpate this post. Hope this ADB basic commands list help you get started!

Android Navigation Drawer Example Step by Step

android navigation drawer horizontal open

Android Navigation drawer is now a standard when creating an Android app.

It gives a better user experience since the user can easily access more app functionality – on a small screen smartphone.

Personally, it is really fun to use since I just have to swipe a finger to use or access a view.

This post is a step by step guide on how to create a navigation drawer for your Android app.

Read more

Android Action Bar Tutorial with 2.2+ Compatibility

I have an Android Action Bar Tutorial for you guys! Android ActionBar looks good on our smartphone apps and at the same time, it is really useful. Aside from displaying your app’s title or section, the ActionBar can also be used as a back function (upper left) or a viewable button or dropdown options (upper right).

android action bar tutorial

This is a step by step guide on how you can create an ActionBar for your awesome Android app. I’ll walk you through the process of creating a very simple but awesome android ActionBar. Let’s get started!

Read more

Android Intents Tutorial to Share Your Social Media Links

The following Android intents tutorial will help increase your app’s Facebook likes or twitter followers. Almost every app has their own social media accounts or links that you can like, follow, +1, or even send an email to. There’s always an app that can connect you to that product or service.

Android Intents Tutorial to Share Your Social Media Links

Now, from that app, a user must be able to view your accounts effortlessly and in a standard, native and beautiful way. Don’t just throw a browser with a link to a social media account, impress your users by opening it in the native app! The most commonly used social media apps are Facebook, Twitter and Google Plus.

Those are covered in this post, but with the additional Browser and GMail intents! For this code’s demo, see our Android Intents video demo below.

Video Demo Permalink

DOWNLOAD APP

By the way, the app on the demo above is this blog’s official browser app. You might want to download it on Google Play. I didn’t have enough time to develop that app due to my busy schedule. But it is working fine, try it out!

Contents:

1.0 Facebook Intent in Android
2.0 Google Plus Intent in Android
3.0 Twitter Intent in Android
4.0 Browser Intent in Android
5.0 GMail Intent in Android
6.0 How to Check If An App Is Installed in Android?

1.0 Facebook Intent in Android

Here’s how my app show that Facebook page.
Step 1: Go to the FB page and get the Facebook page name using the URL, in my case, it is “CodeOfANinja”
https://www.facebook.com/CodeOfANinja
You can also get the Facebook page ID using the graph API URL, for example
http://graph.facebook.com/CodeOfANinja
…and see the “id”: “107786425949934″ on that JSON string.

Step 2: Use the method below on your Listener, just replace the Facebook page name or ID. You can also use some parameters on this method if you’re opening multiple Facebook pages.

public void openFacebookPage() {
Intent i = null;

try {
context.getPackageManager().getPackageInfo(“com.facebook.katana”, 0);

// replace 107786425949934 with your page ID
i = new Intent(Intent.ACTION_VIEW, Uri.parse(“fb://profile/107786425949934″));

} catch (Exception e) {

// replace CodeOfANinja with your page name
i = new Intent(Intent.ACTION_VIEW, Uri.parse(“https://www.facebook.com/CodeOfANinja”));
}

checkIfAppExists(i, “Facebook”);

}

2.0 Google Plus Intent in Android

Calling the official Google Plus app to show the Google+ page of your customers would be great. That’s one feature I already worked with and now I’m ready to show you the working code I used.
Here’s how I did it:
Step 1: Go to the Google+ Page and copy the page ID. In my case, it is: 101266899643014043497
https://plus.google.com/101266899643014043497/posts

Step 2: Add the following code in your file or utility class.

public void openGooglePlusPage(String googlePlusId){
Intent i = new Intent(Intent.ACTION_VIEW);
i.setClassName(“com.google.android.apps.plus”, “com.google.android.apps.plus.phone.UrlGatewayActivity”);
i.putExtra(“customAppUri”, googlePlusId);
startActivity(i);

checkIfAppExists(i, “Google Plus”);
}

How to use? Just call the function with the ID you got in step 1.

openGooglePlusPage("101266899643014043497");

3.0 Twitter Intent in Android

Here’s how my app show that Twitter page.
Step 1: Get the Twitter page username, in my case, it is “ninjazhai”
https://twitter.com/ninjazhai

Step 2: Add the following method on your project or utility class.

public void openTwitterPage(String username){
Intent i = null;

try {

// use the twitter app
i = new Intent(Intent.ACTION_VIEW, Uri.parse(“twitter://user?screen_name=” + username));

}catch (Exception e) {

// try to use other intent
i = new Intent(Intent.ACTION_VIEW, Uri.parse(“https://twitter.com/#!/” + username));
}

checkIfAppExists(i, “Twitter”);
}

How to use the method above? Remember the twitter username you got on step 1 and put code below on your click listener:

openTwitterPage("ninjazhai");

4.0 Browser Intent in Android

This time we are going to take a look at the browser intent filter in android. I used this one when I want my users have the ability to view the subscribe form of this blog. This code basically answers the question “How do I show a web page from my app to a web browser?”
Here’s the working code I used. Just follow this two step guide.
Step 1: Of course, prepare the URL you wanted to be shown. In my case, it was:
http://feedburner.google.com/fb/a/mailverify?uri=TheCodeOfANinja

Step 2: Add this method to your JAVA file or utility class.

public void openUrl_InBrowser(String url){
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));

checkIfAppExists(i, “Web Browser”);

}

How to use? easy, you can do it this way.

openUrl_InBrowser("http://feedburner.google.com/fb/a/mailverify?uri=TheCodeOfANinja");

5.0 Gmail Intent in Android

You can use this code when you want your users to have the ability to send email from your app, for example is the app feature where the users can send feedback, comments or suggestions directly to any given email address.

This code will open the Gmail App with the help of android intent filter.

Now you can add this code to your project or utility class.

public void openGmailApp(String[] emailAddresses, String subject, String text){
Intent i = new Intent(Intent.ACTION_VIEW);
i.setType(“plain/text”);
i.setClassName(“com.google.android.gm”, “com.google.android.gm.ComposeActivityGmail”);
i.putExtra(Intent.EXTRA_EMAIL, emailAddresses);
i.putExtra(Intent.EXTRA_SUBJECT, subject);
i.putExtra(Intent.EXTRA_TEXT, text);
checkIfAppExists(i, “Gmail”);

}

And you can use the method above this way:

// you can try to add more email in this array: new String[] { "ninjazhai30@gmail.com", "email2@yahoo.com" }
// if you're going to send the message to multiple people
openGmailApp(
new String[] { “ninjazhai30@gmail.com” },
“Feedback for The Code of a Ninja Programming Blog”,
“Sent using The Code of a Ninja Android App:nn“
);

6.0 How to Check If An App Is Installed in Android?

Before a specific app will run, we have to verify if that app exists or installed in the device. This will enable us to tell the user that a certain app must be installed before using a feature. This prevents showing an error or force close message, so it is good for the user experience. The method below will show us the way.

Checking if an app is installed in the Android device is required if you are going to start another applications’s intent. There are other ways to do this but the code below is what’s working for me.

I used and tested this code when I wanted to start an intent to some apps like:

  • Facebook
  • Twitter
  • Google Plus
  • Browser
  • Gmail
// method to check whether an app exists or not
public void checkIfAppExists(Intent appIntent, String appName){

if (appIntent.resolveActivity(context.getPackageManager()) != null) {

// start the activity if the app exists in the system
startActivity(appIntent);

} else {

// tell the user the app does not exist
Toast.makeText(context, appName + ” app does not exist!”, Toast.LENGTH_LONG).show();
}
}

Sample Usage: Below is the code I used when I want to open my google plus page with the Google+ official android app.

Intent i = new Intent(Intent.ACTION_VIEW);
i.setClassName("com.google.android.apps.plus", "com.google.android.apps.plus.phone.UrlGatewayActivity");
i.putExtra("customAppUri", "101266899643014043497");
startActivity(i);
checkIfAppExists(i, “Google Plus”);

You can read more about Android intents here.

Fixing Android EditText Lag

Lately I encountered this annoying android EditText lag, each time I try to type a character, it makes me wait for around 1 to 3 seconds before I can type the next character! Now that’s horrible. EditText is not useful. Keyboard looks broken.

Fixing Android EditText Lag

If you have the same issue, I have a good news for you, I found a fix! Now take a look at the code below.

Old Code

This is the XML layout I used for my customized search bar, and it is very laggy.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/tvSearchBy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:padding="10dp"
        android:text="u25BC" />

    <TextView
        android:id="@+id/tvSearchButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="1dp"
        android:layout_marginTop="1dp"
        android:background="#d1d1d1"
        android:padding="10dp"
        android:text="Search" />

    <EditText
        android:id="@+id/autoCompleteTv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_toLeftOf="@+id/tvSearchButton"
        android:layout_toRightOf="@+id/tvSearchBy"
        android:hint="Type..."
        android:padding="10dp"
        android:singleLine="true"
        android:text="" />

</RelativeLayout>

New Code

Now here’s a fix. The code below makes everything smooth and feel good.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/tvSearchBy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="u25BC" />

    <EditText
        android:id="@+id/autoCompleteTv"
        android:layout_width="220dp"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:hint="Type..."
        android:padding="10dp"
        android:singleLine="true"
        android:text="" />

    <TextView
        android:id="@+id/tvSearchButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="1dp"
        android:layout_marginTop="1dp"
        android:background="#d1d1d1"
        android:padding="10dp"
        android:text="Search" />

</LinearLayout>

The Solution

So what’s the actual solution? Avoid using EditText inside a RelativeLayout, use LinearLayout instead. According to James, If you look at the DDMS, a lot of redraws and recalculations occur while entering the text which is related to the RelativeLayout. So that gives us a clue the the problem is indeed the RelativeLayoutUpdate: I forgot to mention that setting a fixed with of an EditText will help a lot with the performance. It prevents re-calculation and re-drawing of layout. Thanks to Giorgos Kylafas for pointing it out in the comments section below! He also included links that can be useful for you when it comes to Android performance tips so I suggest reading his comment.

Did you have the same experience? If this solution did not work for you and you found your own solution, please share it in the comments section below, I’m willing to include your story and update this post!

Fixed: Android Dependencies – Missing facebooksdk.jar

Recently I was working with the Facebook SDK for Android and found the error:     Android     Dependencies     –     Missing     facebooksdk.jar. My project was unable to run and the eclipse console or logcat does not give a clear description of the error.

Home>Android Fixed: Android Dependencies – Missing facebooksdk.jar

But it can be seen when you try to view the properties > java build path > libraries tab > android dependencies of your project.
It looks like the project is looking for the facebooksdk.jar in the Facebook SDK bin folder. But it was missing. I wasn’t able to found a fix after around 30 minutes of googling the error. I don’t know, maybe my google skills are just failing me.
But the good thing is I was able to fixed this error myself. And here is the solution:

Right click on your project > properties > java compiler > compiler compliance level > select 1.7 on the dropdown.

Wait for a while while eclipse re-builds the workspace. Suddenly it was fixed!
Sorry I was too lazy to put up some screenshots, this is just a quick post that I thought can be useful to some devs. As always, thanks for reading!

Android ListView with Adapter Example

How android ListView with adapter works is not so clear to me until I read this awesome article with code examples of Lucas Rocha: Performance Tips for Android’s ListView.

In relation to that, I was inspired again to make a post about android ListView with Adapter, but this one is much more simple than the previous post: How To Customize Android ListView?

Today I’m going to show you the code I use whenever I wanted the user to select an “item” in an AlertDialog with ListView. If you are looking for an example AlertDialog with simple ListView (without an adapter), here’s a blog post I made: Android AlertDialog with ListView.

A ListView item here contains a text (item name) and an ID (item ID), so whenever the user selects an item in the pop up, you’ll be able to get the text and ID of that selected item.
This is very useful if the items are from a database – records with IDs and names. The tags (item IDs) were set using the TextView’s setTag() method.

Video Demo

Here’s the final output of our code for today. Name and ID were fetched and show via toast.

Video Demo Permalink

DOWNLOAD CODE

Let’s Code!

We only need 6 files to run this sample code successfully.
1. activity_main.xml – our main layout. Our trigger to show the ListView is a button.

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

    <Button
        android:id="@+id/buttonShowPopUp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Show AlertDialog with ListView" />

</RelativeLayout>

2. MainActivity.java – will show the main layout, a button at the center of the screen. Clicking that button will show our awesome ListView.

package com.example.listviewpopupwithadapter;

import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.app.Activity;
import android.app.AlertDialog;

public class MainActivity extends Activity {

    AlertDialog alertDialogStores;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // a button to show the pop up with a list view
        View.OnClickListener handler = new View.OnClickListener(){
            public void onClick(View v) {
                switch (v.getId()) {

                    case R.id.buttonShowPopUp:
                        showPopUp();
                        break;
                }
            }
        };
        
        findViewById(R.id.buttonShowPopUp).setOnClickListener(handler);
        
    }
    
    public void showPopUp(){
        
        // add your items, this can be done programatically
        // your items can be from a database
        ObjectItem[] ObjectItemData = new ObjectItem[20];
        
        ObjectItemData[0] = new ObjectItem(91, "Mercury");
        ObjectItemData[1] = new ObjectItem(92, "Watson");
        ObjectItemData[2] = new ObjectItem(93, "Nissan");
        ObjectItemData[3] = new ObjectItem(94, "Puregold");
        ObjectItemData[4] = new ObjectItem(95, "SM");
        ObjectItemData[5] = new ObjectItem(96, "7 Eleven");
        ObjectItemData[6] = new ObjectItem(97, "Ministop");
        ObjectItemData[7] = new ObjectItem(98, "Fat Chicken");
        ObjectItemData[8] = new ObjectItem(99, "Master Siomai");
        ObjectItemData[9] = new ObjectItem(100, "Mang Inasal");
        ObjectItemData[10] = new ObjectItem(101, "Mercury 2");
        ObjectItemData[11] = new ObjectItem(102, "Watson 2");
        ObjectItemData[12] = new ObjectItem(103, "Nissan 2");
        ObjectItemData[13] = new ObjectItem(104, "Puregold 2");
        ObjectItemData[14] = new ObjectItem(105, "SM 2");
        ObjectItemData[15] = new ObjectItem(106, "7 Eleven 2");
        ObjectItemData[16] = new ObjectItem(107, "Ministop 2");
        ObjectItemData[17] = new ObjectItem(108, "Fat Chicken 2");
        ObjectItemData[18] = new ObjectItem(109, "Master Siomai 2");
        ObjectItemData[19] = new ObjectItem(110, "Mang Inasal 2");
        
        // our adapter instance
        ArrayAdapterItem adapter = new ArrayAdapterItem(this, R.layout.list_view_row_item, ObjectItemData);
        
        // create a new ListView, set the adapter and item click listener
        ListView listViewItems = new ListView(this);
        listViewItems.setAdapter(adapter);
        listViewItems.setOnItemClickListener(new OnItemClickListenerListViewItem());
        
        // put the ListView in the pop up
        alertDialogStores = new AlertDialog.Builder(MainActivity.this)
            .setView(listViewItems)
            .setTitle("Stores")
            .show();
        
    }

    
}

3. ObjectItem.java – each item in the list is considered as an object with name and ID.

package com.example.listviewpopupwithadapter;

//another class to handle item's id and name
public class ObjectItem {
    
    public int itemId;
    public String itemName;
    
    // constructor
    public ObjectItem(int itemId, String itemName) {
        this.itemId = itemId;
        this.itemName = itemName;
    }

}

4. ArrayAdapterItem.java – where our ListView performance depends.

package com.example.listviewpopupwithadapter;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

// here's our beautiful adapter
public class ArrayAdapterItem extends ArrayAdapter<ObjectItem> {

    Context mContext;
    int layoutResourceId;
    ObjectItem data[] = null;

    public ArrayAdapterItem(Context mContext, int layoutResourceId, ObjectItem[] data) {

        super(mContext, layoutResourceId, data);
        
        this.layoutResourceId = layoutResourceId;
        this.mContext = mContext;
        this.data = data;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        /*
         * The convertView argument is essentially a "ScrapView" as described is Lucas post 
         * http://lucasr.org/2012/04/05/performance-tips-for-androids-listview/
         * It will have a non-null value when ListView is asking you recycle the row layout. 
         * So, when convertView is not null, you should simply update its contents instead of inflating a new row layout.
         */
        if(convertView==null){
            // inflate the layout
            LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
            convertView = inflater.inflate(layoutResourceId, parent, false);
        }
        
        // object item based on the position
        ObjectItem objectItem = data[position];
        
        // get the TextView and then set the text (item name) and tag (item ID) values
        TextView textViewItem = (TextView) convertView.findViewById(R.id.textViewItem);
        textViewItem.setText(objectItem.itemName);
        textViewItem.setTag(objectItem.itemId);

        return convertView;
        
    }
    
}

5. OnItemClickListenerListViewItem.java – answers what will happen if the user clicks an item in the list?

package com.example.listviewpopupwithadapter;

import android.content.Context;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.Toast;

/*
 * Here you can control what to do next when the user selects an item
 */
public class OnItemClickListenerListViewItem implements OnItemClickListener {

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Context context = view.getContext();
        
        TextView textViewItem = ((TextView) view.findViewById(R.id.textViewItem));
        
        // get the clicked item name
        String listItemText = textViewItem.getText().toString();
        
        // get the clicked item ID
        String listItemId = textViewItem.getTag().toString();
        
        // just toast it
        Toast.makeText(context, "Item: " + listItemText + ", Item ID: " + listItemId, Toast.LENGTH_SHORT).show();

        ((MainActivity) context).alertDialogStores.cancel();
        
    }
    
}

6. list_view_row_item.xml – the layout of each item in the list. You can modify this if you want to have an image or subtitle for each item of your ListView.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp" >

    <TextView
        android:id="@+id/textViewItem"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:text="Item name here..."
        android:textSize="15dp" />

</RelativeLayout>

This is just the first part, the second part will be about the Android ListView performance optimization with the help of Android ViewHolder Design Pattern.

Please share your thoughts about this Android ListView with Adapter Example!

How to Use Joda Time in Eclipse?

Joda Time is another very useful library for your Android application development. It provides a quality library of classes to replace the Java JDK Date and Time classes.

This post is generally about how to import a library in eclipse for Android development, we just choose Joda Time library as a good example. Every time I have a post instructing to install a library, I’ll probably link into this post.

Ok, back to our main topic.

Why use Joda Time? Well, there are plenty of reasons, some include:

  • Easy to use – straightforward field accessors such as getDayOfWeek()
  • Up-to-date time zone calculations – based on public tz database
  • Maturity – active development since 2002, and
  • Open source (Apache).

It can save you a lot of time for tasks such as:

Joda Time: Step by Step

Step 1: Download the latest version of Joda Time.

How to Use Joda Time in Eclipse?

Download joda time in source forge.

Step 2: Extract the ZIP and find the JAR file.

Files included in the zip.

Files included in the zip.

Step 3,: Copy to JAR file to your project’s libs folder.

> Ctrl+C the Jar file
> find your libs folder (My libs folder is located in my c:/workspace/MyProject/libs/),
> and then Ctrl+V (paste) it there.

Refreshing (Click+F5) your project would look like this:

joda-time-jar-in-eclipse-copy

Step 4: Add the JAR file to your build path.

> Right click your project
> java build path
> libraries tab
> add jars button
> browse the joda time jar file in the libs folder
> order and export tab
> check the joda time jar file

If you want some visuals for this step 4, see this one:

Video Demo Permalink

Step 5: Test. You can have the following code on your sample project to see if it works.

We’ll have this code on our MainActivity.java

package com.example.jodatimeexample;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.joda.time.DateTime;
import org.joda.time.Days;

import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        String textViewContents = "Joda Time Results:nn";
        
        TextView tv = (TextView) findViewById(R.id.tvDisplay);
        tv.setText(textViewContents);
        
        
        int daysBetween = getNumDaysBetween("2013-09-01", "2013-09-02");
        tv.setText("Days between 2013-09-01 and 2013-09-02: " + daysBetween);
        
    }

    public int getNumDaysBetween(String dateStart, String dateEnd){
        
        int numDays = 0;
        
        try{
            
            SimpleDateFormat formatYmd = new SimpleDateFormat("yyyy-MM-dd");
         
            Date d1 = formatYmd.parse(dateStart);
            Date d2 = formatYmd.parse(dateEnd);
    
            DateTime dt1 = new DateTime(d1);
            DateTime dt2 = new DateTime(d2);
            
            numDays = Days.daysBetween(dt1, dt2).getDays();
            
            // Days between 2013-09-01 and 2013-09-02: 1
            
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return numDays;
    }
    
}

activity_main.xml (layout file) used:

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

    <TextView
        android:id="@+id/tvDisplay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Loading value..." />

</RelativeLayout>

The TextView will hold the output when you run the code above, and should look like this:

Days between 2013-09-01 and 2013-09-02: 1

Download Code

Just in case you want to download the code we used: JodaTimeExample.zip

Further Readings

As for some pros and cons of using Joda Time, see Jon’s answer here.

Since Joda Time is another API to learn, you’ll need more examples codes, here are some few hundred Joda Time code examples.