Monday, March 21, 2011

Sound, Vibrate and Data Storage etc.

1) How we play a sound in Android
Answer :- We use android.media.MediaPlayer.
Playing from a Raw Resource :- Perhaps the most common thing to want to do is play back media (notably sound) within your own applications. Doing this is easy:
Put the sound (or other media resource) file into the res/raw folder of your project, where the Eclipse plugin (or aapt) will find it and make it into a resource that can be referenced from your R class
Create an instance of MediaPlayer, referencing that resource using MediaPlayer.create, and then call start() on the instance:
         MediaPlayer mp = MediaPlayer.create(context, R.raw.sound_file_1);
         mp.start();

To stop playback, call stop(). If you wish to later replay the media, then you must reset() and prepare() the MediaPlayer object before calling start() again. (create() calls prepare() the first time.). To pause playback, call pause(). Resume playback from where you paused with start().

Playing from a File or Stream :- You can play back media files from the filesystem or a web URL:
Create an instance of the MediaPlayer using new
Call setDataSource() with a String containing the path (local filesystem or URL) to the file you want to play
First prepare() then start() on the instance:
      MediaPlayer mp = new MediaPlayer();
      mp.setDataSource(PATH_TO_FILE);
      mp.prepare();
      mp.start();

2) What is difference between prepare() and prepareAsync() 
Answer :- There are two ways (synchronous vs. asynchronous) that the Prepared state can be reached: either a call to prepare() (synchronous) which transfers the object to the Prepared state once the method call returns, or a call to prepareAsync() (asynchronous) which first transfers the object to the Preparing state after the call returns (which occurs almost right way) while the internal player engine continues working on the rest of preparation work until the preparation work completes. When the preparation completes or when prepare() call returns, the internal player engine then calls a user supplied callback method, onPrepared() of the OnPreparedListener interface, if an OnPreparedListener is registered beforehand via setOnPreparedListener(android.media.MediaPlayer.OnPreparedListener).
                                    The main difference is that when we use files then we call prepare() and when we use streams then we call prepareAsync().

3) How we play vibrate in Android 
Answer:-
android.os.Vibrator
public class VibrateGame
{
   Vibrator v;
   public VibrateGame(Context context)
  {
     v = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
  }
  public void vibrateGame(int ms)
  {
     v.vibrate(ms);
  }
}

4) What is SharedPreferences in Android and how we implement it ? 
Answer :- The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can useSharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).
To get a SharedPreferences object for your application, use one of two methods:
getSharedPreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter.
getPreferences() - Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name.

To write values:
1. Call edit() to get a SharedPreferences.Editor.
2. Add values with methods such as putBoolean() and putString().
3. Commit the new values with commit()
To read values, use SharedPreferences methods such as getBoolean() and getString().

// Create Object
SharedPreferences setting = getSharedPreferences("SAVE_FILE", 0);
SharedPreferences.Editor editor = setting.edit();

// For Store The Value
editor.putInt("ypad", canvas.ypad);
editor.putBoolean("up", canvas.up);
editor.commit();

// For Retrieving The Value
canvas.ypad = setting.getInt("ypad", 0);
canvas.up=setting.getBoolean("up", false);

What do u meant 0 and false in above ?
0 and false - Value to return if this preference does not exist. Throws ClassCastException if there is a preference with this name that is not a long

What do u mean by 0 in SharedPreferences setting = getSharedPreferences("SAVE_FILE", 0);
public abstract SharedPreferences getSharedPreferences (String filename, int mode)

There are 3 types of File creation mode:
0 - MODE_PRIVATE - the default mode, where the created file can only be accessed by the calling application
1 - MODE_WORLD_READABLE - allow all other applications to have read access to the created file.
2 - MODE_WORLD_WRITEABLE - allow all other applications to have write access to the created file.

5) How we implement SQLite in Android ?
Answer :- Android provides full support for SQLite databases. Any databases you create will be accessible by name to any class in the application, but not outside the application. The recommended method to create a new SQLite database is to create a subclass of SQLiteOpenHelper and override the onCreate() method, in which you can execute a SQLite command to create tables in the database. For example:

public class DictionaryOpenHelper extends SQLiteOpenHelper 
{
     private static final int DATABASE_VERSION = 2;
     private static final String DICTIONARY_TABLE_NAME = "dictionary";
     private static final String DICTIONARY_TABLE_CREATE =
     "CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" +
     KEY_WORD + " TEXT, " +
     KEY_DEFINITION + " TEXT);";

    DictionaryOpenHelper(Context context) {
         super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
     
    @Override
     public void onCreate(SQLiteDatabase db) {
          db.execSQL(DICTIONARY_TABLE_CREATE);
     }
}
You can then get an instance of your SQLiteOpenHelper implementation using the constructor you've defined. To write to and read from the database, call getWritableDatabase() and getReadableDatabase(), respectively. These both return a SQLiteDatabase object that represents the database and provides methods for SQLite operations.
Android does not impose any limitations beyond the standard SQLite concepts. We do recommend including an autoincrement value key field that can be used as a unique ID to quickly find a record. This is not required for private data, but if you implement a content provider, you must include a unique ID using the BaseColumns._ID constant.
You can execute SQLite queries using the SQLiteDatabase query() methods, which accept various query parameters, such as the table to query, the projection, selection, columns, grouping, and others. For complex queries, such as those that require column aliases, you should use SQLiteQueryBuilder, which provides several convienent methods for building queries.
Every SQLite query will return a Cursor that points to all the rows found by the query. The Cursor is always the mechanism with which you can navigate results from a database query and read rows and columns.


1 comment:

  1. very vary good..
    i like very much..
    keep it up .
    plz continue u r blogging ............

    ReplyDelete