Skip to main content

Interview Questions




Broadcast receivers - Interview questions:
1) what is broadcast receiver?
ans : It is a component of android, which is used to receive/ listen important system events.
eg: BATTERY LOW, POWER CONNECTED, ....
2) How do you start a receiver?
ans : By using Intent, and sendBroadcast() method
3) How do you kill a receiver?
ans : abortBroadcast() method.
4) types of receivers?
ans : static receivers, dynamic receivers, ordered receivers, sticky receivers.
6) What are the life cycle methods of broacast receiver?
ans : onreceive()
Database related interview questions:
1. What is database?
ans : It is a logical container of data/ information.
2. Which database do we use in android?
ans : SQLite - RDBMS
3. Where is database stored?
ans : Database is stored within the application, in Internal memory.
4. How to store images/ audios/ videos in a table using SQLite?
ans : by using BLOB datatype = binary large object .
First we have to convert images to 0101, then store in tablee using BLOB data type. Later while reading the image we will read 0101 and recreate the image by using BitMapFactory class.
5. what is primary key?
ans : unique + not null.
Primary key is used to uniquely identify each row.
6. what is foreign key?
ans : used to maintain relationship between tables. If a primary key of one tables comes to other table then it becomes foreign key.
Every RDBMS should support foreign key. But by default SQLite doesn’t have support for foreign key. To enable foreign key support below command should be issued.
db.execSQL("pragma FOREIGN KEY;");
7. how to upgrade database? (imp)
ans :
a. change application version code and version name in build.gradle.
b. change database version in helper parameter.
c. go to inner helper class, go to onupgrade() method, use if-else condition and we can add/ remove/ alter tables based on the version.
8. Difference between delete and drop? (imp)
ans : delete is DML statement. drop is DDL command.
drop = delete the rows + delete the table.
delete = will delete only rows.
9. Difference between update and upgrade?
ans : update is DML statement. but upgrade is related to DDL.
update = will update the rows.
upgrade = create table/ drop table/ alter table in the future application releases.
note : upgrade terminology is used for databases.
Activity & Fragment Interview questions:
1. how do you start an activity?
ans:Using intent class& startActivity() method
2. how do you start a fragment?
ans:by using FragmentManager, fragmentTransaction & add() method.
[or]
using <Fragment ..tag> in xml.
Note : first approach is dynamic fragment, 2nd is static fragment.
3. how do you kill an activity?
ans: finish() method
4. how do you kill a fragment?
ans:
fragmenttransaction.popBackstack() method [or]
fragmenttransaction.replace() [or]
fragmenttransaction.remove()
5. how do you pass data to an activity?
ans: By using Intent & putExtra() method.
6. how do you pass data to fragment?
ans: By using Bundle, setArguments() method.
6.1: What is fragment?
def: Fragment is a "re-usable UI component". Fragments are introduced in android 3.0. Fragments are used to design UI for mobiles & tablets.
7. User clicks back button, which life cycle methods will be called for activity?
ans : onpause, onstop, ondestroy.
8. User clicks home button, which life cycle methods will be called for activity?
ans : onpause, onstop
9. User is looking at screen & suddenly call comes which life cycle methods will be called for an activity?
ans : onpause, onstop
10. User rotates the phone, life cycle methods of an activity? [IMP]
ans : onpause, onsaveinstancestate, onstop, ondestroy,
oncreate, onstart, onrestoreinstancestate, onresume.
same for virtual kyeboard up/down & language changes also. same for low memory also.
11. write one line about each life cycle method.
oncreate()
a. first life cycle method
b. we will load screen design here
c. we will initialize all views here
onapuse()
a. when user is moving away from the screen this method will be called.
b. eg: popup displayed, new screen comes, etc..
c. important data has to be saved here. eg: saving database, saving files etc..
onsaveinstancestate()
a. this is called in configuration changes
b. eg: phone rotation, language changes, etc.
c. programmer has to save activity states here and restore in onRestoreinstancestate() method.
12) What is the use of frgment?
ans: For designing applications for mobile phones & tablets, we use fragments.
Material Design Api classes & definitions:
CoOrdinatorLayout :
a. It is inherited from FrameLayout
b. It is used to place elements on one-on-top of other, with shadow/3d effect.
c. If coordinator layout is removed, then 3d layering will not happen properly.
AppBarLayout:
a. It is used to club ActionBar+Tabs.
b. It is used to have parallox effect on actionbar. Parallox effect means - when user scrolls up / down, then actionbar will be moved out of screen.
ToolBar :
a. it is introduced in android 5.0
b. it is actionbar with shadow effect.
c. toolbar can be placed anywhere on the screen.in olden days, action bar used to stick at top.
TabLayout :
a. it is used mostly with viewpager.
b. it inherits from horizontal scrollview.
c. mostly it is attached to actionbar/toolbar.
FloatActionButton:
a. it appears at right corner of the screen.
b. Most important item should be placed as FAB.
eg: gmail app places "compose mail" as FAB.
c. this is highest priority icon.
NagivationView :
a. It is used to attach sliding menu with actionbar.
b. it will have header and menu body portions.
SnackBar :
a. it is advanced version of Toast.
b. it comes with colors & buttons.
c. it can be swipe deleted. [not possible with toast
RecyclerView :
a. Advanced version of listview.
b. it is faster & memory efficient compared to list view.
c. It comes with viewholder design pattern.
d. can be used as listview/ gridview/ staggered grid
CardView :
a. it inherits from framelayout.
b. it is is used to design round cornered - cards, with 3d shadow effect.
c. mostly used along with recyclerview - to show good looking rows.
Network related questions:
1. what is URL api?
a) it is used to represent website url.
2. what is HttpUrlConnection api?
a) it is used to establish connection between android application & server.
3. what is InputStream api?
a) this API is used for GET request. if we want to read some data from server, we will use this API. this is where the actual data will come from server.
Note : this may take some time, depending on internet connection.
4. what is InputStreamReader API?
a) it is used to convert/read the raw data [bits] coming in the input stream.
note : this api converts bits to ascii chars.
note : it is not efficient as it reads each character one by one.
5. what is BufferedReader API?
a) this api provides an efficient way to read data coming from server in big chunks, in line by line fashion.
Note : InputStreamReader vs BufferedReader is interview question.
Terminology used in websites:
Server/Webserver : it is combination of hardware & software where websites [website code] will run.
eg : apache webserver, tomcat webserver - for J2EE websites.
IIS webserver - for .NET websites.
webconfig : it is a small xml file in the server, which is similar to our android manifest xml file. this xml file contains, which URL is mapped to which Servlet this xml file also contains, which URL is mapped to which webservice.
Servlet : full form is serving the request.
Servlet is a small java file, which sits in server.
Servlet class will generally extend a predefined class HTTPServlet.
Servlet will handle all incoming requests from BROWSER.
Servlet is the first entry point in the server, which handles incoming request.
JSP : Java server pages. It is a small java file which sits in server. Main responsibility of JSP class is to prepare HTML content.
MVC : Model View Controller, is a design pattern used while designing web sites. Controller -is- servlet. View -is- JSP/ JSF. Model -is- Database connection logic.
WebServices: It is a small java file which sits in server.
Webservices will handle all incoming requests from non-browser applications.
Eg: if an android application sends a request to server, it most likely hits a web service.
Note : A website can have n-num of servlets/ webservices.
Note : Each servlet/ webservice will have one URL.
Types of webservices: RESTful & SOAP
RESTful Webservices: Representational State Transfer web services. Faster than SOAP services. Most of the RESTful services uses JSON format to transfer the data.
SOAP: Simple object access protocol. Slower compared to REST. Mostly SOAP services uses XML format to transfer the data.
HTTP : is a common language/ protocol used over internet for communicating between client & server systems.
HTTPRequest : it is a class representing request going from client to server.
HTTPResponse : it is a class representing response coming from server to client.
interview questions on services
1. what is service?
ans : component android used to do background task.
eg: connecting to internet.
2. types of services?
ans : Service & IntentService
3. service life cycle methods?
ans : oncreate, onstartcommand, ondestroy, onbind.
4. what is intent service?
ans : Service with 1 background thread.
lifecycle methods - constructor, onhandleintent
5. how to kill a service?
ans : stopservice(intent);
6. what is a thread?
ans : thred is a light weight process [or]
thread is an independent path of execution.
7. thread vs service?
ans : thread is os component, service is android component
interview questions on services - part 2
1. what is ANR?
ans : Application Not Responding is a famous error
in android.
2. why ANR error will occur?
ans : if key events are not delivered in 5 seconds time limit, then O.S will show this error popup to user.
3. What is the root cause for ANR errors?
ans : if service is not having its own thread, then service will use main thread for doing background task. when main thread is busy in the service, it can't handle key events. That leads to ANR.
4. what precautions to take to avoid ANR errors?
ans : when we create a service, create a thread also in the service.
Note : 1 thread handling too many taks is not good design.
Activities - will always use - MainThread.
Services - should always use - separate thread.
5. Some other scenarios where ANR may occur?
ans : opening, inserting, reading database in activity is danger. It might lead to ANR.
Activities - will use - main thread.
database - also using - main thread.
6. what is the time limit of ANR?
ans : 5 seconds. [set by google]
but phone manifacturer can reduce it for more efficiency. but should not increase it.
Shared preferences
1) What is preferences/ sharedPreferences?
ans : It is a small xml file which is used to store small amount of data permenantly.
eg: Storing user registration details/ credentials.
Note : we can only store primitive data types.
2) Which API we have to use to create a preference file?
ans : getSharedPreferences()
3) What is the 2nd parameter while creating
new preference file?
ans : 1st - file name, 2nd - PRIVATE MODE [0]
4) Which API we have to use to open preference file?
ans : getSharedPreferences()
5) Can I store array of strings in a preference file? how?
ans : putStringSet() - convert array to set and store.
6) How do you save a preference file?
ans : apply() [or] commit()
7) What is the difference between commit() & apply().
ans : commit() is slow, because it runs on main thread. apply() is fast, as it runs on different thread.
8) Is preference files secured?
ans : yes, but we have to use 2nd parameter 0 - PRIVATE MODE
9) How do you store multiple user credentials using preferences?
ans : op1 : for each user create a seperate pref file.
op2 : use 1 pref file but use different keys/tags for each user -
et.putString("user1",...);
et.putString("user2",...);
10)List all the methods of SharedPreferences class?
ans : getInt, getstring, getboolean, getfloat, getlong, getStringset
11)List all the methods of Editor class?
ans : putint, putstring, putboolean, putfloat, putlong, putstringset, apply, commit
12)How to create a preference file without name?
ans : SharedPreferences sp = getSharedPreferences("abc",0);
SharedPreferences sp = getPreferences(0);
13)what is the extension of preference file?
ans : xml
14)Can other applications access our preference file?
ans : generally no.
a. if other app has root permission
b. if second parameter is 1/2 [world readable/writab]
15)Can other activity of same application access pref file?
ans : yes
Interview questions on starting screens:
1. How do you start other activity/ screen?
ans : Intent class, startActivity() method.
2. How do you pass data from one screen to other screen?
ans : putExtra() method.
3. What is Bundle?
ans : Bundle is a container which carries data.
4. How do you kill a screen?
ans : finish() method.
Interview questions on passing data:
1. How do we pass data from one screen to other screen?
a) using Intent class, & putExtra() method.
2. Is there any other way to pass data to other screen?
a) yes, Serialization. [For passing objects]
note : Serialization also uses intent & putextra.
3. What is Serialization?
a) The process of converting "java object -to- bits & bytes".
4. what is De-Serialization?
a) The process of converting "bits & bytes -to- java object".
5. what is Serializable?
a) It is a marker interface [empty interface] in JDK s/w.
6. What is difference between Serializable vs Serialization?
a) Serializable is predefined interface [empty] of java. Serialization is a process of converting "java obj to bits". Serialization is done by JVM.
7) What is Parcellable?
a) It is predefined interface of Android.
8) What is parcelling? [or] what is the use of Parcellable?
a) Serialization is a java technique, which takes more memory and it is slower. Parcellable is an android technique, to pass objects faster and with less memory wastage.
Company interview questions - part 1
1. DIF between ART & DVM
ans : ART is replacement for DVM, in android 5.0
ART is 4times faster than DVM.
ART uses Ahead of Time compiler, DVM uses JIT compiler
2. what is dx file, how it is generated?
ans : dx = dalvik executeable file.
generated by build.gradle.
apk = android application package file.
generated by apkgen tool.
3. what is intent-filter?
4. what is broadcast receiver?
ans : it is a component of android which is used to listen or receive important system events.
ways : static - through xml
dynamic - through java code
5. where will you catch announcements / system events.
ans : using broadcast receiver.
6. what is content provider?
ans : it is used to share data from one application to other application.
eg : contact application is sharing numbers to whatsp
7. is there any other way to share data between 2 apps.
ans : using server. [or] cloud.
8. service life cycle methods?
ans : oncreate/ onstartcommand/ ondestroy.
9. types of services?
ans : service & IntentService.
10. when to service & when to use intentservice?
ans : Service does not come with default thread. Service depends on Main thread. Service has 4 life cycle methods. Using only service will lead to ANR error. Service need to be stopped explicitly either by stopserver [or] stopselfresult() methods.
IntentService class inherits from Service class. IntentService class comes with one thread. Using IntentService solves ANR problem. IntentService will kill itself when there are no more requests to start the service.
Some java related questions asked for android engineers:
1. dif between abs class & interface.
ans : abstract class can have abstract methods & concrete methods. abstract class is partial abstraction. Abstract class should be extended. interface can have only method declarations. interface is used to achieve pure abstraction. interface should be implemented.
2. dif bw hashmap & hashtable?
ans : HashMap part of collection framework library.jdk1.2
HashTable is legacy class. JDK 1.0
HashMap allows 1 null key, but HashTable will not.
HashMap is not synchronized, HashTable is synchronizd
Some more android questions
1. what is intent? types of intent?
ans : Intent is predefined class which is used to start other activities.
types : implicit, explicit, pending, sticky.
2. how will you start activity if you are expecting data back?
ans : startactivityforresult(in, requestcode).
3. what is child activity?
ans : Each screen in android is called as an activity.
4. can we use intent to start content provider?
ans : using intent you can start activity/service/receiver. we can't start content providers using intent. We use ContentResolver to start content provider.
5. does java support multiple inheritance?
ans : no for class, yes for interfaces. because it leads to function ambiguity.
6. how many ways we can store data in android. What all the different data storage options available in android?
ans : preferences[offline], sqlite db [offline], server[online], cloud[online], sd card[offline], internal memory[offline].
7. what manifest file contains?
ans : <manifest>
<uses-permission>
<application>
<activity>
<intent-filter>
8. types of access modfiers?
ans : private, default, protected, public.
9. can we access protected variables in child class?
ans : yes.
10. string vs stringbuilder vs stringbuffer
ans : Strings are immutable, stored in s.c.pool
stringbuilder is mutable, stored in heap, not sync
stringbuffer is mutable, stoerd in heap, synchronized
Interview questions part 2:
1. What is activity & write activity life cycle methods?
ans : Each screen in android is an Activity.
2. what is fragment & write fragment life cycle methods?
ans : fragment is a modular & reusable UI component.
[or]
fragment is used to design screens/applications for
mobles & tablets.
3. write string polyndrome logic?
ans :
4. User is going back from second activity to main activity, draw life cycle methods?
ans : onrestart, onstart, onresume
5. what is recyclerview?
ans : RecyclerView is introduced in MaterialDesign [5.0]
RecyclerView is faster than ListView, because of
ViewHolder design pattern.
6. how to pass data from one activity to other?
ans : intent, putextra.
7. what is intent filter?
ans : <intent-filter> tag will be in manifest file.
use case not yet covered. will be covered later.
8. what is broadcast receiver? can we create custom
broadcast receiver?
ans : it is component of android. it is used to receive important system events.
eg : I want to listen charger plugged.
eg : I want to listne when battery low.
9. what is asynctask? and draw life cycle methods of async task?
ans : It is used to create threads in android application.
onpreexecute, doinbackground, onprogressupdate, onpostexecute.
10.What are the components of android?
ans : activity, service, Broadcast Receiver, ContentProvider.
11.what is database.
ans : Database is a container of data in table format.
12.what is service? how many types of services are there?
ans : Service is a component of android, Which is used to do background task.
types : Service and IntentService.
Interview questions part-3:
1. What is activity & Intent?
ans : Each screen in android is an Activity.
Intent is a predefined class of android, which is used to start other activities & pass data.
2. Difference between activity & Intent?
ans : Activity is a component of android, it has life cycle methods. Intent is a predefined class to start activities.
3. Explain different types of intents?
ans : 4.
Implicit Intent, Explicit Intent, Pending Intent,
Sticky Intent.
4. What is the use of ViewGroup?
ans : ViewGroup is a predefined class extending from View class
It is used to design screens.
Eg of viewgroups - LinearLayout, FrameLayout, RelativLayout, AbsoluteLayout is deprecated.
5. What are different types of notifications?
ans : will be covered later
6. What is GCM notification & what is the Use?
ans : will be covered later
7. What is the us of 9-Patch image?
ans : 9-patch images are scalable, without loosing resolution.
nine patch image extension is .9.png
draw9patch.exe file is used to generate 9 patch image.
8. What is launcher activity?
ans : It is the starting screen that gets started, when user opens the applicaiton.
10. How to set first/ default screen?
ans : by going to manifest file, use <intent-filter> with
<category .. LAUNCHER> & <action...MAIN>
9. How to change application language based on phone location?
ans : will be covered later.
11. what is the use Manifest file?
ans : Without manifest, our application & activities will
not start.
12. Tell me about Build.gradle?
ans : already covered.
Interview questions part-4:
1. what is android?
ans : it is an o.s for mobiles and tablets [or]
it is a software which contains 4 layers.
os/ libraries/ framework/ applications.
2. what is a fragment?
ans : fragment is a modular & reusable UI component.
[or]
fragment is used to design screens/applications for
mobles & tablets. i.e for portatit mode & landscape
mode.
3. what is a recycler view?
ans : RecyclerView is introduced in MaterialDesign [5.0]
RecyclerView is faster than ListView, because of
ViewHolder design pattern.
4. how will you pass the data?
ans : Using intent & putextra() - between activities.
[or] bundle & setarguments() - activity to fragment.
5. what is bundle?
ans : bundle is a container which stores data in key,val pairs
we will use Bundle in onsaveinstancestat &
onrestoreinstancestate, when user rotates the phone.
6. what is manifest file?
ans : this file contains <manifest> tag, <application> tag
<activity..> tags.
this file also has <intent filter>
this file also has <uses-permission > tag.
it talks about application components.
7. what is build gradle?
ans : It is a tool/program, which comes along with android
studio, which generates apk file.
In build.gradle, in dependencies section we will
keep libraries used in the application.
eg : YouTubeAndroidPlayerApi.jar
compile 'com.support.recyclerview:26+'
compile 'com.support.cardview:26+'
...material design...
...google maps...
...appcompat v7...
8. what is zomato app?
ans :
9. how do you design 20% overlapping 2 images?
ans : framelayout
10. what are the methods of asynctask? [100%]
ans : onpreexecute, doinbackground, onprogressupdate,
onpostexecute.
11. what is joins?
ans : outer join, inner join, self join.
12. what do you do onpostexecute?
ans : 
onpost execute method the execution of the response task will be finished.
public class MyAsyncTask extends AsyncTask<Void, Void, String> {
  public AsyncResponse delegate = null;

    @Override
    protected void onPostExecute(String result) {
      delegate.processFinish(result);
    }
 }
13. how do you use http request/ http response?
ans : 
First of all, request a permission to access network, add following to your manifest:
<uses-permission android:name="android.permission.INTERNET" />
Then the easiest way is to use Apache http client bundled with Android:
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(new HttpGet(URL));
    StatusLine statusLine = response.getStatusLine();
    if(statusLine.getStatusCode() == HttpStatus.SC_OK){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        String responseString = out.toString();
        out.close();
        //..more logic
    } else{
        //Closes the connection.
        response.getEntity().getContent().close();
        throw new IOException(statusLine.getReasonPhrase());
    }
If you want it to run on separate thread I'd recommend extending AsyncTask:
class RequestTask extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... uri) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String responseString = null;
        try {
            response = httpclient.execute(new HttpGet(uri[0]));
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                responseString = out.toString();
                out.close();
            } else{
                //Closes the connection.
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
        } catch (ClientProtocolException e) {
            //TODO Handle problems..
        } catch (IOException e) {
            //TODO Handle problems..
        }
        return responseString;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        //Do anything with response..
    }
}
You then can make a request by:
   new RequestTask().execute("http://deftminds.com");
14. when I open application, how many life cycle
methods will be called?
ans : oncreate, onstart, onresume.
15. when we press home button what happens?
ans : onpause, onstop will be called.
note : activity is not destroyed, it is still in memory.

Comments

Popular posts from this blog

Why Ethereum Smart Contracts Make It Hard to Get Payments

  The Unique Role of Smart Contracts in Ethereum One of Ethereum’s standout features is its ability to host diverse applications on its blockchain using smart contracts. However, these smart contracts, while powerful, sometimes complicate simple tasks. For instance, determining the amount of ETH deposited into a specific Ethereum address can be surprisingly complex. This is because you cannot understand the actions of a smart contract without executing it. Synchronizing Blockchain Internals and Externals Smart contracts operate exclusively within the blockchain's data, reading and writing information stored on-chain. This limitation does not prevent the creation of valuable applications, such as multi-signature wallets or tokens like ERC-20 and ERC-721, which rely solely on on-chain data. However, most practical applications also require interaction with off-chain systems. Take cryptocurrency exchanges, for example. Exchanges facilitate converting ETH into fiat currency or vice ver...

Room + ViewModel + LiveData + RecyclerView (MVVM)

Part 1 - Introduction Part 2 – Entity Part 3 – DAO & RoomDatabase Part 4 – Repository Part 5 – ViewModel Part 6 – RecyclerView + Adapter Part 7 – Add Note Activity Part 8 – Swipe to Delete Part 9 – OnItemClickListener & Update Functionality Part 10 – ListAdapter                     Part 1 - Introduction In this tutorial we will build a note taking app, using the Android Architecture Component libraries (Room, ViewModel, LiveData and LifeCycle), a RecyclerView and Java. The data will be stored in an SQLite database and supports insert, read, update and delete operations. For this we will follow the official recommendations from the “Guide to App Architecture” (link below). In part 1 we will learn what the Architecture Components are, how they work and why we need them. We will learn about the problems that arise from the Activity and Fragment lifecycle, configuration changes and bloated, tightly coupled cl...

DodgeInsetEdges

The layout_dodgeInsetEdges together with the layout_insetEdge attribute, to move views within a CoordinatorLayout out of the way of other views. This behavior is the default behavior for FloatingActionButtons and Snackbars , but we will also apply it to views like normal buttons and bottom sheets. In Mainactivity.java add the code below stated:- import android.support.design.widget.BottomSheetBehavior; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity {     private BottomSheetBehavior bottomSheetBehavior;     @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activ...