Android Custom Fonts

August 12,2016

In android, you can define your own custom fonts for the strings in your application. You just need to download the required font from the internet, and then place it in assets/fonts folder.

After putting fonts in the assets folder under fonts folder, you can access it in your java code through Typeface class. First , get the reference of the text view in the code. Its syntax is given below −

TextView tx = (TextView)findViewById(R.id.textview1);

The next thing you need to do is to call static method of Typeface class createFromAsset() to get your custom font from assets. Its syntax is given below −

Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/font name.ttf");

The last thing you need to do is to set this custom font object to your TextView Typeface property. You need to call setTypeface() method to do that. Its syntax is given below −

tx.setTypeface(custom_font);

Apart from these Methods, there are other methods defined in the Typeface class , that you can use to handle Fonts more effectively.

Sr.No Method & description
1 create(String familyName, int style)

Create a Typeface object given a family name, and option style information

2 create(Typeface family, int style)

Create a Typeface object that best matches the specified existing Typeface and the specified Style

3 createFromFile(String path)

Create a new Typeface from the specified font file

4 defaultFromStyle(int style)

Returns one of the default Typeface objects, based on the specified style

5 getStyle()

Returns the Typeface’s intrinsic style attributes

Android Camera

August 11,2016

These are the following two ways, in which you can use camera in your application

  • Using existing android camera application in our application
  • Directly using Camera API provided by android in our application

Using existing android camera application in our application

You will use MediaStore.ACTION_IMAGE_CAPTURE to launch an existing camera application installed on your phone. Its syntax is given below

Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

Apart from the above, there are other available Intents provided by MediaStore. They are listed as follows

Sr.No Intent type and description
1 ACTION_IMAGE_CAPTURE_SECURE

It returns the image captured from the camera , when the device is secured

2 ACTION_VIDEO_CAPTURE

It calls the existing video application in android to capture video

3 EXTRA_SCREEN_ORIENTATION

It is used to set the orientation of the screen to vertical or landscape

4 EXTRA_FULL_SCREEN

It is used to control the user interface of the ViewImage

5 INTENT_ACTION_VIDEO_CAMERA

This intent is used to launch the camera in the video mode

6 EXTRA_SIZE_LIMIT

It is used to specify the size limit of video or image capture size

Bluetooth

August 10,2016

Android provides Bluetooth API to perform these different operations.

  • Scan for other Bluetooth devices
  • Get a list of paired devices
  • Connect to other devices through service discovery

Android provides BluetoothAdapter class to communicate with Bluetooth. Create an object of this calling by calling the static method getDefaultAdapter(). Its syntax is given below.

private BluetoothAdapter BA;
BA = BluetoothAdapter.getDefaultAdapter();

In order to enable the Bluetooth of your device, call the intent with the following Bluetooth constant ACTION_REQUEST_ENABLE. Its syntax is.

Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);

Apart from this constant, there are other constants provided the API , that supports different tasks. They are listed below.

Sr.No Constant & description
1 ACTION_REQUEST_DISCOVERABLE

This constant is used for turn on discovering of bluetooth

2 ACTION_STATE_CHANGED

This constant will notify that Bluetooth state has been changed

3 ACTION_FOUND

This constant is used for receiving information about each device that is discovered

Once you enable the Bluetooth , you can get a list of paired devices by calling getBondedDevices() method. It returns a set of bluetooth devices. Its syntax is.

private Set<BluetoothDevice>pairedDevices;
pairedDevices = BA.getBondedDevices();

Apart form the parried Devices , there are other methods in the API that gives more control over Blueetooth. They are listed below.

Sr.No Method & description
1 enable()

This method enables the adapter if not enabled

2 isEnabled()

This method returns true if adapter is enabled

3 disable()

This method disables the adapter

4 getName()

This method returns the name of the Bluetooth adapter

5 setName(String name)

This method changes the Bluetooth name

6 getState()

This method returns the current state of the Bluetooth Adapter.

7 startDiscovery()

This method starts the discovery process of the Bluetooth for 120 seconds.

Android – Auto Complete

August 9,2016

In order to use AutoCompleteTextView you have to first create an AutoCompletTextView Field in the xml. Its syntax is given below.

<AutoCompleteTextView
   android:id="@+id/autoCompleteTextView1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignParentTop="true"
   android:layout_centerHorizontal="true"
   android:layout_marginTop="65dp"
   android:ems="10" >

After that, you have to get a reference of this textview in java. Its syntax is given below.

private AutoCompleteTextView actv;
actv = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);

The the next thing you need to do is to specify the list of suggestions items to be displayed. You can specify the list items as a string array in java or in strings.xml. Its syntax is given below.

String[] countries = getResources().getStringArray(R.array.list_of_countries);
ArrayAdapter<String> adapter = new ArrayAdapter<String>
   (this,android.R.layout.simple_list_item_1,countries);
actv.setAdapter(adapter);

The array adapter class is responsible for displaying the data as list in the suggestion box of the text field. The setAdapter method is used to set the adapter of the autoCompleteTextView. Apart from these methods, the other methods of Auto Complete are listed below.

Sr.No Method & description
1 getAdapter()

This method returns a filterable list adapter used for auto completion

2 getCompletionHint()

This method returns optional hint text displayed at the bottom of the the matching list

3 getDropDownAnchor()

This method returns returns the id for the view that the auto-complete drop down list is anchored to.

4 getListSelection()

This method returns the position of the dropdown view selection, if there is one

5 isPopupShowing()

This method indicates whether the popup menu is showing

6 setText(CharSequence text, boolean filter)

This method sets text except that it can disable filtering

7 showDropDown()

This method displays the drop down on screen.

Audio Manager

August 8,2016

In order to use AndroidManager class, you have to first create an object of AudioManager class by calling the getSystemService() method. Its syntax is given below.

private AudioManager myAudioManager;
myAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);

Once you instantiate the object of AudioManager class, you can use setRingerMode method to set the audio or ringer profile of your device. Its syntax is given below.

myAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);

The method setRingerMode takes an integer number as a parameter. For each mode , an integer number is assigned that will differentiate between different modes. The possible modes are.

Sr.No Mode & Description
1 RINGER_MODE_VIBRATE

This Mode sets the device at vibrate mode.

2 RINGER_MODE_NORMAL

This Mode sets the device at normal(loud) mode.

3 RINGER_MODE_SILENT

This Mode sets the device at silent mode.

Once you have set the mode , you can call the getRingerMode() method to get the set state of the system. Its syntax is given below.

int mod = myAudioManager.getRingerMode();

Apart from the getRingerMode method, there are other methods available in the AudioManager class to control the volume and other modes. They are listed below.

Sr.No Method & description
1 adjustVolume(int direction, int flags)

This method adjusts the volume of the most relevant stream

2 getMode()

This method returns the current audio mode

3 getStreamMaxVolume(int streamType)

This method returns the maximum volume index for a particular stream

4 getStreamVolume(int streamType)

This method returns the current volume index for a particular stream

5 isMusicActive()

This method checks whether any music is active.

6 startBluetoothSco()

This method Start bluetooth SCO audio connection

7 stopBluetoothSco()

This method stop bluetooth SCO audio connection.

Audio Capture

August 5,2016

Android has a built in microphone through which you can capture audio and store it , or play it in your phone. There are many ways to do that but the most common way is through MediaRecorder class.

Android provides MediaRecorder class to record audio or video. In order to use MediaRecorder class ,you will first create an instance of MediaRecorder class. Its syntax is given below.

MediaRecorder myAudioRecorder = new MediaRecorder();

Now you will set the source , output and encoding format and output file. Their syntax is given below.

myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);

After specifying the audio source and format and its output file, we can then call the two basic methods prepare and start to start recording the audio.

myAudioRecorder.prepare();
myAudioRecorder.start();

Apart from these methods , there are other methods listed in the MediaRecorder class that allows you more control over audio and video recording.

Sr.No Method & description
1 setAudioSource()

This method specifies the source of audio to be recorded

2 setVideoSource()

This method specifies the source of video to be recorded

3 setOutputFormat()

This method specifies the audio format in which audio to be stored

4 setAudioEncoder()

This method specifies the audio encoder to be used

5 setOutputFile()

This method configures the path to the file into which the recorded audio is to be stored

6 stop()

This method stops the recording process.

7 release()

This method should be called when the recorder instance is needed.

Android-Animation

August 4,2016

Animation is the process of creating motion and shape change

Animation in android is possible from many ways. In this chapter we will discuss one easy and widely used way of making animation called tweened animation.

Tween Animation

Tween Animation takes some parameters such as start value , end value, size , time duration , rotation angle e.t.c and perform the required animation on that object. It can be applied to any type of object. So in order to use this , android has provided us a class called Animation.

In order to perform animation in android , we are going to call a static function loadAnimation() of the class AnimationUtils. We are going to receive the result in an instance of Animation Object. Its syntax is as follows −

Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), 
   R.anim.myanimation);

Note the second parameter. It is the name of the our animation xml file. You have to create a new folder called anim under res directory and make an xml file under anim folder.

This animation class has many useful functions which are listed below −

Sr.No Method & Description
1 start()

This method starts the animation.

2 setDuration(long duration)

This method sets the duration of an animation.

3 getDuration()

This method gets the duration which is set by above method

4 end()

This method ends the animation.

5 cancel()

This method cancels the animation.

In order to apply this animation to an object , we will just call the startAnimation() method of the object. Its syntax is −

ImageView image1 = (ImageView)findViewById(R.id.imageView1);
image.startAnimation(animation);

SQLite Spinner

August 3,2016

In this example, we are adding a label on button click and displaying all the added labels on the spinner. As you have seen in the previous example, SQLiteOpenHelper class need to be extended for performing operations on the sqlite.

We have overridden the onCreate() and onUpgrade() method of SQLiteOpenHelper class in the DatabaseHandler class that provides additional methods to insert and display the labels or data.

Android Sqlite Spinner Example

Let’s see the simple code to add and display the string content on spinner using sqlite database.

activity_main.xml

File: activity_main.xml
  1. <RelativeLayout xmlns:androclass=http://schemas.android.com/apk/res/android&#8221;
  2.     xmlns:tools=http://schemas.android.com/tools&#8221;
  3.     android:layout_width=“match_parent”
  4.     android:layout_height=“match_parent”
  5.     tools:context=“.MainActivity” >
  6.      <!– Label –>
  7.     <TextView
  8.         android:layout_width=“fill_parent”
  9.         android:layout_height=“wrap_content”
  10.         android:text=“Add New Label”
  11.         android:padding=“8dip” />
  12.     <!– Input Text –>
  13.     <EditText android:id=“@+id/input_label”
  14.         android:layout_width=“fill_parent”
  15.         android:layout_height=“wrap_content”
  16.         android:layout_marginLeft=“8dip”
  17.         android:layout_marginRight=“8dip”/>
  18.     <Spinner
  19.         android:id=“@+id/spinner”
  20.         android:layout_width=“fill_parent”
  21.         android:layout_height=“wrap_content”
  22.         android:layout_alignParentLeft=“true”
  23.         android:layout_below=“@+id/btn_add”
  24.         android:layout_marginTop=“23dp” />
  25.     <Button
  26.         android:id=“@+id/btn_add”
  27.         android:layout_width=“wrap_content”
  28.         android:layout_height=“wrap_content”
  29.         android:layout_below=“@+id/input_label”
  30.         android:layout_centerHorizontal=“true”
  31.         android:text=“Add Item” />
  32. </RelativeLayout>

Android SQLite Database

August 2,2016

SQLiteDatabase class

It contains methods to be performed on sqlite database such as create, update, delete, select etc.

Methods of SQLiteDatabase class

There are many methods in SQLiteDatabase class. Some of them are as follows:

Method Description
void execSQL(String sql) executes the sql query not select query.
long insert(String table, String nullColumnHack, ContentValues values) inserts a record on the database. The table specifies the table name, nullColumnHack doesn’t allow completely null values. If second argument is null, android will store null values if values are empty. The third argument specifies the values to be stored.
int update(String table, ContentValues values, String whereClause, String[] whereArgs) updates a row.
Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) returns a cursor over the resultset.

Android SQLite

August 1,2016

Today i come to know the sqlite  and database in android.

Android SQLite

SQLite is an open-source relational database i.e. used to perform database operations on android devices such as storing, manipulating or retrieving persistent data from the database.

It is embedded in android bydefault. So, there is no need to perform any database setup or administration task.

SQLiteOpenHelper class

The android.database.sqlite.SQLiteOpenHelper class is used for database creation and version management. For performing any database operation, you have to provide the implementation of onCreate() and onUpgrade() methods of SQLiteOpenHelper class.

Constructors of SQLiteOpenHelper class

There are two constructors of SQLiteOpenHelper class.

Constructor Description
SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) creates an object for creating, opening and managing the database.
SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler) creates an object for creating, opening and managing the database. It specifies the error handler.

Methods of SQLiteOpenHelper class

There are many methods in SQLiteOpenHelper class. Some of them are as follows:

Method Description
public abstract void onCreate(SQLiteDatabase db) called only once when database is created for the first time.
public abstract void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) called when database needs to be upgraded.
public synchronized void close () closes the database object.
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) called when database needs to be downgraded.