Kotlin Introduction





Hello friends finally we are starting to lean Kotlin programming, here we are going to learn about basic introduction of Kotlin.

1. What is Kotlin?


Kotlin is a object-oriented programming  language like java programming language  that is interoperable with the Java virtual ,machine and It can also be compiled to JavaScript source code.
Kotlin is also for web apps and server-side.

Kotlin was developed by JetBrains  and year 2017 Google announced that Kotlin would be the first officially supported to Android Studio.


2. Kotlin for Android


we know that before Kotlin there was not any language to develop android app. now we can develop Android app with Kotlin programming language in android studio.
If i talk about Java there is lot of redundancy results in verbose and the code can be longer code. but The Kotlin has been simplified and more modern language to making easier for beginners to learn.The most Kotlin features are null safety, eliminating null pointer exception errors.

3.  Why Kotlin?

Kotlin is a latest open source object-oriented programming language for Java Virtual machine enables and we can also compile to JavaScript Source code. Kotlin is very similar to Java in  statically typed  structure and object oriented. Kotlin reduce the complexity and length of code .
We know that java is always a difficult  to handle null values and if i talk about Kotlin in this department you don’t have to write extra logic to manage null values.
In Kotlin we  don’t have to write class for simple logics and there are many things like extension function, 

4. Fetures of Kotlin

As a android developer i think the  Kotlin is very useful for Andoird development because of the some very useful features :
  • Kotlin Supported by Google 
  • The most imported Null Safety in Kotlin
  • Kotlin is open source and easy to use 
  • Full Java Interoperability 
  • We can compiles Kotlin  into  JVM bytecode and  JS also
  • Kotlin use defaulted parameters
  • Kotlin use Extension functions
  • Kotlin wants you to write less code



Top 10 important Android Interview Question with Answer for Experience Android Developer?


Hello Friends today i am sharing some advance android interview question with answers please read all questions it can help to crack interview.

if you want to learn about top most android basic interview question and answer please click blow link it can help to understand about basic android question.
https://android4point.blogspot.in/2016/12/top-10-android-interview-question-and.html

1.What is Asynctask class and its methods in android?

What is AsyncTask class?

AsyncTask is a android class which is allows to run instructions in the background and to synchronize again with the main thread.

when started AsyncTask class

AsyncTask is started when we called execute() method. This execute() method calls the doInBackground() and the onPostExecute() method.

What is use of AsyncTask?

This AsyncTask class allows to perform background operations and publish results on the UI thread without manipulate threads or handlers.

you must extend doInBackground() method inside AsyncTask class(its necessary).

There are 4 methods you will need to implement in AsyncTask class:

1. onPreExecute() – called on the UI thread before the thread starts running. This method is usually  used to setup the task, for example by displaying a progress bar.

2. doInBackground(Params…) – this is the method that runs on the background thread. In this method you should put all the code you want the application to perform in background. Referring to our Simple RSS Aplication, you would put here the code that downloads the XML feed and does the parsing. The doInBackground() is called immediately after onPreExecute(). When it finishes, it sends the result to the onPostExecute().

3. onProgressUpdate() – called when you invoke publishProgress() in the doInBackground().

4. onPostExecute(Result) – called on the UI thread after the background thread finishes. It takes as parameter the result received from doInBackground().

2.What is ANR  in Android and How can the ANR be prevented?

What is ANR?

First thing we know that ANR means Application Not Responding.
ANR will occur when you are running long time UI thread.

How to avoid ANR?

To avoid ANR we can run your lengthy task in separate thread,Handlers,AsyncTask etc. instead of UI thread(Main Thread).


3. Sqlite in Android?

Android OS provides many ways to store data. SQLite is one of the best way to storing user data.because the SQLite is a light weight database which comes with Android OS.In android os 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.

if you want to know more about Sqlite and demo example please click blow link.
https://goo.gl/YaorXB

4. What is DDMS? Describe some of its capabilities.

Now a time we are using Android Studio which is provide debugging tool called the Dalvik Debug Monitor Server (DDMS), which provides so many facility for developer like screen capture on the device, thread and heap information on the device,port-forwarding services, logcat, process etc.

How to run(Open) DDMS in android?

Open Android studio and click on Tools>Android>Android device Monitor.

How to DDMS works?


When we start DDMS it connects to adb (or currently running android devices). When a device is connected, a VM monitoring service is created between adb and DDMS, which notifies DDMS when a VM on the device is started or terminated.

5. What is difference between Serializable and Parcelable ? Which is best approach in Android?

serialization 

android developing we used java serialization as a data transfer mechanism between activities and it is a marker interface which implies the user cannot marshal the data according to their requirements.
This helps identify the Java objects member and behavior, but also ends up creating a lot of garbage objects. Due to this, the Serialization process is slow in comparison to Parcelable

Parcelable

Parcelable is an Android specific interface where you implement the serialization yourself.
In Parcelable, developers write custom code for marshaling and unmarshaling so it creates less garbage objects in comparison to Serialization.

6. What are different data storage options are available in Android?

Android has following options for you to save persistent data.We can choose depend on own specific needs, such as whether data should be private to over application or accessible to other application and also depend on how much space required by data.
The data storage options are the following.
  •     Shared Preferences
  •     Internal Storage
  •     External Storage
  •     SQLite Databases
  •     Network connection
if you want to know more about this topic please click blow link
https://goo.gl/7DCTIR

7. Is it possible to add a fragment without using a user interface?

Ans. Yes, it is possible.
when we want to create a background behavior for a particular activity. You can do this by using add(Fragment,string) method to add a fragment from the activity.

8. What do you  know about Sticky Intent?

A Sticky Intent is a like broadcast from sendStickyBroadcast() method.


9. What is an action?

An action is a Intent sender which is want to get as a response.we are use action tag inside the manifest.xml.file with the help of inside Intent filter.


10. what is Handler in android?

Handler is like a thread but Handler allow to user interference in android OS like update the value of Textview from other thread, it is necessary that UI objects could only be updated in UI Thread. Also, when you just want to run some light code later(like delay for some ms) you can use Handler because it's lighter and faster.

The Handler is associated with the application's main thread. it handles and schedules messages and runnables sent from background threads to the app main thread.

11. Different between Handler and thread?

11.1 When we have to use Thread in android:

1) First thing is that we have to use thread when we execute long running process that would block the UI from updating. 

2) Second thing is when we lock the UI thread for more than 5 seconds then the user will be prompted for  "kill or wait" by the OS.

3)When you're doing a heavy work like network communication, or decoding large bitmap files, a new thread is preferred. 

11.2 When we have to use Handlers in android:

1) I recommended to you use for Handler when you just want to run some light code like mili of second because Handler is lighter and faster.
when you just want to run some light code later(like delay for 300ms) you can use Handler because it's lighter and faster.

2) We can use also Handlers when we want to bound to threads that allow you to communicate with the UI thread (update the UI).



Top 10 most important Interview question with Answer in android for fresher?


Hello Friends today i am going to share about top 10 interview question with answer.please read all question carefully that will help you to crack interview

Top 10 Interview Questions with Answer are follows:-


1.What is Activity and Activity Life Cycle

 Activity is an component and this is single screen for user interference.  
In Activity Lifecycle is controlled by 7 methods 

Activity methods are :-
1) onCreate - called when activity is first created.
2) onStart - called when activity is becoming visible to the user.
3) onResume - called when activity will start interacting with the user.
4) onPause - called when activity is not visible to the user.
5) onStop - called when activity is no longer visible to the user.
6) onRestart - called after your activity is stopped, prior to start.
7) onDestroy - called before the activity is destroyed.

For more details about Activity click here 


2.What are the basic key components of Android Architecture? 

There are 4 key components of Android  Architecture  :

- Linux Kernel
- Libraries
- Android Framework
- Android Applications

3. What is Intent and Intent filter?

3.1 Intent 

The Intent is the message that is passed between android components such as activities, content providers, broadcast receivers etc.
There are two type Intent in android.
1. Implicit Intent
2. Explicit Intent  

3.2 Intent filter

We know that Intent is used to call an another activity and  The android OS uses filters to pinpoint the set of  Services, Broadcast receivers and Activities that can handle the Intent with help of specified set of action, categories, data scheme associated with an Intent. we will use of  <intent-filter> element inside the manifest file and use of that we can categories and data types associated with any activity, service, or broadcast receiver.


4.What is DDMS in Android? 

DDMS means Dalvik Debug Monitor Server that ships with Android. 
It provides a wide array of debugging features Like : port-forwarding services, location data spoofing, screen capture, thread and heap information ,incoming call and SMS spoofing etc.

5.What is Service and Life Cycle? 

A service is runs on background without user interaction such as playing music, handle network transactions, interacting content providers etc..

LifeCycle of Service

Methods are service LifeCycle :

1. onStartCommand()

This method is called when the another component like an activity, requests that the service be started, by calling startService(). 
Note - Once this method executes, the service is started and can run in the background indefinitely. it is your responsibility to stop the service when its work is done, by calling stopSelf() or stopService() methods

onBind()
You need to override this method, only if you are defining your service as bounded service. This method is called, when another component wants to bind with the service by calling bindService(). In your implementation of this method, you must provide an interface that clients use to communicate with the service, by returning an IBinder. You must always implement this method, but if you don’t want to allow binding, then you should return null.
The system calls this method when another component wants to bind with the service by calling bindService(). If you implement this method, you must provide an interface that clients use to communicate with the service, by returning an IBinder object. You must always implement this method, but if you don't want to allow binding, then you should return null
2.onUnbind()

This method called when all clients have disconnected from a particular interface published by the service.
3. onRebind()

This method called when new clients have connected to the service, after it had previously been notified that all had disconnected in its onUnbind(Intent).
4. onCreate()

This method is called while the service is first created  using onStartCommand(). Here all the service initialization is done. This method is called only single time.  
5. onDestroy()

This method called when the service is not used for long tome and is being destroyed. This method are clean up any resources such as threads, registered listeners, receivers, etc.
steners, receivers, etc.

Friends this tutorial will help to you crash interview based on android development. Read all the questions carefully. If you have any query about this Content please comments me on comment box blow.

6. What is Fragment and Life Cycle?

Android Fragment is a part of  Activity for build dynamic User Interface.we can also know as Sub-Activity.we can use multiple fragment in a Activity.

Fragment Life Cycle

The following lifecycle for fragment blow - :

1) onAttach: when the fragment attaches to the activity
2) onCreate: when a new fragment instance initializes.
3) onCreateView: when a fragment creates its portion of the view hierarchy, 
4) onActivityCreated: when the fragment’s activity has finished its own onCreate event
onStart: when the fragment is visible; a fragment cannot start until its starts and often starts immediately after the activity does
5) onResume: when the fragment is visible and interactable; a fragment cannot resume until its activity resumes and often does so in quick succession after the activity

There’s more. These lifecycle events happen when you remove a fragment:

6) onPause: when the fragment is no longer interactable; 
7) onStop: when the fragment is no longer visible; it occurs either after the fragment is about to be removed or replaced or when the host activity stops
8) onDestroyView: when the view and related resources created in onCreateView is removed from the activity’s view hierarchy and destroyed

9) onDestroy: when the fragment does its final clean up
10) onDetach: when the fragment is detached from its host activity

7. what is Android AndroidManifest.xml ?

The AndroidManifest.xml is a XML ifile that contain information of your package, including components of the application such as activities, services, broadcast receivers, content providers etc.  

8. What is ANR? and How can the ANR be prevented?

ANR means A for Application, N for NOT, R for Responding
If i talk about in brief an ANR will occur if you are running a process on the UI thread which takes a long time, usually around 5 seconds.

9.What is Broadcast Receiver?

The  broadcast receiver is a Android component which allows you to register for system or application events likelike sms message received , phone call received/pick/cut ,battery status changed, the Wifi came on etc.


10.Difference between a regular .png image and a nine-patch image? 

The  Nine-patch image allows resizing accroding to content 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.

Thanks

There are four ways to Store Data in android

Android has following options for you to save persistent data.We can choose depend on own specific needs, such as whether data should be private to over application or accessible to other application and also depend on how much space required by data.
The data storage options are the following.

  •     Shared Preferences
  •     Internal Storage
  •     External Storage
  •     SQLite Databases

1. Shared Preferences

Private data is saved as a key-value pair.

//Initialized SharedPreferences;
SharedPreferences sp;
  sp=getSharedPreferences("Test", MODE_PRIVATE);

//put data by Editor with the help of SharedPreferences
SharedPreferences.Editor ed=sp.edit();
ed.putString("name", name);
ed.putString("age", age);
ed.commit();

//get data by SharedPreferences
  String nm=sp.getString("name","");
  String  age=sp.getString("age", "");


2. Internal Storage

It's store private data on device memory and it's use only private data,Android has provide the facility to save data and read data from the device internal memory. We can use FileInputStream and FileOutputSream class to read and write data into file.


//write data in any file  

try {
//Initialized OutputStream 
OutputStream out=openFileOutput("Enter Your file name", MODE_PRIVATE);
  String data1="your test whenever you want";
  byte[]  databyte=data1.getBytes();
  out.write(databyte);
  out.close();
catch (FileNotFoundException e) {
e.printStackTrace();
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


//read data from any file  

    String name="Enter Your file name";
    String line= "";
try {
InputStream inp=openFileInput(name);
InputStreamReader is=new InputStreamReader(inp);
BufferedReader br=new BufferedReader(is);
while( br.readLine()!=null){
line=br.readLine();
data.setText(line);
}
}
 catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


3. External Storage

it's store data publicly in external memory like external memory card.

//write data in any file  

String file="Your File name"+".txt";
try {
   File f_path=Environment.getExternalStorageDirectory();
        File fl1=new File(f_path,file);
         FileWriter fw=new FileWriter(fl1);
     fw.write(data1);
     fw.close();
 Toast.makeText(sdcard.this, "file Write", 4).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


//read data from any file  

String name="Enter File Name"+".txt";
File fr=Environment.getExternalStorageDirectory();
File fi=new File(fr,name);
FileReader ff;
try {
ff = new FileReader(fi);
BufferedReader br=new BufferedReader(ff);
String st="";
while(true){
String dt=br.readLine();
if(dt==null)
break;
st+=dt+"\n";
}
data.setText(st);
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


 4. SQLite Databases

It's store structured data and it use to perform database operations on android devices. SQLiteOpenHelper class is use for SQLite database.
for complete information with example click 



and we have another option to store data - on Server throw network connection.

Network connection

there is another way to store data for android developer.
it's store data in own server.
you can use following class for Network connection
java.net.*
android.net.*


Thanks you?

Menus in Android

Menus is a most important part of android application.menu are use for handle common features of activity.
In this tutorial we will learn about how to create menu in application with simple ways.

Type of Menu:-there are two type of menu in android 

1. Option menu
2. Context menu

1) Options menu

Now we will learn to create option menu with simple step.

1.Now first Create a folder named menu inside your project res directory.Now let us add a new xml file named menu_item.xml file 
2.add item in menu_item.xml.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- this is first for Search item-->
<item
        android:id="@+id/action_search1"
        android:title="Profile"
        android:orderInCategory="100"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="ifRoom" />
    <!-- this is use for Search item-->
    <item
        android:id="@+id/action_search"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="always"
        app:actionViewClass="android.support.v7.widget.SearchView"
        android:title="Search"/>
   <!-- this is use for setting option-->
    <item
        android:id="@+id/action_settings"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        app:showAsAction="never" />
</menu>

3.Now we will implement the onCreateOptionsMenu() method  in Activity class and inflate the menu items created in the menu_item.xml. We will also override method OnOptionsItemSelected  for handle the events when user presses the menu option in android.

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.home, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        if(id == R.id.action_search){
       Toast.makeText(getApplicationContext(), "Search action is  selected!" ,                                                   Toast.LENGTH_SHORT).show();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }



1.output screen for three type menu item .



menu item 1 : this is SearchView item and it's :showAsAction="always" it mean this is always show on ActionBar.

menu item2 : this is TextView item and it's showAsAction="ifRoom" it mean this is show in ActionBar if space available on ActionBar otherwise it will open with menu item list as show on image like other menu(three dot).

other menu : this is contain all other menu like howAsAction="never properties menu item as well as showAsAction="ifRoom" item if no space on ActionBar.


2) Context menu

Now we will talk about to create option menu with simple step.

Context Menu is also useful part of application.When we want to open menu in long press of any view class and subClass of android.Context Menu appears when user long press on a View like ListView, GridView etc.

You must to register each view whenever  you want to associated with the context menu.
like this;-
   registerForContextMenu(lv); // lv is a List View

Lets take a exampke.

package com.example.contextmenuapp;

import java.util.ArrayList;
import android.app.ListActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class StudentActivity extends ListActivity
{
ListView lv;
ArrayList<String> list;
ArrayAdapter<String> adp;
@Override
protected void onCreate(Bundle savedInstanceState) {

lv = getListView();
list = new ArrayList<String>();
list.add("Dheeraj");
list.add("Manish");
list.add("Rohan");
list.add("Prakhar");
list.add("Pranav");

adp = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
lv.setAdapter(adp);
registerForContextMenu(lv);

super.onCreate(savedInstanceState);
  }
  @Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) 
 {
      menu.add(0,1,0,"Red");
      menu.add(0,2,0,"Green");
      menu.add(0,3,0,"Blue");
 super.onCreateContextMenu(menu, v, menuInfo);
 }
    @Override
    public boolean onContextItemSelected(MenuItem item) 
    {
        int id = item.getItemId();
        AdapterContextMenuInfo minf = (AdapterContextMenuInfo) item.getMenuInfo();
        
            TextView tv = (TextView) minf.targetView;
       switch(id)
 {
 case 1:
 tv.setTextColor(Color.RED);
 break;
 case 2:
 tv.setTextColor(Color.GREEN);
 break;
 case 3:
 tv.setTextColor(Color.BLUE);
 break;
 }
     return super.onContextItemSelected(item);
    }
}

Your screen something like this:- 

after long press on list item 




Thanks You

Activity and Activity Life Cycle in Android


What is Activity?

Activity is a component and this is a single screen for user interference,
In any Application can be multiple activity according to depend on user screens in application and its compulsory to define all activity on AndroidManifest.xml file other wise we will get an error ClassNotFindException and also we have to declear the starting point of application with the help of defile launch activity in AndroidManifest.xml file by use of <intent-filter> that includes the MAIN action as show an example below.
Activity has own life cycle and we invoke the method  according to requirement .the starting point of Activity is onCreate() method. now we will discuss about all collection  callback methods of activity lifestyle.

Activity LifeCycle?

There are 7 life cycle methods of android.app.Activity class.






1) onCreate();

this called When Activity created first time

onStart();

onStar called when activity becoming visible to user. this is called from two times - first after OnCreate method and second after onRestart method. After called onCreate method OnResume call immediately.

onResume();

onResume method invoke when Activity will interact with user. It's followed by onPause method and this method always use for change UI during the period of when Activity not visible.when onResume is running condition at this point Activity is on top of the Activity stack.

onPause();

onPause method is called when the activity into the background or when the activity becomes partially invisible. we have two Activity x and y.  suppose Activity  x is on top of the Activity stack and Activity y is launched in front of activity x, onPause will be invoke on x.

onStop();

onStop Called when activity are no longer visible to user.You will next receive either onRestart(), onDestroy(), this is happened because new activity is being started and the activity is being destroyed.

onRestart();

onRestart:  Called when the activity has been stopped and is restarting again and it's  called only after onStop.

onDestroy();

onDestroy(): called after the Activity getting killed,When the user Enter(press) back button on any Activity so activity gets destroyed and control will return to the previous Activity or it’s destroyed and completely removed from memory,



Example:-


package com.android4point.lifecycle;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class ActivityLifeCycle extends Activity {

    // this called When Activity created first time 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Toast.makeText(LifeCycleActivity.this,"onCreate", Toast.LENGTH_SHORT).show();
    }
// onStar called when activity becoming visible to user.
    @Override
    protected void onStart() {
       // TODO Auto-generated method stub
       super.onStart();
        Toast.makeText(LifeCycleActivity.this,"onStart", Toast.LENGTH_SHORT).show();
    }
// onResume method invoke when Activity will interact with user. 
    @Override
    protected void onResume() {
       // TODO Auto-generated method stub
       super.onResume();
        Toast.makeText(LifeCycleActivity.this,"onResume", Toast.LENGTH_SHORT).show();
    }
//called when the activity becomes partially invisible
    @Override
    protected void onPause() {
       // TODO Auto-generated method stub
       super.onPause();
        Toast.makeText(LifeCycleActivity.this,"onPause", Toast.LENGTH_SHORT).show();
    }
// Called when the activity has been stopped and is restarting again 
    @Override
    protected void onRestart() {
       // TODO Auto-generated method stub
       super.onRestart();
        Toast.makeText(LifeCycleActivity.this,"onRestart", Toast.LENGTH_SHORT).show();
    }
//onStop Called when activity are no longer visible to user
    @Override
    protected void onStop() {
       // TODO Auto-generated method stub
       super.onStop();
        Toast.makeText(LifeCycleActivity.this,"onStop", Toast.LENGTH_SHORT).show();
    }
//called after the Activity getting killed.
    @Override
    protected void onDestroy() {
       // TODO Auto-generated method stub
       super.onDestroy();
        Toast.makeText(LifeCycleActivity.this,"onDestroy", Toast.LENGTH_SHORT).show();
    }
}


Thanks


SQLite DataBase in Android?

Hi  Friends in this tutorial we will learn about sqlite database, In this tutorial we learn basic concept of Sqlite Database and how to use of tham.so pleaase read all my steps for learning Sqlite Database.

1. What is Sqlite Database?

SQLite is a open source relational database,it's used to perform database operation on device and its features like SQL syntax, transactions and prepared statements
In android Sqlite database There are several SQLite commands such as these are REATE,SELECT,INSERT.UPDATE and DELETE.
Note - In android Sqlite database is requires limited memory at runtime (approx. 250 KByte)

2. Supporting Data Type in Sqlite database?

SQLite supports the data types TEXT (similar to String in Java), INTEGER (similar to long in Java) and REAL (similar to double in Java). All other types must be converted into one of these fields before getting saved in the database.SQLite itself does not validate if the types written to the columns are actually of the defined type, e.g. you can write an integer into a string column and vice versa.


3. What is use of SQLite in Android

SQLite is embedded into every Android device. Using an SQLite database in Android does not require a setup procedure or administration of the database.

You only have to define the SQL statements for creating and updating the database. Afterwards the database is automatically managed for you by the Android platform.

Access to an SQLite database involves accessing the file system. This can be slow. Therefore it is recommended to perform database operations asynchronously.

If your application creates a database, this database is by default saved in the directory DATA/data/APP_NAME/databases/FILENAME.


4.How to use SQLite Database.

here i am providing all basic coding for use of Sqlite database please create all classes (java files)
in your project and use of them.
i am providing you source code blow.

5. Source code 

                                      Download Source 



6. Screen Shot for this code




7. Follow step bay step to create app with SQlite Dtabase


1.create modal class for store student detail.
Here is a Modal class in your project Student.java.

package com.example.model;
import java.io.Serializable;
import java.util.ArrayList;

public class Student implements Serializable 
{
private int roll;
private String name,branch,phone;
private ArrayList<StudentMarks> marks;

public Student(int roll, String name, String branch, String phone) {
super();
this.roll = roll;
this.name = name;
this.branch = branch;
this.phone = phone;
}
public Student(int roll, String name, String branch, String phone,
ArrayList<StudentMarks> marks) {
super();
this.roll = roll;
this.name = name;
this.branch = branch;
this.phone = phone;
this.marks = marks;
}
public int getRoll() {
return roll;
}
public void setRoll(int roll) {
this.roll = roll;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public ArrayList<StudentMarks> getMarks() {
return marks;
}
public void setMarks(ArrayList<StudentMarks> marks) {
this.marks = marks;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return name;
 }
}

2. Defining database helper class

At this point we have to write our own class to create and update database using the SQLiteOpenHelper:
MyDBHelper.java

 Example :

package com.example.helper;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class MyDBHelper extends SQLiteOpenHelper
{
public static final String DBNAME = "StudentDB";
public static final int DBVER = 1;

public MyDBHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("create table student (roll integer primary key,name text,branch text,phone text)");
db.execSQL("create table studmarks (mid integer primary key autoincrement,roll integer,date text,marks real)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
if(oldVersion==1 && newVersion==2)
{}
if(oldVersion==1 && newVersion==3)
{}
if(oldVersion==2 && newVersion==3)
{}
}
}

4.Create database manager class

At this point we have to write our own class to handle database operations such as creation, upgrading, reading and writing. Database operations are defined using the MyDBHelpe class:

package com.example.manager;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.helper.MyDBHelper;
import com.example.model.Student;

public class StudentManager 
{
  private MyDBHelper helper;
  private SQLiteDatabase db;
  private Context ctx;
  
  public StudentManager(Context ctx)
  {
  this.ctx = ctx;
  helper = new MyDBHelper(ctx, MyDBHelper.DBNAME,null, MyDBHelper.DBVER);
  }
  
  public boolean addStudent(Student stud)
  {
  db = helper.getWritableDatabase();
  
  ContentValues cv = new ContentValues();
  cv.put("roll",stud.getRoll());
  cv.put("name",stud.getName());
  cv.put("branch",stud.getBranch());
  cv.put("phone",stud.getPhone());
     
  long x = db.insert("student", null, cv);
  db.close();
  
  if(x>0)
    return true;
  return false;  
  }
public ArrayList<Student> getStudents()
{
ArrayList<Student> list = new ArrayList<Student>();
db = helper.getReadableDatabase();
Cursor cr = db.rawQuery("select * from student",null);
while(cr.moveToNext())
{
int roll = cr.getInt(0);
String name = cr.getString(1);
String branch = cr.getString(2);
String phone = cr.getString(3);
Student s = new Student(roll, name, branch, phone);
list.add(s);
}
cr.close();
db.close();
return list;
public void deleteStudent(int roll)
{
db = helper.getWritableDatabase();
db.delete("student","roll=?",new String[]{roll+""});
db.close();
}
public void updateStudent(Student s)
{
  db = helper.getWritableDatabase();
  
  ContentValues cv = new ContentValues();
    cv.put("name", s.getName());
  cv.put("branch", s.getBranch());
  cv.put("phone", s.getPhone());
  
  db.update("student", cv, "roll=?",new String[]{s.getRoll()+""});
  db.close();
}

public ArrayList<Student> getStudentByRoll(int roll)
{
ArrayList<Student> s = new ArrayList<Student>();
db = helper.getReadableDatabase();
Cursor c  = db.rawQuery("select * from student where roll="+roll, null);
if(c.moveToNext())
{
int r = c.getInt(0);
String n = c.getString(1) ;
String b = c.getString(2) ;
String p = c.getString(3) ;
s.add(new Student(r, n, b, p));
}
db.close();
return s;
}
}

5.create main_Activity
Here is a main Activity  for showing all students list with the help of ListActivity and also use Option Menu like show on Screen

MainActivity.java



package com.example.view;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

import com.example.facultyapp.R;
import com.example.manager.StudentManager;
import com.example.model.Student;
import com.example.model.StudentAdapter;

public class MainActivity extends  ListActivity 
{
ListView lv;
ArrayList<Student> studList;
StudentAdapter sadp;
StudentManager sm;
public int updatepos;
public void deleteStud(Student s)
{
studList.remove(s);
sadp.notifyDataSetChanged();
}
@Override
protected void onCreate(Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);
sm = new StudentManager(this);
lv = getListView();
studList = sm.getStudents();
sadp = new StudentAdapter(studList, this);
lv.setAdapter(sadp);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) 
{
int id = item.getItemId();
switch(id)
{
case R.id.addStud:
Intent in = new Intent(MainActivity.this,AddStudentActivity.class);
startActivityForResult(in, 11);
break;
case R.id.searchStud: 
openDialog();
break;
case R.id.allStud:
studList.clear();
sadp.clear();
studList = sm.getStudents();
sadp = new StudentAdapter(studList, MainActivity.this);
lv.setAdapter(sadp);
break;
}
return super.onOptionsItemSelected(item);
}
private void openDialog() 
{
   AlertDialog.Builder bd = new AlertDialog.Builder(MainActivity.this);
   bd.setTitle("Search Student");
   
   final EditText et = new EditText(MainActivity.this);
   bd.setView(et);
   bd.setPositiveButton("Roll", new DialogInterface.OnClickListener()
   {
@Override
public void onClick(DialogInterface dialog, int which) {
studList.clear();
sadp.clear();
int roll = Integer.parseInt(et.getText().toString());
studList = sm.getStudentByRoll(roll);
sadp = new StudentAdapter(studList, MainActivity.this);
lv.setAdapter(sadp);
}
   });
   bd.setNegativeButton("Branch", new DialogInterface.OnClickListener()
   {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
   });
   AlertDialog dlg = bd.create();
   dlg.show();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
if(requestCode==11 && resultCode==RESULT_OK)
{
Student s = (Student) data.getSerializableExtra("stud");
studList.add(s);
sadp.notifyDataSetChanged();
}
if(requestCode==12 && resultCode==RESULT_OK)
{
Student s = (Student) data.getSerializableExtra("s");
studList.set(updatepos, s);
sadp.notifyDataSetChanged();
}
super.onActivityResult(requestCode, resultCode, data);
}
}

23.Create Layout for adaptor view (Row for list of students)

this is XML coding for show item on the list view    studview.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
    <TextView
        android:id="@+id/nameTv"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />
    <Button
        android:id="@+id/viewBT"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="View" />
    <Button
        android:id="@+id/updateBT"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Update" />
    <Button
        android:id="@+id/delBT"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Delete" />
</LinearLayout>

45. Create Adaptor  
At this point we are creating Adaptor using BaseAdaptor  StudentAdapter.java

package com.example.model;

import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.example.facultyapp.R;
import com.example.manager.StudentManager;
import com.example.view.MainActivity;
import com.example.view.UpdateActivity;

public class StudentAdapter extends BaseAdapter
{
private ArrayList<Student> list;
private Context ctx;
public StudentAdapter(ArrayList<Student> list, Context ctx) {
super();
this.list = list;
this.ctx = ctx;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// 
LayoutInflater inf = (LayoutInflater) ctx.getSystemService(ctx.LAYOUT_INFLATER_SERVICE);
View vw = inf.inflate(R.layout.studview, null);
TextView tv = (TextView) vw.findViewById(R.id.nameTv);
Button viewBT = (Button) vw.findViewById(R.id.viewBT);
Button delBT = (Button) vw.findViewById(R.id.delBT);
Button upBT = (Button) vw.findViewById(R.id.updateBT);
final Student s = list.get(position);
upBT.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) 
{
Intent in = new Intent(ctx, UpdateActivity.class);
in.putExtra("stud",s);
MainActivity act = (MainActivity) ctx;
act.updatepos=position;
act.startActivityForResult(in, 12);
}
});
delBT.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) 
{
   int roll = s.getRoll();
   StudentManager sm = new StudentManager(ctx);
   sm.deleteStudent(roll);
   
   MainActivity act = (MainActivity) ctx;
   act.deleteStud(s);
}
});
viewBT.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) 
{
AlertDialog.Builder bd = new AlertDialog.Builder(ctx);
bd.setTitle("Student..");
TextView tv = new TextView(ctx);
String data = "Roll - " + s.getRoll() + "\n";
data += "NAme - " + s.getName() + "\n";
data += "Phone - " + s.getPhone() + "\n";
data += "Branch - " + s.getBranch() + "\n";
tv.setText(data);
bd.setView(tv);
bd.setPositiveButton("Close",new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
AlertDialog dlg = bd.create();
dlg.show();
}
});
tv.setText(s.getName());
return vw;
}
public void clear() {
// TODO Auto-generated method stub
list.clear();
}  
}

6.Create Layout for add student detail  

Here an Example of  XML file for creating layout of add new students. addstud.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <EditText
        android:id="@+id/rollET"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Roll Number" 
        android:layout_marginTop="10dp"
        >
        <requestFocus />
    </EditText>
    <EditText
        android:id="@+id/nameET"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Student Name"
        android:layout_marginTop="10dp"
         />
    <Spinner
        android:id="@+id/branchSP"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:layout_marginTop="10dp"/>
    <EditText
        android:id="@+id/phoneET"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:layout_marginTop="10dp"
        android:hint="Phone Number" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:layout_marginTop="10dp">
        <Button
            android:id="@+id/saveBT"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Save" />
        <Button
            android:id="@+id/canBT"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Cancel" />
    </LinearLayout>
</LinearLayout>


6. insert New DATA 

here we are creating new Activity AddStudentActivity.java    for inser data on Sqlite database.     


package com.example.view;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.facultyapp.R;
import com.example.manager.StudentManager;
import com.example.model.Student;

public class AddStudentActivity extends Activity 
{
EditText rollET,nameET,phoneET;
Spinner branchSP;
Button saveBT,canBT;
String [] branch = 
{
"CS","EC","IT","ME","CE","EE"
};
ArrayAdapter<String> branchadp;
StudentManager sm;
@Override
protected void onCreate(Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);
setContentView(R.layout.addstud);
rollET = (EditText) findViewById(R.id.rollET);
nameET = (EditText) findViewById(R.id.nameET);
phoneET = (EditText) findViewById(R.id.phoneET);
branchSP = (Spinner) findViewById(R.id.branchSP);
saveBT = (Button) findViewById(R.id.saveBT);
canBT = (Button) findViewById(R.id.canBT);
sm = new StudentManager(this);
branchadp = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,branch);
branchSP.setAdapter(branchadp);
saveBT.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) 
{
  int roll  = Integer.parseInt(rollET.getText().toString());
  String name = nameET.getText().toString();
  String branch = (String) branchSP.getSelectedItem();
  String phone = phoneET.getText().toString();
  
  Student stud = new Student(roll, name, branch, phone);
  
  boolean check = sm.addStudent(stud);
  
  if(check)
  {
  Toast.makeText(AddStudentActivity.this, "Record Insert !",2).show();
  Intent in = new Intent();
  in.putExtra("stud", stud);
  setResult(RESULT_OK, in);
  }
  else
  Toast.makeText(AddStudentActivity.this, "Record Insert Failed !",2).show();
  
  finish();
}
});
canBT.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
}


7.Create Layout for Update Student Detail 
here is XML Coding for updates students data by using EditText   updatestud.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/rollET"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Roll Number" 
        android:layout_marginTop="10dp"
        android:editable="false"
        >
        <requestFocus />
    </EditText>
    <EditText
        android:id="@+id/nameET"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Student Name"
        android:layout_marginTop="10dp"
         />
    <Spinner
        android:id="@+id/branchSP"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:layout_marginTop="10dp"/>
    <EditText
        android:id="@+id/phoneET"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:layout_marginTop="10dp"
        android:hint="Phone Number" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:layout_marginTop="10dp">
        <Button
            android:id="@+id/updateBT"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Update" />
        <Button
            android:id="@+id/canBT"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Cancel" />
    </LinearLayout>
</LinearLayout>


7. For  Update screen  
At this screen we can update database using UpdateActivity class


package com.example.view;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import com.example.facultyapp.R;
import com.example.manager.StudentManager;
import com.example.model.Student;

public class UpdateActivity extends Activity {

EditText rollET,nameET,phoneET;
Spinner branchSP;
Button upBT,canBT;
String [] branch = 
{
"CS","EC","IT","ME","CE","EE"
};
ArrayAdapter<String> branchadp;
StudentManager sm;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.updatestud);
rollET = (EditText) findViewById(R.id.rollET);
nameET = (EditText) findViewById(R.id.nameET);
phoneET = (EditText) findViewById(R.id.phoneET);
branchSP = (Spinner) findViewById(R.id.branchSP);
upBT = (Button) findViewById(R.id.updateBT);
canBT = (Button) findViewById(R.id.canBT);

sm = new StudentManager(this);
branchadp = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,branch);
branchSP.setAdapter(branchadp);

//creating a reference of Intent for getting data from previous Activity  
Intent in  = getIntent();
Student s = (Student) in.getSerializableExtra("stud");
rollET.setText(s.getRoll()+"");
nameET.setText(s.getName());
phoneET.setText(s.getPhone());
String b = s.getBranch();
for(int i=0;i<branch.length;i++)
{
if(b.equals(branch[i]))
{
branchSP.setSelection(i);
break;
}
}
canBT.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});

//click on update button 
upBT.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) 
{
   int roll = Integer.parseInt(rollET.getText().toString());
   String name = nameET.getText().toString(); 
   String branch = (String) branchSP.getSelectedItem();
   String phone = phoneET.getText().toString();
   Student s = new Student(roll, name, branch, phone);

   //call a method for update database 
      sm.updateStudent(s);

       Intent in = new Intent();
      in.putExtra("s",s);
      setResult(RESULT_OK, in);
      finish();
   }
  });
 }
}



ScreenShot :-






Source code 

Download Source 


if you if any an issue regarding this post please give me comment on comment box?

Thank You for reading my blog?