Showing posts with label developer.android.com. Show all posts
Showing posts with label developer.android.com. Show all posts

Filling an adapter view with data in android

Filling an adapter view with data in android have two methods.

You can populate an AdapterView such as ListView or GridView by binding the AdapterView instance to an Adapter, which retrieves data from an external source and creates a View that represents each data entry.

Android provides several subclasses of Adapter that are useful for retrieving different kinds of data and building views for an AdapterView. T

1. ArrayAdapter
2. SimpleCursorAdapter

1. ArrayAdapter


Use this adapter when your data source is an array. By default, ArrayAdapter creates a view for each array item by calling toString() on each item and placing the contents in a TextView.
For example, if you have an array of strings you want to display in a ListView, initialize a new ArrayAdapter using a constructor to specify the layout for each string and the string array:
ArrayAdapter adapter = new ArrayAdapter<String>(this, 
        android
.R.layout.simple_list_item_1, myStringArray);
The arguments for this constructor are:
  • Your app Context
  • The layout that contains a TextView for each string in the array
  • The string array
Then simply call setAdapter() on your ListView:
ListView listView = (ListView) findViewById(R.id.listview);
listView
.setAdapter(adapter);

To customize the appearance of each item you can override the toString() method for the objects in your array. Or, to create a view for each item that's something other than a TextView (for example, if you want an ImageView for each array item), extend the ArrayAdapter class and override getView() to return the type of view you want for each item.

Example 1  Example 2  Example 3


2. SimpleCursorAdapter
Use this adapter when your data comes from a Cursor. When using SimpleCursorAdapter, you must specify a layout to use for each row in the Cursor and which columns in the Cursorshould be inserted into which views of the layout. For example, if you want to create a list of people's names and phone numbers, you can perform a query that returns a Cursor containing a row for each person and columns for the names and numbers. You then create a string array specifying which columns from the Cursor you want in the layout for each result and an integer array specifying the corresponding views that each column should be placed:
String[] fromColumns = {ContactsContract.Data.DISPLAY_NAME, 
                       
ContactsContract.CommonDataKinds.Phone.NUMBER};
int[] toViews = {R.id.display_name, R.id.phone_number};
When you instantiate the SimpleCursorAdapter, pass the layout to use for each result, the Cursor containing the results, and these two arrays:
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
        R
.layout.person_name_and_number, cursor, fromColumns, toViews, 0);
ListView listView = getListView();
listView
.setAdapter(adapter);
The SimpleCursorAdapter then creates a view for each row in the Cursor using the provided layout by inserting each fromColumns item into the corresponding toViews view.
.
If, during the course of your application's life, you change the underlying data that is read by your adapter, you should call notifyDataSetChanged(). This will notify the attached view that the data has been changed and it should refresh itself.

Example 1  Example 2  Example 3

Handling click events

You can respond to click events on each item in an AdapterView by implementing the AdapterView.OnItemClickListener interface. For example:

// Create a message handling object as an anonymous class.
private OnItemClickListener mMessageClickedHandler = new OnItemClickListener() {
   
public void onItemClick(AdapterView parent, View v, int position, long id) {
       
// Do something in response to the click
   
}
};

listView
.setOnItemClickListener(mMessageClickedHandler);



Sources: http://developer.android.com/guide/topics/ui/declaring-layout.html

Android Developer Tutorials

Android invasion, Sydney, Australia
Android invasion, Sydney, Australia (Photo credit: Pranav Bhatt)
  1. Building Your First App

    After you've installed the Android SDK, start with this class to learn the basics about Android app development.
    1. Creating an Android Project
    2. Running Your Application
    3. Building a Simple User Interface
    4. Starting Another Activity
  2. Managing the Activity Lifecycle

    How Android activities live and die and how to create a seamless user experience by implementing lifecycle callback methods.
    1. Starting an Activity
    2. Pausing and Resuming an Activity
    3. Stopping and Restarting an Activity
    4. Recreating an Activity
  3. Supporting Different Devices

    How to build your app with alternative resources that provide an optimized user experience on multiple device form factors using a single APK.
    1. Supporting Different Languages
    2. Supporting Different Screens
    3. Supporting Different Platform Versions
  4. Building a Dynamic UI with Fragments

    How to build a user interface for your app that is flexible enough to present multiple UI components on large screens and a more constrained set of UI components on smaller screens—essential for building a single APK for both phones and tablets.
    1. Using the Support Library
    2. Creating a Fragment
    3. Building a Flexible UI
    4. Communicating with Other Fragments
  5. Saving Data

    How to save data on the device, whether it's temporary files, downloaded app assets, user media, structured data, or something else.
    1. Saving Key-Value Sets
    2. Saving Files
    3. Saving Data in SQL Databases
  6. Interacting with Other Apps

    How to build a user experience that leverages other apps available on the device to perform advanced user tasks, such as capture a photo or view an address on a map.
    1. Sending the User to Another App
    2. Getting a Result from the Activity
    3. Allowing Other Apps to Start Your Activity
  7. Sharing Content

    How to take your app interaction to the next level by sharing information with other apps, receive information back, and provide a simple and scalable way to perform Share actions with user content.
    1. Sending Content to Other Apps
    2. Receiving Content from Other Apps
    3. Adding an Easy Share Action
Enhanced by Zemanta

Saving Activity state in Android

 
The introduction to Managing the Activity Lifecycle briefly mentions that when an activity is paused or stopped, the state of the activity is retained. This is true because the Activity object is still held in memory when it is paused or stopped—all information about its members and current state is still alive. Thus, any changes the user made within the activity are retained so that when the activity returns to the foreground (when it "resumes"), those changes are still there.

You need to override onSaveInstanceState(Bundle savedInstanceState) and write the application state values you want to change to the Bundle parameter like this:

Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState
.putBoolean("MyBoolean", true);
savedInstanceState
.putDouble("myDouble", 1.9);
savedInstanceState
.putInt("MyInt", 1);
savedInstanceState
.putString("MyString", "Welcome back to Android");
// etc.
}
The Bundle is essentially a way of storing a NVP ("Name-Value Pair") map, and it will get passed in to onCreate and also onRestoreInstanceState where you'd extract the values like this:
 
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
double myDouble = savedInstanceState.getDouble("myDouble");
int myInt = savedInstanceState.getInt("MyInt");
String myString = savedInstanceState.getString("MyString");
}
 
You'd usually use this technique to store instance values for your application (selections, unsaved text, etc.).

CAREFUL: you need to call super.onSaveInstanceState(savedInstanceState) before adding your values to the Bundle, or they will get wiped out on that call (Droid X Android 2.2).

The savedInstanceState is only for saving state associated with a current instance of an Activity, for example current navigation or selection info, so that if Android destroys and recreates an Activity, it can come back as it was before. See the documentation for onCreate and onSaveInstanceState
For more long lived state, consider using a SQLite database, a file, or preferences. See Saving Persistent State.

Resources:
http://developer.android.com/guide/components/activities.html
http://stackoverflow.com/questions/151777/saving-activity-state-in-android

The DDMS Perspective


The DDMS Perspective in Eclipse lets you access all of the features of DDMS from within the Eclipse IDE. The following sections of DDMS are available to you:
  • Devices - Shows the list of devices and AVDs that are connected to ADB.
  • Emulator Control - Lets you carry out device functions.
  • LogCat - Lets you view system log messages in real time.
  • Threads - Shows currently running threads within a VM.
  • Heap - Shows heap usage for a VM.
  • Allocation Tracker - Shows the memory allocation of objects.
  • File Explorer - Lets you explore the device's file system.
To access the DDMS perspective, go to Window > Open Perspective > DDMS. If DDMS does not appear, go to Window > Open Perspective > Other ... and select DDMS from the Open Perspective window that appears. For more information on using DDMS, see Using the Dalvik Debug Monitor Server.