Technical Knowledge

technical knowledge is that type of blogger in which you can find all the soluctions of your problems which you cannot solve you can see the video given on this blog and solve your problem by yourself.

Like us on Facebook

Technical Knowledge

Sunday, March 29, 2015

options menu, context menu, and sub menu: android tutorial

Program description:

This program will show how to design, create, and handle menus in android.

There are 3 types menus:

1. Options menu - displayed when user clicks hard menu key on the keyboard
2. Sub menu - menu with in a menu
3. Context menu - press and hold on a view, to show context menu.
                                just like when you right click on some item in your desktop.

This will show how to create options menu, how to handle option menu items &

How to register context menu for a button, and how to handle context menu items.

Note: From android version 3.0 on wards there is no support for hard key menu, so using options menu is discouraged. In place of options menu we will be using action bars.


First Activity
package com.techpalle.b15_menus;

import android.os.Bundle;
import android.app.Activity;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button1);
registerForContextMenu(b1);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if(v.getId() == R.id.button1){

}
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.contextmenu, menu);
menu.setHeaderIcon(R.drawable.ic_launcher);
menu.setHeaderTitle("Contact Us!");
super.onCreateContextMenu(menu, v, menuInfo);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.item1:
Toast.makeText(getApplicationContext(),
"Contact by SMS", 0).show();
break;
case R.id.item2:
Toast.makeText(getApplicationContext(),
"Contact by Call", 0).show();
break;
case R.id.item3:
Toast.makeText(getApplicationContext(),
"Contact by Map location", 0).show();
break;
}
return super.onContextItemSelected(item);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.optionsmenu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.getItem(0).setTitle("My home");
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.item1:
Toast.makeText(getApplicationContext(), "Home", 0).show();
break;
case R.id.item2:
Toast.makeText(getApplicationContext(), "AboutUs", 0).show();
break;
case R.id.item3:
item.getSubMenu().setHeaderIcon(R.drawable.ic_launcher);
item.getSubMenu().setHeaderTitle("Techpalle Trainings");
Toast.makeText(getApplicationContext(), "Trainings", 0).show();
break;
case R.id.item4:
Toast.makeText(getApplicationContext(), item.getTitle(),
0).show();
break;
case R.id.item5:
item.setChecked(!item.isChecked());
Toast.makeText(getApplicationContext(), "Android", 0).show();
break;
case R.id.item6:
Toast.makeText(getApplicationContext(), "DotNet", 0).show();
break;
}
return super.onOptionsItemSelected(item);
}

}




xml layout file for First Activity 
File name: activity_main.xml
  xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >


options menu file in res -> menu folder
optionsmenu.xml (in res-menu folder)
  




android:checkable="true" android:checked="true"/>
android:checkable="true"/>










context menu file in res -> menu folder
contextmenu.xml (in res-menu folder)
  





Download complete code : Click to download

Similar programs:
android Dialogs tutorial

Tags: android, tutorial, examples, menus, options menu, sub menu, context menu

250 Android Interview Questions - part 2

I am giving set of 250 Android interview questions here, which I have answered in android interview questions and answers - skillgun

Since Java is also a part of android interview, I have included around 60 java interview questions here.

I am giving only questions here as space is a constraint for explaining every answer.
                                            
Android Interview Questions:

101.                        I want to store huge structured data in my app that is private to my application, now should I use preferences [or] files [or] sqlite [or] content provider?
102.                        My application has only a service, and my service performs heavy lift functionality to connect to internet and fetch data, now should I create a thread or not? If so why?
103.                        I want to write a game where snake is moving in all the directions of screen randomly, now  should I use existing android views or should use canvas? Which is better?
104.                        Can I have more than one thread in my service? How to achieve this?
105.                        When lcd goes off, what is the life cycle function gets called in activity?
106.                        When a new activity comes on top of your activity, what is the life cycle function that gets executed.
107.                        When a dialog is displayed on top of your activity, is your activity in foreground state or visible state?
108.                        When your activity is in stopped state, is it still in memory or not?
109.                        When your activity is destroyed, will it be in memory or moved out of it?
110.                        I started messaging app –> composer activity -> gallery  -> camera -> press home button. Now which state camera activity is in?
111.                        Continuation to above question, now If I launch gmail application will it create a new task or is it part of old messaging task?
112.                        Can I have more than one application in a given task?
113.                        Can I have more than one process in a given task?
114.                        Do all the activities and services of my application run in a single process?
115.                        Do all components of my application run in same thread?
116.                        How to pass data from activity to service?
117.                        How to access progress bar from a service?
118.                        What is the difference between intent and intent-filter?
119.                        What is the difference between content-provider and content-resolver?
120.                        What is the difference between cursor & contentvalues ?
121.                        What is Bundle? What does it contain in oncreate() of your activity?
122.                        When an activity is being started with an intent action “MY_ACTION”, how can I see that action in triggered component(activity)?
123.                        How to get contact number from contacts content provider?
124.                        How to take an image from gallery and if no images available in gallery I should be able to take picture from camera and return that picture to my activity?
125.                        What is the difference between linear layout and relative layout?
126.                        How many kinds of linear layouts are there?
127.                        What is “dp” [or] “dip” means ?
128.                        What is importance of gravity attribute in the views?
129.                        What is adapter? What is adapter design pattern?
130.                        What is adapterview? How many adapter views are available in android?
131.                        Can you tell me some list adapters?
132.                        Can I give cursor to an array adapter?
133.                        What is custom adapter, when should I use it. what are the mandatory functions I need to implement in custom adapter?
134.                        What is the class that I need to extend to create my own adapter?
135.                        What is the android compilation and execution process/ cycle?
136.                        What is adb? What is the command to install one application using adb command prompt?
137.                        What is the debugging procedures available in android?
138.                        How will you analyze a crash, how will fix using logcat?
139.                        What is a break point and how to watch variables while debugging?
140.                        What is ddms? What are the various components in ddms?
141.                        What is the difference between started service and binded service?
142.                        How to achieve bind service using IPC?
143.                        How will I know if a client is connected to a service or not?
144.                        I want to access a functionality from one application to other application, then should I use content provider or startservice or bind service?
145.                        I want to access data of another application in my application, now do I need to implement content providers in my application or other application has to implement it?
146.                        What is the difference between local variables, instance variables, and class variables?
147.                        What is anonymous class? Where to use it?
148.                        What is singleton class, where to use it? show with one example how to use it?
149.                        If I want to listen to my phone locations, what all the things I need to use? Is it better to use network providers or gps providers?
150.                        My phone don’t have network signal and satellite signal, now is there any way to fetch my last location where signal was available?
151.                        I have some data available in docs.google server, and I want to display it in tabular fashion, tell me the sequence of steps to achieve this?
152.                        If I want to start some heavy weight functionalities that takes lot of battery power like starting animation or starting camera, should I do it in oncreate() or onstart() or onresume() of my activity? And where should I disable it?
153.                        Why you should not do heavy functionality in onresume and onpause()  of your activity?
154.                        What things I can do in onrestart() of my activity?
155.                        What is the life cycle of a service?
156.                        What is the life cycle of a broadcast receiver?
157.                        What is the life cycle of a content provider?
158.                        What is the life cycle of a thread?
159.                        What is the life cycle of your application process?
160.                        How to kill one activity?
161.                        What is log.d ? where to use log functions?
162.                        Draw the life cycle of an activity in case of configuration change?
163.                        What is the difference between viewgroup and layout?
164.                        Draw the key event flow in android?
165.                        When you fire an intent to start with ACTION_CALL , what is the permission required?
166.                        What are the permissions required to obtain phone locations?
167.                        How many levels of security available in android?
168.                        How to achive security to your service programmatically in such a way that your service should not get triggered from outside applications?
169.                        What are the sequence of tests done to map intent with an intent-filter?
170.                        Describe various folders in android project in eclipse?
171.                        What is raw folder in eclipse project?
172.                        Under what thread broad cast receiver will run?
173.                        If I want to notify something to the user from broadcast receiver, should I use dialogs or notifications? Why?
174.                        Can you create a receiver without registering it in manifest file?
175.                        If I want to broadcast BATTERY_LOW action, should I use sendbroadcast() or sendstickybroadcast? Why?
176.                        If I want to set an alarm to trigger after two days, how should I implement it? assume that I may switch off the phone in between.
177.                        I want to trigger my broadcast receiver as long as my activity is in memory, else it should not get triggered, how should I achieve this?
178.                        What is sleep mode? What will happened to CPU once screen light goes off?
179.                        How many kinds of wake locks are available, which one to use when?
180.                        If I am using full wake lock and user presses screen lights off, what will happen?
181.                        When phone is in sleep mode, what are the two components that will keep running even though phone is in sleep mode?
182.                        Every day night at 12 o clock I need to post some images to facebook, in that case I will set repeating alarm for every day night 12 am. But to upload images I want to start service, how should I do this ?
183.                        When you start an activity from a notification, will it start as new task or old task?
184.                        Why android follows single threaded ui mode? How other threads can manipulate ui views?
185.                        What is the purpose of SQLiteOpenHelper?
186.                        What is the procedure to upgrade database after first release?
187.                        Show with one example where memory leak possibility in Android?
188.                        If I want to write one application for both phones and tablets, what should I use in my UI?
189.                        I have a thousands of items in my array, and I want to display it in listview, what is the most optimized way to achieve this?
190.                        What is r.java file? What does it contain?
191.                        Write one application which will get triggered immediately after booting.
192.                        What does .apk  file contains?
193.                        How will pass information from one activity to other activity, let’s say pass userid, city, and password to next activity and display it.
194.                        Write code for an xml file having a relative layout with employee registration form.
195.                        Get a table information from the database and show it in table UI format.
196.                        I have thousands of columns and thousands of rows to display it in UI tabular format, how should I show it this dynamically growing UI. Should I load all in single shot or any optimization can be done?
197.                        When to use String, StringBuffer, & StringBuilder?
198.                        What is String constant pool? What is the difference between below two statements? 
                                                               i.      Which is preferred way to use?
                                                             ii.      String str1 = “hi”;
                                                            iii.      String str2 = new String(“hi”);
199.                        If I want to share a String between two threads, and none of threads are modifying my String which class I have to use?
200.                        If I want to use my String within only one thread which is modifying my String, then which class I have to use? Similarly if I want to my string to be changed by more than one thread then which class I have to use?
201.                        How does String class look like? What is final class meant for? How will you implement your own String class?
202.                        What is immutable object? How is it different from immutable class?
203.                        Depict one example for immutable class in java framework?
204.                        How will you write a class in such a way that it should generate immutable objects?
205.                        Does String class uses character array internally in its implementation?
206.                        What is the difference between char & Character classes? Which one is value type and which one is ref type?
207.                        What is the meaning of pass by reference? If I have an integer array and if I pass that array name to a function, is it pass by value or pass by reference?
208.                        I want to use array in my program which has to grow dynamically, in that case should I use Array [or] ArrayList [or] Vector? What is the difference between arraylist and vector? Which one of them is not part of collections framework of JAVA?
209.                        I want to use dynamically growing array shared between two threads, should I use arraylist or vector?
210.                        I want to store values of my employees in a data structure using java collections framework in such a way that I should be able to read, write, modify & delete them very fastly. Which datastructure should I use ? arraylist [or] linkedlist [or] hashsets [or] hashmap ?
211.                        Write a program in such a way that Thread1 will print from 1-1000 & Thread2 will print from 1000-1. Thread1 should sleep for 1 second at every 100th location. Thread2 should interrupt thread1 once thread2 reaches 500.
212.                        How will you stop a thread, which is currently running?
213.                        If Thread1 interrputs Thread2, how Thread2 should handle it? (Generally how threads should handle interruptions?) how will thread2 know that other threads are interrupting it?
214.                        What is interrupted exception? Which functions will throw this exception? How to handle it?
215.                        Assume that two threads t1, & t2 are running simultaneously in single core CPU. How does t2 will request OS that it wants to wait till t1 is finished?
216.                        I want to implement threads in my program, should I extend Thread class or implement Runnable interface? Which one is better, justify your answer in terms of design.
217.                        What will happen if you return from run() function of your thread?
218.                        What is the difference between checked  & unchecked exceptions? Which one programmer should handle?
219.                        arrayIndexOutOfBounds, NullPointerException, FileNotFoundException, ArithmeticException, InterruptedException, IOError, IOException. In this list which exceptions programmer has to handler compulsorily? Categorize above exception list into ERROR/ RUNTIME EXCEPTION/ REST categories.
220.                        Assume that I am writing a function which likely to throw checked exception, in that case if I don’t handle it will compiler throw any error?
221.                        How one should handle checked exceptions? Mention 2 ways to handle it.
222.                        I am writing a function where it is likely that checked exception may come, I want to handle it in my function and I want to pass that exception to my parent caller also. How do I achieve it?
223.                        What is difference between throw, throws?
224.                        Can I write a try block without catch statement?
225.                        What is difference between final, finally, & finalize.
226.                        Will java ensure that finalize will be executed all the time immediately after object is destroyed? How to mandate it?
227.                        What is 9 patch image, how is it different from .png images? Why we have to use this in android? How will it help in the scalability of an image for various screens?
228.                        What is the difference between synchronized method and synchronized block? If I have a huge function where only two lines of code is modifying a shared object then should I use synchronized block or method?
229.                        Implement insertion sort, binary search, and heap sort.
230.                        How many ways a server can communicate (Send data) to a mobile application? Which is fastest way json or xml?
231.                        What is JSONArray & JSONObject. Show this with one example by requesting one URL using HTTP, which gives JSON object.
232.                        Name some sites which extensively use JSON in communicating their data with clients.
233.                        What is the permission you need to take for fetching GPS locations, & reading contacts. Where will you have to write permissions in manifest file?
234.                        How will you display data base information in a table kind of architecture in android? Which view will you use?
235.                        How many kinds of adapter-views, and adapters available in android?
236.                        What is notifydatasetchanged() function meant for?
237.                        Take data base cursor of employee (eno, ename, salary) into a cursor, fill into a list view where each item should have a check box also, how will you implement it in android?
238.                        What is the difference between constructor and static block. Can I initialize static variables in constructor?
239.                        I want to use a private variable of Class-A in classB directly without using any function. How to achieve this?
240.                        I want to create a class in such a way that nobody should be able to create object for that class except me. How to do it?
241.                        Can I access instance variables in a static function? Can I access static function /variable from an instance method?
242.                        Why is multiple inheritance of classes not allowed in java? If I want to get functions of Class-A & Class-B into class-C. how do I design this program?
243.                        Does java allow multiple inheritance of interfaces? Can one interface extend other interface ? when should I extend interface from other interface?
244.                        What is the difference between over loading and over riding?
245.                        Can I over ride base class constructor in derived class?
246.                        Can I over load a constructor?
247.                        How does default constructor look like? What super() call does in a constructor?
248.                        Why does base class constructor gets executed before executing derived class constructor? Justify this with appropriate example?
249.                        How will you achieve dynamic polymorphism using over riding? Justify usage by taking some example (note: use client-server example)
250.                        Why overloading is static polymorphism, justify your answer?
251.                        What is the difference between static/compile time linking & dynamic/run time linking? Are static functions dynamically linked?
252.                        Show one Is-A relation with one example.
253.                        Show one Has-A relation with one example.
 
 
Happy job hunting
      Best wishes
          Team,
Palle Technologies
enquiry@techpalle.com
Phone : 080 - 4164-5630The training expert in Bangalore.

Android Interview Questions - part 3

What is the difference between DVM and JVM? Why Android opted for DVM?
Android team preferred DVM over JVM because of below given reasons.
1. Though JVM is free it was under GPU license, which is not good for Android as most of the Android is under Apache license.
2. JVM was designed by keep desktops in mind. So it is too heavy for embedded devices.
3. DVM takes less memory, runs & loads faster compared to JVM.
4. Since mobile devices have lot of limitations like low CPU speed and less Memory, it is always better not to use heavy components like JVM.

Which layer does Dalvik Virtual Machine sit?
Every android application runs in DVM. To run an application it requires memory, process, threads and other resources. But all these resources are under control of kernel. So DVM has to interact with driver layer for memory and thread management, it sits just above driver layer (that is.. it sits in library layer)

What is the importance of version code and version name attributes in manifest file?
Version no and name will be useful when you upload some application to play store and wanted to update it. When you are upgrading your application then you can increment the version number so that users of your application will get notification on their phones about the latest updates available.

Give two examples for configuration changes in Android?
configuration changes include: rotating the phone, having virtual keypad on, and changing language settings in settings.

What is the difference between implicit intent and explicit intent, give one example?
Implicit intent - Intent with out target component name; Explicit intent - Intent with target component name.

How to make a phone call from an android application?
Intent in = new Intent();  
in.setAction(Intent.ACTION_CALL);
in.setData(Uri.parse("tel:12345"));
startActivity(in);

What is the difference between intent, sticky intent, and pending intent?
intent - is a message passing mechanism between components of android, except for Content Provider. You can use intent to start any component.
Sticky Intent - Sticks with android, for future broad cast listeners. For example if BATTERY_LOW event occurs then that intent will be stick with android so that if any future user requested for BATTER_LOW, it will be fired;
Pending Intent - If you want some one to perform any Intent operation at future point of time on behalf of you, then we will use Pending Intent. Eg: Booking a ticket at late night when your application is not running. In this scenario we will create a pending intent to start a service which can book tickets at late night and hand it over to Alarm Manager to fire it at that time.
What type of kernel is used in Android?
Linux modified kernel (Monolithic) is used in Android.

What is r.java in android? What does it contain?
all resources located in res folder are mostly .xml files, which will not be understood by java compiler. So aapt (android application packaging) tool will convert all those xml files and other resources into a java file, which has identification numbers(pointers) to all those resources. if we want to access any resource from the code, then we can access through this R.java file. full form is Resource.java file.

What is APK in android, and What does .apk  file contains?
APK - Application Package file. It is a file format used to distribute and install android applications.

.apk will contain single .dex file, zipped resources, other non java library files (c/c++). .dex file will internally contains converted .class files. other wise .apk will not contains .class files.


Android Interview Questions - part 4

What is android raw folder in eclipse project?
This is just like assets folder, but only difference is this folder has to be accessed via R.java file. you can store any assets like MP3 or other files.

What is the maximum memory limit given for each process or application in android?
16 MB is the maximum memory limit given to any given android application. Some second generation phones will return 24 MB of memory for each process or even more.

How to send an SMS in android, through code ?
Eg: If I want to send a message to destination number "9741200300", then what is the correct code to do it?
SmsManager s = SmsManager.getDefault();
       s.sendTextMessage("9741200300", null,
                       "Hi how are you?", null, null);

Note: first parameter is destination number, second parameter is source number which you can omit, third parameter is text to be sent, fourth parameter is sent intent, fifth parameter delivery intent.

Sent intent: You can give a pending intent that should be broad casted once your message reaches your service providers SMS center.
Delivery intent: you can give a pending intent that should be broad casted once your message is delivered to the destination phone.

What is rooting?
It is the process of allowing users of smartphones, and other android enabled devices to get the privileged permissions (root access).
rooting allows to run any appliction that requires admin level permissions in the android system And can perform any operation which is not allowed by normal android user.
rooting is also done to overcome the limitations set by carriers and OEM (original equipment manufacturers) on a phone. Rooted phone can be used any where with any carrier network.

What is the difference between permission and uses-permission in android?

i. permission tag is used to enforce a user defined permission on a component of your application.
ii. uses-permission tag is used to take a permission from the user for your application.
iii. permission tag is used when you want other applications to seek permission from the user to use some of your applications components.

How to send an email in android through code? What is the correct intent to send an email?
       Intent in = new Intent(Intent.ACTION_SEND);  
       in.setType("message/rfc822"); //this is MIME type of email
       in.putExtra(Intent.EXTRA_EMAIL, new String[]{"user@gmail.com",
                       "more@gmail.com"}); // to address field
       in.putExtra(Intent.EXTRA_SUBJECT, "Hey imp!"); //subject of your mail
       in.putExtra(Intent.EXTRA_TEXT, "WHAT ARE YOU DOING?"); //body of your email
       
       startActivity(Intent.createChooser(in, "Select one option"));


What is the difference between this context and getapplicationcontext ?
There are two types of contexts available in android to create any component.
1. this context (or) this pointer
2. application context

When programmer wants to create any component or control, then you have to use one of the contexts.
eg: TextView t = new TextView(this);
Here we are using this pointer (context).
eg: static TextView st = new TextView(getApplicationContext());
Here we are using application context, because it is a static variable whose life time will be through out application life time.
If you use this pointer here, then it will leak memory (memory wastage) of your activity.

When to use this & getapplicationcontext:
1.If the control or variable you are creating should belong to application level then use applicationContext.
2.If the control or variable you are creating should belong to Activity level then use this pointer or this context.

Note: Generally people will think that java will not have memory leaks. But if you don't use contexts properly, then it might lead to some dangerous memory leaks in your android application.
Tip : Don't ever link between this pointer and static variables. If you follow this simple tip, you can almost reduce most of your memory leaks in your program.

what is the permission required to make a call in android, by using  ACTION_CALL ?
To make calls, we should have below permission tag in manifest file after tag.
.

how to create customized textview in android?

TextView is a predefined UI control given by android. If you don't like or wanted to enhance its properties, then you can create your own class by extending TextView class and implementing your own functionalities.


Newer Posts Older Posts Home