Thursday, 23 July 2015

Localization in Android app supporting all Indian Languages


Prerequisite : Needs Android Studio Setup.            

Step 1. Create new Project called Localization Demo
Step 2. Go to activity_main and add following code

<LinearLayout 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:orientation="vertical"
    tools:context=".MainActivity"
    android:gravity="center">

    <TextView  android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:textSize="26sp"
       android:text="Language"
       android:id="@+id/textView1" />

    <TextView
       android:layout_marginTop="10dp"
       android:text="@string/app_lang"
       android:textSize="40sp"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:id="@+id/textView2"/>
</LinearLayout>

Step 3. Right Click on values folder, Go to New-> Values resource file
    Enter filename as strings and choose Language option from Available qualifiers and then choose the language from right side. As I have create strings.xml for all Indian languages.

Step 4. Add following code in hindi(hi) string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_lang">हिन्दी</string>
</resources>
Step 5. Add following code in Assamese(as) string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_lang">অসমীয়া</string>
</resources>


Step 6. Add following code in Bihari(bh) string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_lang">बिहारी</string>
</resources>

Step 7. Add following code in English(en) string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_lang">English</string>
</resources>

Step 8. Add following code in Gujarati(gu) string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_lang">ગુજરાતી</string>
</resources>

Step 9. Add following code in Kannada(kn) string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_lang">ಕನ್ನಡ</string>
</resources>

Step 10. Add following code in Kashmiri(ks) string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_lang">कॉशुर</string>
</resources>

Step 11. Add following code in Malayalam(ml) string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_lang">മലയാളം</string>
</resources>

Step 12. Add following code in Marathi(mr) string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_lang">मराठी</string>
</resources>

Step 13. Add following code in Oriya(or) string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_lang">ଓଡ଼ିଆ</string>
</resources>

Step 14. Add following code in Sanskrit(sa) string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_lang">संस्कृत</string>
</resources>

Step 15. Add following code in Tamil(ta) string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_lang">தமிழ்</string>
</resources>

Step 16. Add following code in Telgu(te) string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_lang">తెలుగు</string>
</resources>

Step 17. Add following code in Urdu(ur) string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_lang">اُردُو</string>
</resources>

Step 18. After that add following code to your menu_main.xml. For providing language change access to user.

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">
    <item android:id="@+id/action_assamese" android:title="Assamese"
       android:orderInCategory="100" app:showAsAction="never" />
    <item android:id="@+id/action_hindi" android:title="Hindi"
       android:orderInCategory="100" app:showAsAction="never" />
    <item android:id="@+id/action_bihari" android:title="Bihari"
       android:orderInCategory="100" app:showAsAction="never" />
    <item android:id="@+id/action_english" android:title="English"
       android:orderInCategory="100" app:showAsAction="never" />
    <item android:id="@+id/action_gujarati" android:title="Gujarati"
       android:orderInCategory="100" app:showAsAction="never" />
    <item android:id="@+id/action_kannada" android:title="Kannada"
       android:orderInCategory="100" app:showAsAction="never" />
    <item android:id="@+id/action_kashmiri" android:title="Kashmiri"
       android:orderInCategory="100" app:showAsAction="never" />
    <item android:id="@+id/action_malayalam" android:title="Malayalam"
       android:orderInCategory="100" app:showAsAction="never" />
    <item android:id="@+id/action_marathi" android:title="Marathi"
       android:orderInCategory="100" app:showAsAction="never" />
    <item android:id="@+id/action_oriya" android:title="Oriya"
       android:orderInCategory="100" app:showAsAction="never" />
    <item android:id="@+id/action_sanskrit" android:title="Sanskrit"
       android:orderInCategory="100" app:showAsAction="never" />
    <item android:id="@+id/action_tamil" android:title="Tamil"
       android:orderInCategory="100" app:showAsAction="never" />
    <item android:id="@+id/action_telgu" android:title="Telgu"
       android:orderInCategory="100" app:showAsAction="never" />
    <item android:id="@+id/action_urdu" android:title="Urdu"
       android:orderInCategory="100" app:showAsAction="never" />
</menu>

Step 19. Add below code to your MainActivity

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
    
       int id = item.getItemId();
       switch (id){
           case R.id.action_assamese:
               setLocale("as");
               return true;
           case R.id.action_bihari:
               setLocale("bh");
               return true;
           case R.id.action_english:
               setLocale("en");
               return true;
           case R.id.action_gujarati:
               setLocale("gu");
               return true;
           case R.id.action_hindi:
               setLocale("hi");
               return true;
           case R.id.action_kannada:
               setLocale("kn");
               return true;
           case R.id.action_kashmiri:
               setLocale("ks");
               return true;
           case R.id.action_malayalam:
               setLocale("ml");
               return true;
           case R.id.action_marathi:
               setLocale("mr");
               return true;
           case R.id.action_oriya:
               setLocale("or");
               return true;
           case R.id.action_sanskrit:
               setLocale("sa");
               return true;
           case R.id.action_tamil:
               setLocale("ta");
               return true;
           case R.id.action_telgu:
               setLocale("te");
               return true;
           case R.id.action_urdu:
               setLocale("ur");
               return true;
       }
       return super.onOptionsItemSelected(item);
    }

public void setLocale(String lang) {
       Locale myLocale = new Locale(lang);
       Resources res = getResources();
       DisplayMetrics dm = res.getDisplayMetrics();
       Configuration conf = res.getConfiguration();
       conf.locale = myLocale;
       res.updateConfiguration(conf, dm);
       Intent refresh = new Intent(this, MainActivity.class);
       startActivity(refresh);
       finish();
    }

setLocale Method will set user selected language to your application

Now, Run your application. And enjoy all Indian language support to your application

Note: You can download sourcecode from gihub.

Wednesday, 22 July 2015

Send SMS from Android Application


Program to send SMS is very simple to develope. You hardly have to write two lines of code. For writing a code for sending SMS we need to understand SMSManager class

SMSManager

This class manages android SMS such as sending text, We need to create object by calling the static method.

android.telephony.SmsManager.getDefault();

This method will give you default instance of SmsManager .

Using this instance we need to call sendTextMessage(destinationAddress, scAddress, text, sentIntent, deliveryIntent);

scAddress - This is used to specify the SMS service center to use. If you enter null, the default service center for the device carrier will be used.
destinationAddress - is the target phone number you wish to text
text - message to be send

android.telephony.SmsManager smsManager = android.telephony.SmsManager.getDefault();
smsManager.sendTextMessage(destinationAddress, scAddress, text, sentIntent, deliveryIntent);


That's it, simple it is..

Permission

Another critical part is to update Androidmanifest.xml, by adding this code to it

 <uses-permission android:name="android.permission.SEND_SMS" />

This grants permission for Android application to send sms.

Code

EditText editText;
Button btnSend;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText=(EditText) findViewById(R.id.editText1);
btnSend=(Button) findViewById(R.id.button1);
btnSend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
android.telephony.SmsManager smsManager = android.telephony.SmsManager.getDefault();
smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);
}
});
}

Tuesday, 7 July 2015

Android Interview Question Part-3


1. What is the APK format?
The APK file is compressed AndroidManifest.xml file with extension .apk. It also includes the application code (.dex files), resource files, and other files which are compressed into a single .apk file.

2. What is a resource?
A user defined JSON, XML, bitmap, or other file, injected into the application build process, which can later be loaded from code.

3. What is an Intent?
A class (Intent) which describes what a caller desires to do. The caller will send this intent to Android’s intent resolver, which finds the most suitable activity for the intent. E.g. opening a PDF document is an intent, and the Adobe Reader apps will be the perfect activity for that intent (class).

4.What is a Sticky Intent?
sendStickyBroadcast() performs a sendBroadcast(Intent) known as sticky, i.e. the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter). In all other ways, this behaves the same as sendBroadcast(Intent). One example of a sticky broadcast sent via the operating system is ACTION_BATTERY_CHANGED. When you call registerReceiver() for that action — even with a null BroadcastReceiver — you get the Intent that was last broadcast for that action. Hence, you can use this to find the state of the battery without necessarily registering for all future state changes in the battery.

5. What are the life cycle methods of android activity?
There are 7 life-cycle methods of activity. They are as follows:
  1. onCreate()
  2. onStart()
  3. onResume()
  4. onPause()
  5. onStop()
  6. onRestart()
  7. onDestroy()

6. What is implicit intent in android?

Implicit intent is used to invoke the system components.

7. What is explicit intent in android?

Explicit intent is used to invoke the activity class.

Thursday, 2 July 2015

Android Interview Question Part-2


11. When does onResume() method called?

onResume() method is an activity lifecycle method. This is called when the activity come to foreground. You can override this method in your activity to execute code when activity is started, restarted or comes to foreground.

12. How to launch an activity in your application?

For launching an activity, we need to create an explicit intent that defines the activity that we wish to start. In the below code snippet, the first parameter to Intent constructor is the current activity context and the second parameter is your new activity class.startActivity() method can be called on Activity context.
Intent intent = new Intent(this,
SecondActivity.class);
startActivity(intent);
If you want to start an activity from fragment
Intent intent = new Intent(getActivity(),
SecondActivity.class);
getActivity().startActivity(intent);

13. How to define an Activity as launcher activity in application Manifest file?

All the activities used in the application should be defined in application manifest file. For launcher activity you need to define intent filter as shown in the below code snippets.
<activity android:name=".MyActivity"
              android:label="@string/app_name">
        <intent-filter>
            <action
android:name="android.intent.action.MAIN" />
            <category
android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

14. What is a ANR ?

ANR is short for Application Not Responding. Android systems shows this dialog, if application is performing too much of task on main thread and been unresponsive for a long period of time.

15. What are the measures to avoid application ANR?

ANR in application is annoying to user. It can be caused due to various reasons. Below are some of the tips to avoid ANR
  • Perform all you long running network or database operation in separate thread
  • If you have too much of background tasks, then take it off the UI thread. You may use IntentService
  • Server not responding for longer period can be guilt for ANR. To avoid always define HTTP time out for your all your webs service calls.
  • Be watchful of infinite loops during your complex calculations

16. What is the difference between a regular .png and a nine-patch image?

The nine patch images are extension with .9.png. Nine-patch image allows resizing that can be used as background or other image size requirements for the target device. The Nine-patch refers to the way you can resize the image: 4 corners that are unscaled, 4 edges that are scaled in 1 axis, and the middle one that can be scaled into both axes.

17. How to share text using android share Intent ?

Share intent is an easy and convenient way of sharing content of your application with other apps.
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This
is my text to send.");
sendIntent.setType("text/plain");
startActivity(sendIntent);

18. What is the use of WebView in android?

A WebView is an android UI component that displays webpages. It can either display a remote webpage or can also load static HTML data. This encompasses the functionality of a browser that can be integrated to application. WebView uses the WebKit rendering engine to display web pages and includes methods to navigate forward and backward through a history, zoom in and out, etc.

19. Define different kind of context in android

Context defines the current state of application or object. Context provides access to things such as creating new activity instance, access databases, start a service, etc. You can get the context by invoking getApplicationContext(), getContext(), getBaseContext() or this when in the activity class.
//Creating ui instance
ImageButton button = new
ImageButton(getContext());

//creating adapter
ListAdapter adapter = new
SimpleCursorAdapter(getApplicationContext(), ...);

//querying content provider
getApplicationContext().getContentResolver().query(uri,
...);

//start activity. Here this means activity
context
Intent intent = new
Intent(this, SecondActivity.class);

20. What are the different storage methods in android

Android offers several different options for data persistence.
  1. Shared Preferences – Store private primitive data in key-value pairs. This sometimes gets limited as it offers only key value pairs. You cannot save your own java types.
  2. Internal Storage – Store private data on the device memory
  3. External Storage – Store public data on the shared external storage
  4. SQLite Databases – Store structured data in a private database. You can define many number of tables and can store data like other RDBMS.