Saturday, January 24, 2015

Experienced Android Interview Questions - 4

Company - Tarang

1. How do you join 2 Notifications?
//Below are the steps to create notifications.
//create variables
NotificationManager nm;
Notification n;
//initialize all the variables.
//step1: create notification manager object
nm = (NotificationManager) getSystemService(
Context.NOTIFICATION_SERVICE);
//step2: prepare the ticker text and ticker icon
n = new Notification(R.drawable.ic_launcher,
"Urgent Msg", System.currentTimeMillis());
//step3: create intent to start activity
Intent in = new Intent(getApplicationContext(),
MyNotifcationActivity.class);
//spte4: prepare the pending intent for above intent
PendingIntent pi = PendingIntent.getActivity(
getApplicationContext(),
0,
in,
0);
//step5: set the latest event information & pass the pi
n.setLatestEventInfo(getApplicationContext(),
"Urgent Message",
"Please click here to read the message",
pi);

n.flags = n.flags | Notification.FLAG_AUTO_CANCEL;
//step6: use notification mgr to notify or to push
nm.notify(1, n); //1 is the id of this notification.
-------------------------------------------------------------
Now if you want to merge two notifications, when you are notifying
       next time, use same id of previous notification. "1"


2. How do you insert data into SQLite DB.
//create a table with some columns in SQLiteOpenHelper
db.execSQL("Create table emp(_id integer primary key," +
"ename text, esal integer);");

/*function to insert values into emp table.
  *this function assumes user will pass two values to insert
 *to insert into emp table */

public void insertEmp(String name, int sal){
//we will create content values to insert
ContentValues cv = new ContentValues();
cv.put("ename", name);
cv.put("esal", sal);
//now we have to insert
sdb.insert("emp", null, cv);
}

Company - Tavant

1. How do you register a Fragment?
To register a fragment with an xml file, go to xml file and use <fragment> tag with name as the complete package qualifier name of your fragment class. For eg:

<fragment android:id="@+id/myfrag"
   android:name="com.skillgun.fragments.MyFrag"
   android:layout_width="0dp"
   android:layout_height="match_parent"
   android:layout_weight="2"/>

Once you load this xml file using your activity, automatically Android will load an instance of your Fragment class (i.e object of MyFrag class)

2. In Manifest file what is config.uses and config.orientation/config.keyboard
Generally when ever there is a configuration change in the phone, like screen orientation changes [or] soft keyboard availability [or] language changes, in these scenarios android will automatically kill and restart your activity to take the new resources effective.

But you have the choice of requesting android to not restart your activity, and you can handle configuration changes on your own.
This can be done by using android:configChanges property in your activity tag, of your manifest.xml file.

<activity android:name=".MyActivity"
          android:configChanges="orientation|keyboardHidden"
          android:label="@string/app_name">

The above activity tag says to android that, don't kill and restart my activity in case of screen orientation or keyboard availability.
Instead android will call  onConfigurationChanged() of your activity.

<uses-configuration> tag indicates what all hardware and software features are required for your application.

3. In HTTP request what header will do?
HTTP Request header can have various things based on your requirement.

It can have
1. content-type.
   for eg content-type is json or xml
2. you can also give authorization token in header.
3. you can also set "accept-charset" for the header.

4. Implement Async Task functionality (touching UI from worker thread), by using Handlers.
// Here is an example of creating our own handlers to do inter thread communication. I am creating a service which extends an intentservice.
// Since we can't touch UI from intentservice, we are creating a handler
// to communicate with main thread to touch UI by using handlers.

public class MyService1 extends IntentService {

MyHandler mh; // variable for our handler

@Override
public void onCreate() {
// create Handler for with MainThread's looper
mh = new MyHandler(getMainLooper());
super.onCreate();
}
// implement Handler to communicate with Main thread.
class MyHandler extends Handler{
public MyHandler(Looper lp){
super(lp);
}
@Override
public void handleMessage(Message msg) {
// What ever logic you write here, will get executed
                        // in Main thread's context, since it is having main
                        // thread's looper
Toast.makeText(getApplicationContext(),
"intent service", 0).show();
super.handleMessage(msg);
}
}

public MyService1() {
super("My-Wthread");
}

@Override
protected void onHandleIntent(Intent intent) {
Message m = mh.obtainMessage();
m.arg1 = 1;
// send message to our handler, which will push to main thread.
mh.sendMessage(m);
}
}

5. What is URI?
URI : Uniform Resource Indicator. Used to access or send data in Android.

Just like how we access the data stored in the web servers by using URLs (Uniform Resource Locators), Similarly we send or receive data in Android by using URI's

Some of the examples for URI's:
for telephone numbers we use "tel:<number>"
for content stored in databases we use "content:// ...."
for emails we use "email: <email>"

This is similar to how we access gmail by using "http://gmail.com"

6. What is system.out.println? Why we use this in Java? (java)
This line System.out.println() is used to print the arguments passed to it on standard output.
System is the final class, out is the public static final variable of PrintStream class, and println() is the function of PrintStream class.

7. How do you iterate data from your cursor if your cursor have some data?
Cursor c = mdb.getAllEmp(); // lets say this will get all the rows of your employee table.

if(c!=null){ // first check if cursor is not null
while(c.moveToNext()){   // this line will move the cursor to next valid record, proceed until last record is reached.
                           // here read the cursor values.. and proceed
                           ...
                        }
                 }
                             

8. How do you load fragment into Activity?
1.Create a layout for your fragment
2.Implement a fragment by defining a class for your fragment code, by extending Fragment class.
3.Return your fragment layout from your fragment's life cycle funciton onCreateView()
4.Define an xml file for your activity, which has <fragment> tag, which will contain your fragment class

Now run your program, once android sees <fragment> tag in your activity's layout file, it will go and create object for your fragment and loads it into
your activity.


9. What is Handler.message and Handler.post?
These are the mechanisms to do inter thread communication.
For example we have thread-1 and thread-2, now thread-2 want to communicate with thread-1.
For this we have to create a handler for thread-1 using its looper. 
Once we create handler for thread-1, thread-2 can use that handler to send messages to thread-1.
Handler.Message is the class which we use to create messages to send to other threads.
Handler.post() is the method, which we use to post a Runnable Interface object to a thread's handler.
You can use Handler.sendMessage() to send a simple messages created by Handler.Message class.


Example of sending message to other threads:
// First create a handler implementation
class MyHandler extends Handler{
public MyHandler(Looper l){
super(l);
}
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), 
"thread created", 
0).show();
super.handleMessage(msg);
}
}

// create object for your handler , pass other thread's looper.
MyHandler mh = new MyHandler(getMainLooper());
// create a message
Message m = new Message();
m.arg1 = 1;
// pass that message to handler (mh) , which is connected to other thread.
mh.sendMessage(m);

10. How do you know whether your screen is in landscape/portrait mode to load fragments
// Solution : To know if you are in landscape or portrait mode

if(myCurrentActivity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) 
{
    // code to do for Portrait Mode
} else {
    // code to do for Landscape Mode         
}

11. What is the use of os.message?
This is the class used to create messages to pass between two threads.
Refer to above questions on how to do inter thread communication to understand Messages.

No comments:

Post a Comment