Wednesday, September 14, 2016

How are Java objects stored in memory?

Very frequent question on java that how java objects are stored in memory.

Ans: 

In Java, all objects are dynamically allocated on Heap.
In Java, when we only declare a variable of a class type, only a reference is created (memory is not allocated for the object). To allocate memory to an object, we must use new(). So the object is always allocated memory on heap.

For example, following program fails in compilation. Compiler gives error “Error here because t is not initialed”.

class Test {
    // class contents
    void show() {
        System.out.println("Test::show() called");
    }
}

public class Main {
    public static void main(String[] args) {
        Test t;
        t.show(); // Error here because t is not initialed
    }
}

Allocating memory using new() makes above program work.

class Test {
    // class contents
    void show() {
        System.out.println("Test::show() called");
    }
}
 
public class Main {
    public static void main(String[] args) {
        Test t = new Test(); //all objects are dynamically allocated
        t.show(); // No error
    }
}

in java basically there are different section where jvm allocate memory either loading time of class or run time.

1.) class area or method area -> here static data member gets memory at loading time of class.
2.) heap area -> here object get memory and it initialize all instance data member
at run time of class.
3.) stack area -> here local variable gets memory .

Maximize number of 0s by flipping a subarray in java

Maximize number of 0s by flipping a sub-array

Given a binary array, find the maximum number zeros in an array with one flip of a sub-array allowed. A flip operation switches all 0s to 1s and 1s to 0s.

Examples:

Input :  arr[] = {0, 1, 0, 0, 1, 1, 0}
Output : 6
We can get 6 zeros by flipping the sub-array {1, 1}

Input :  arr[] = {0, 0, 0, 1, 0, 1}
Output : 5

The idea is very simple just count the original zero and find the largest sum in the sub-array.
i would provide a solution for it which will work in o(n) complexity.

Solution:

/**
 * @author Abhinaw.Tripathi
 *
 */
public class FlipZeroApp
{
public static void main(String[] args)
{
//int[] arr={0, 1, 0, 0, 1, 1, 0};  output should 6
int[] arr={0, 0, 0, 1, 0, 1};   // here output should be 5
int size=arr.length;
int count=findMaxZeroCount(arr, size);
System.out.println(count);
}
public static int findMaxZeroCount(int arr[], int n)
{
   int orig_zero_count = 0;
   int max_diff = 0;
   int curr_max = 0;

   for (int i=0; i<n; i++)
   {
       if (arr[i] ==0)
          orig_zero_count++;
       // Value to be considered for finding maximum sum
       int val = (arr[i] ==1)? 1 : -1;

       // Update current max and max_diff
       curr_max = Math.max(val, curr_max + val);
       max_diff = Math.max(max_diff, curr_max);
   }
   max_diff = Math.max(0, max_diff);

   return orig_zero_count + max_diff;
}


}

Complexity= o(n) where as any other solution would work in o(n^2).

Output: 5

Non Fibonacci Numbers in Java

Given a positive integer n, the task is to print the n'th non Fibonacci number. The Fibonacci numbers are defined as:

Fib(0) = 0
Fib(1) = 1
for n >1, Fib(n) = Fib(n-1) + Fib(n-2)

First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141,....

Examples:

Input : n = 2
Output : 6

Input : n = 5
Output : 10

There are basically two solutions for it,

Naive Approach: First Approach is to find find Fibonacci numbers and then print first n numbers not present in the found Fibonacci numbers.

Better Solution: A better solution is to use the formula of Fibonacci numbers and keep adding of gap between two consecutive Fibonacci numbers. Value of sum of gap is count of non-Fibonacci numbers seen so far.

Solution:

/**
 * @author Abhinaw.Tripathi
 *
 */
public class FibonaciNumber
{
public static int nonFibonaciNumber(int n)
{
int prevprev=1,prev=2,current=3;

while(n>0)
{
prevprev=prev;
prev=current;
current=prevprev + prev;
n=n-(current-prev-1); //it can be negative
}
n=n+(current-prev-1); //make it positive

return prev+n;
}

public static void main(String[] args)
{
int count=nonFibonaciNumber(5);
System.out.println(count);
}

}

Output: 10

Tuesday, September 13, 2016

Android TV App Building Concept

Building TV Apps

Android offers a rich user experience that's optimized for apps running on large screen devices, such as high-definition televisions. Apps on TV offer new opportunities to delight your users from the comfort of their couch.


  • TV apps use the same structure as those for phones and tablets.
  • This approach means you can create new TV apps based on what you already know about building apps for Android, or extend your existing apps to also run on TV devices. 
  • However, the user interaction model for TV is substantially different from phone and tablet devices. In order to make your app successful on TV devices, you must design new layouts that can be easily understood from 10 feet away, and provide navigation that works with just a directional pad and a select button.

There are few points you can note while TV app development such as
  1. Handling TV Hardware
  2. Building TV Layouts
  3. Creating TV Navigation
Each of them plays a very vital role in Android Tv app development.Lets see how they
impact on the development but before that you must have understanding about few things
such as

1)Supported Media Formats
2)DRM
3)android.drm
4)ExoPlayer
5)android.media.MediaPlayer

And Android TV app uses lean back support.

1)Declare Leanback support for TV:

Declare that your app uses the Leanback user interface required by Android TV. If you are developing an app that runs on mobile (phones, wearables, tablets, etc.) as well as Android TV, set the required attribute value to false. If you set the required attribute value to true, your app will run only on devices that use the Leanback UI.

<manifest>
    <uses-feature android:name="android.software.leanback"
        android:required="false" />
</manifest>

So there are few things also which are not required at TV app development.

2)Declare touchscreen not required:

Applications that are intended to run on TV devices do not rely on touch screens for input. In order to make this clear, the manifest of your TV app must declare that a the android.hardware.touchscreen feature is not required. This setting identifies your app as being able to work on a TV device, and is required for your app to be considered a TV app in Google Play. The following code example shows how to include this manifest declaration:

<manifest>
    <uses-feature android:name="android.hardware.touchscreen"
              android:required="false" />
</manifest>

3)Provide a home screen banner:

An application must provide a home screen banner image for each localization if it includes a Leanback launcher intent filter. The banner is the app launch point that appears on the home screen in the apps and games rows. When designing your banner, follow the design requirements described in Banners. To add the banner to your app, describe the banner in the manifest as follows:

<application
    android:banner="@drawable/banner" >
</application>

4)Add TV Support Libraries:

The Android SDK includes support libraries that are intended for use with TV apps. These libraries provide APIs and user interface widgets for use on TV devices. The libraries are located in the <sdk>/extras/android/support/ directory. Here is a list of the libraries and their general purpose:

a)v17 leanback library - Provides user interface widgets for TV apps, particularly for apps that do media playback.

b)v7 recyclerview library - Provides classes for managing display of long lists in a memory efficient manner. Several classes in the v17 leanback library depend on the classes in this library.

c)v7 cardview library - Provides user interface widgets for displaying information cards, such as media item pictures and descriptions.
Note: You are not required to use these support libraries for your TV app. However, we strongly recommend using them, particularly for apps that provide a media catalog browsing interface.

If you decide to use the v17 leanback library for your app, you should note that it is dependent on the v4 support library. This means that apps that use the leanback support library should include all of these support libraries:

v4 support library
v7 recyclerview support library
v17 leanback support library
The v17 leanback library contains resources, which require you to take specific steps to include it in app projects. For instructions on importing a support library with resources, see Support Library Setup.


5)Declaring hardware requirements for TV:

<uses-feature android:name="android.hardware.touchscreen"
        android:required="false"/>
<uses-feature android:name="android.hardware.faketouch"
        android:required="false"/>
<uses-feature android:name="android.hardware.telephony"
        android:required="false"/>
<uses-feature android:name="android.hardware.camera"
        android:required="false"/>
<uses-feature android:name="android.hardware.nfc"
        android:required="false"/>
<uses-feature android:name="android.hardware.location.gps"
        android:required="false"/>
<uses-feature android:name="android.hardware.microphone"
        android:required="false"/>
<uses-feature android:name="android.hardware.sensor"
        android:required="false"/>

Android apps can declare hardware feature requirements in the app manifest to ensure that they do not get installed on devices that do not provide those features. If you are extending an existing app for use on TV, closely review your app's manifest for any hardware requirement declarations that might prevent it from being installed on a TV device.

If your app uses hardware features (such as a touchscreen or camera) that are not available on TV, but can operate without the use of those features, modify your app's manifest to indicate that these features are not required by your app. The following manifest code snippet demonstrates how to declare that your app does not require hardware features which are unavailable on TV devices.

So, These are few things which are basic requirement for Android TV App Development and must
be taken care while Android TV app Development. Now,So if we can not use touch screen and so how we will navigate within the Application.Will tell you in next tutorial.



Monday, September 12, 2016

Android Request Run-Time Permission Example

Although Android is being keep developed but the latest update to Android M is totally different since there is some major change that would change everything like new Run-time Permission. Surprisingly it is not much talked about in Android Developer community even though it is extremely important and may cause some big trouble in the near future.

The New Runtime Permission
Android's permission system is one of the biggest security concern all along since those permissions are asked for at install time. Once installed, the application will be able to access all of things granted without any user's acknowledgement what exactly application does with the permission.

No surprise why there are so many bad guys trying to collect user's personal data through this security weakness and use it in the bad way.

Android team also know this concern. 7 year passed, finally permission system is redesigned. In Android 6.0 Marshmallow, application will not be granted any permission at installation time. Instead, application has to ask user for a permission one-by-one at runtime.

Note: Please note that permission request dialog shown above will not launch automatically. Developer has to call for it manually. In the case that developer try to call some function that requires a permission which user has not granted yet, the function will suddenly throw an Exception which will lead to the application crashing.

What happened to the application that has already been launched?
This new permission system may cause you some panic right now. "Hey ! What's about my application that launched 3 years ago. If it is installed on Android 6.0 device, does this behavior also applied? Will my application also crash?!?"

Don't worry. Android team has already thought about it. If the application's targetSdkVersion is set to less than 23. It will be assumed that application is not tested with new permission system yet and will switch to the same old behavior: user has to accept every single permission at install time and they will be all granted once installed !

As a result, application will run perfectly like previous. Anyway please note that user still can revoke a permission after that ! Although Android 6.0 warn the user when they try to do that but they can revoke anyway.

Very Simple Code Solution:

Manifest.xml: 


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.myandrioid.abhinaw">
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <application 
       android:allowBackup="true" 
       android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name" 
       android:supportsRtl="true"  
      android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>



MainActivity.java :

package com.myandrioid.abhinaw;
import android.Manifest;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity
{
    private Button buttonRequestPermission;
    private int STORAGE_PERMISSION_CODE = 23;

    @Override    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requestPermisssion();
    }

    private  void requestPermisssion()
    {
        buttonRequestPermission = (Button) findViewById(R.id.buttonRequestPermission);
        buttonRequestPermission.setOnClickListener(new View.OnClickListener()
        {
            @Override            public void onClick(View v)
            {
                if(isReadStorageAllowed())
                {
                    Toast.makeText(MainActivity.this,"You already have the permission",Toast.LENGTH_LONG).show();
                    return;
                }
                requestStoragePermission();
            }
        });
    }

    private boolean isReadStorageAllowed()
    {
        int result = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
        if (result == PackageManager.PERMISSION_GRANTED)
            return true;
        return false;
    }

    private void requestStoragePermission()
    {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.READ_EXTERNAL_STORAGE))
        {
           // do nothing
        }
        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},STORAGE_PERMISSION_CODE);
    }

    @Override    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
    {
        if(requestCode == STORAGE_PERMISSION_CODE)
        {
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                Toast.makeText(this,"Permission granted now you can read the storage",Toast.LENGTH_LONG).show();
            }
            else            {
                Toast.makeText(this,"Oops you just denied the permission",Toast.LENGTH_LONG).show();
            }
        }
    }
}

activity_main.xml :

<Button  
  android:layout_width="match_parent" 
   android:layout_height="wrap_content" 
   android:text="Request Storage Permission"  
  android:id="@+id/buttonRequestPermission"  
  android:layout_centerVertical="true"  
  android:layout_below="@+id/button" />

Result: 







Nagarro Coding Questions for Experienced Interview Android

1)Given an unsorted list of repeated elements in an array, Find the element with maximum frequency.
Solution:

There are two approaches for this:
1)Naive Approach: Need two loop,outer-inner and outer loop will pick element and will traverse and inner loop will just count the duplicate.

Time Complexity: o(n^2)

2)Better Approach: 

Time Complexity: o(n) and o(k) for space where k=size;
/*
 * @author Abhinaw.Tripathi
 *
 */
public class MaxRepeatingApp
 {
public static void main(String[] args)
{
int arr[] = {2, 3, 3, 5, 3, 4, 1, 7};
                int n = arr.length;
                int k=8;
                System.out.println("Maximum repeating element is: " +maxRepeating(arr,n,k));
}
public static int maxRepeating(int[] arr,int n,int k)
{
for(int i=0;i<n;i++)
arr[(arr[i])%k] +=k;

int max=arr[0],result=0;
for(int i=0;i<n;i++)
{
if(arr[i] > max)
{
max=arr[i];
result=i;
}
}
return result;
}
}
Result: Maximum repeating element is: 3

2) Given a string containing characters and brackets, find if the brackets are paired in the string.

Solution: 
public static boolean pairedNotpaired(String str)
{
Stack stack=new Stack();
boolean result=true;
for(int i=0;i<str.length();i++)
{
char c=str.charAt(i);
switch (c) 
{
 case ')':
 if((Character)stack.pop()!=null)
 {
 return false;
 }
 
 case '}':
 
 if((Character)stack.pop()!=null)
 {
 return false;
 }
 
break;
 case ']' :
 {
 if((Character)stack.pop()!=null)
 {
 return false;
 }
 }

default:
stack.push(c);
break;
}
}
return result;

}


3) Given a set of integers, find the third maximum sum of two elements from the set.
Solution:
/**
 * @author Abhinaw.Tripathi
 *
 */
public class ThirdlargestSumApp {

public static int swap(int a, int b)
{
return a;
}
public static void main (String[] args) throws java.lang.Exception
{
   int k = 3;                            //Finding kth largest pair sum in array "a".
   int []a = {-2, 3, 4, -1, 5, 7, 8};   //input array
   int []b = new int[k]; //Holds the calculated pair sum. Not more than k highest pair-sum arerequired at any moment.  
   
   for(int i = 0; i < k; i++) 
    b[i] = Integer.MIN_VALUE;
   
   for(int i = 0; i < a.length-1; i++)
   {
       int pair = a[i] + a[i+1];
       if(pair > b[0]) 
       {                                //Compare with the Min Value i.e. b[0].
           b[0] = pair;
           System.out.println("All Sum:" +b[0]);                                                      
           if(b[1] < b[0]) 
           {
               b[1] = swap(b[0], b[0]=b[1]); // To satisfy parent(b[0]) <= left_child(b[1]) constraint for MinHeap
           }
           if(b[2] < b[0])
           {
               b[2] = swap(b[0], b[0]=b[2]); // To satisfy parent(b[0]) <= right_child(b[1]) constraint for MinHeap
           }
       }
   }
   System.out.println( "\n" +"3rd Sum:" +b[0]);
}
}

4)Find middle element efficiently of a Circular Linked List.
Solution:

class LinkedList
{
Node head; 
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}

void printMiddle()
{
Node slow_ptr = head;
Node fast_ptr = head;
if (head != null)
{
while (fast_ptr != null && fast_ptr.next != null)
{
fast_ptr = fast_ptr.next.next;
slow_ptr = slow_ptr.next;
}
System.out.println("The middle element is [" +
slow_ptr.data + "] \n");
}
}

public void push(int new_data)
{
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}

public void printList()
{
Node tnode = head;
while (tnode != null)
{
System.out.print(tnode.data+"->");
tnode = tnode.next;
}
System.out.println("NULL");
}

public static void main(String [] args)
{
LinkedList llist = new LinkedList();
for (int i=5; i>0; --i)
{
llist.push(i);
llist.printList();
llist.printMiddle();
}
}
}

5) Given a string ,find the longest sub-string with all distinct characters in it.If there are multiple such strings,print them all.

Solution:
/**
 * 
 */

/**
 * @author Abhinaw.Tripathi
 *
 */
import java.util.*;
 
public class UniqueSubStringApp
{ 
  static boolean isValid(int count[],int k)
   {
int val = 0;
    for (int i=0; i<26; i++)
        if (count[i] > 0)
            val++;
 
    return (k >= val);
   }
static int uniquesubstring(String s,int k)
{
int u=0;
int max=0,max_start=0;
int cur_start=0;
int cur_end=0;
int n=s.length();
int count[]=new int[27];
Arrays.fill(count,0);
for(int i=0;i<n;i++)
{
if(count[s.charAt(i)-'a']==0)
{
u++;
}
count[s.charAt(i)-'a']++;
}
if(u<k)
{
System.out.printf("k is greater than no of characters");
return 0;
}
Arrays.fill(count,0);
count[s.charAt(0)-'a']++;
for(int i=1;i<n;i++)
{
count[s.charAt(i)-'a']++;
cur_end++;
while(!isValid(count,k))
{
count[s.charAt(cur_start)-'a']--;
cur_start++;
}
 
if(cur_end-cur_start+1>max)
{
max=cur_end-cur_start+1;
max_start=cur_start;
}
 
}
 
System.out.println("Max substring "+s.substring(max_start,cur_end+1));
System.out.println("length "+max);
return 0;
}
public static void main (String[] args) throws java.lang.Exception
{
String s="aabacbebebe";
int k=3;
uniquesubstring(s,3);
}
}

Friday, September 9, 2016

Android Content Provider Tutorial


A content provider manages a shared set of app data. You can store the data in the file system, an SQLite database, on the web, or any other persistent storage location your app can access. Through the content provider, other apps can query or even modify the data (if the content provider allows it).

For example, the Android system provides a content provider that manages the user's contact information. As such, any app with the proper permissions can query part of the content provider (such as ContactsContract.Data) to read and write information about a particular person.

A content provider component supplies data from one application to others on request. Such requests are handled by the methods of the ContentResolver class. A content provider can use different ways to store its data and the data can be stored in a database, in files, or even over a network.
sometimes it is required to share data across applications. This is where content providers become very useful.

Content providers let you centralize content in one place and have many different applications access it as needed. A content provider behaves very much like a database where you can query it, edit its content, as well as add or delete content using insert(), update(), delete(), and query() methods. In most cases this data is stored in an SQlite database.





A content provider is implemented as a subclass of ContentProvider class and must implement a standard set of APIs that enable other applications to perform transactions.

How to Create Content Provider:

This involves number of simple steps to create your own content provider.
First of all you need to create a Content Provider class that extends the ContentProviderbaseclass.
Second, you need to define your content provider URI address which will be used to access the content.

Next you will need to create your own database to keep the content. Usually, Android uses SQLite database and framework needs to override onCreate() method which will use SQLite Open Helper method to create or open the provider's database. When your application is launched, the onCreate() handler of each of its Content Providers is called on the main application thread.

Next you will have to implement Content Provider queries to perform different database specific operations.

Finally register your Content Provider in your activity file using <provider> tag.

CONTENT PROVIDER Call Backs:

onCreate() This method is called when the provider is started.

query() This method receives a request from a client. The result is returned as a Cursor object.

insert()This method inserts a new record into the content provider.

delete() This method deletes an existing record from the content provider.

update() This method updates an existing record from the content provider.

getType() This method returns the MIME type of the data at the given URI.


Let me provide a simple application where you can add records and retrieve records.

MainActivity.java :

import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast; 
 
public class MainActivity extends AppCompatActivity


@Override protected void onCreate(Bundle savedInstanceState) {
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}


public void onClickAddName(View view) {
ContentValues values = new ContentValues();

values.put(StudentsProvider.NAME, ((EditText)findViewById(R.id.editText2)).getText().toString());
values.put(StudentsProvider.GRADE, ((EditText)findViewById(R.id.editText3)).getText().toString());

Uri uri = getContentResolver().insert(StudentsProvider.CONTENT_URI, values);
Toast.makeText(getBaseContext(), uri.toString(), Toast.LENGTH_LONG).show(); }

public void onClickRetrieveStudents(View view) {

// Retrieve student records String URL = "content://com.myandrioid.provider.College/students";
Uri students = Uri.parse(URL);
Cursor c = managedQuery(students, null, null, null, "name");
if (c.moveToFirst()) {
do {
Toast.makeText(this,
c.getString(c.getColumnIndex(StudentsProvider._ID)) +

", " + c.getString(c.getColumnIndex( StudentsProvider.NAME)) +

", " + c.getString(c.getColumnIndex( StudentsProvider.GRADE)),

Toast.LENGTH_SHORT).show();

}
while (c.moveToNext());

} }

}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"


xmlns:tools="http://schemas.android.com/tools"


android:layout_width="match_parent"


android:layout_height="match_parent"


android: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="com.myandrioid.abhinaw.MainActivity">



<TextView


android:id="@+id/textView1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Content provider"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true"

android:textSize="30dp" />


<TextView

android:id="@+id/textView2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Abhinaw Tutorial "

android:textColor="#ff87ff09"

android:textSize="30dp"

android:layout_below="@+id/textView1"

android:layout_centerHorizontal="true" />


<ImageButton

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageButton"

android:src="@mipmap/ic_launcher"

android:layout_below="@+id/textView2"

android:layout_centerHorizontal="true" />


<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/button2"

android:text="Add Name"

android:layout_below="@+id/editText3"

android:layout_alignRight="@+id/textView2"

android:layout_alignEnd="@+id/textView2"

android:layout_alignLeft="@+id/textView2"

android:layout_alignStart="@+id/textView2"

android:onClick="onClickAddName"/>


<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText"

android:layout_below="@+id/imageButton"

android:layout_alignRight="@+id/imageButton"

android:layout_alignEnd="@+id/imageButton" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText2"

android:layout_alignTop="@+id/editText"

android:layout_alignLeft="@+id/textView1"

android:layout_alignStart="@+id/textView1"

android:layout_alignRight="@+id/textView1"

android:layout_alignEnd="@+id/textView1"

android:hint="Name"

android:textColorHint="@android:color/holo_blue_light" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText3"

android:layout_below="@+id/editText"

android:layout_alignLeft="@+id/editText2"

android:layout_alignStart="@+id/editText2"

android:layout_alignRight="@+id/editText2"

android:layout_alignEnd="@+id/editText2"

android:hint="Grade"

android:textColorHint="@android:color/holo_blue_bright" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Retrive student"

android:id="@+id/button"

android:layout_below="@+id/button2"

android:layout_alignRight="@+id/editText3"

android:layout_alignEnd="@+id/editText3"

android:layout_alignLeft="@+id/button2"

android:layout_alignStart="@+id/button2"

android:onClick="onClickRetrieveStudents"/>

</RelativeLayout>

StudentsProvider.java :


import java.util.HashMap;

import android.content.ContentProvider;

import android.content.ContentUris;

import android.content.ContentValues;

import android.content.Context;

import android.content.UriMatcher;

import android.database.Cursor;

import android.database.SQLException;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

import android.database.sqlite.SQLiteQueryBuilder;

import android.net.Uri;


import android.text.TextUtils;
public class StudentsProvider extends ContentProvider


static final String PROVIDER_NAME = "com.myandrioid.provider.College"; {
static final String URL = "content://" + PROVIDER_NAME + "/students";


static final Uri CONTENT_URI = Uri.parse(URL);


static final String _ID = "_id";


static final String NAME = "name";


static final String GRADE = "grade";


private static HashMap<String, String> STUDENTS_PROJECTION_MAP;


static final int STUDENTS = 1;


static final int STUDENT_ID = 2;


static final UriMatcher uriMatcher;


static {


uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);


uriMatcher.addURI(PROVIDER_NAME, "students", STUDENTS);


uriMatcher.addURI(PROVIDER_NAME, "students/#", STUDENT_ID);


}


/** * Database specific constant declarations */ private SQLiteDatabase db;


static final String DATABASE_NAME = "College";


static final String STUDENTS_TABLE_NAME = "students";


static final int DATABASE_VERSION = 1;


static final String CREATE_DB_TABLE =


" CREATE TABLE " + STUDENTS_TABLE_NAME +


" (_id INTEGER PRIMARY KEY AUTOINCREMENT, " +


" name TEXT NOT NULL, " +


" grade TEXT NOT NULL);";


/** * Helper class that actually creates and manages * the provider's underlying data repository. */ private static class DatabaseHelper extends SQLiteOpenHelper {


DatabaseHelper(Context context){


super(context, DATABASE_NAME, null, DATABASE_VERSION);


}


@Override public void onCreate(SQLiteDatabase db) {


db.execSQL(CREATE_DB_TABLE);


}


@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {


db.execSQL("DROP TABLE IF EXISTS " + STUDENTS_TABLE_NAME);


onCreate(db); } }


@Override public boolean onCreate() {


Context context = getContext();


DatabaseHelper dbHelper = new DatabaseHelper(context);


/** * Create a write able database which will trigger its * creation if it doesn't already exist. */ db = dbHelper.getWritableDatabase();


return (db == null)? false:true;


}


@Override public Uri insert(Uri uri, ContentValues values) {


/** * Add a new student record */ long rowID = db.insert( STUDENTS_TABLE_NAME, "", values);


/** * If record is added successfully */


if (rowID > 0)


{


Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);


getContext().getContentResolver().notifyChange(_uri, null);


return _uri;


}


throw new SQLException("Failed to add a record into " + uri); }


@Override public Cursor query(Uri uri, String[] projection, String selection,String[] selectionArgs, String sortOrder) {


SQLiteQueryBuilder qb = new SQLiteQueryBuilder();


qb.setTables(STUDENTS_TABLE_NAME);


switch (uriMatcher.match(uri)) {


case STUDENTS:


qb.setProjectionMap(STUDENTS_PROJECTION_MAP);


break;


case STUDENT_ID:


qb.appendWhere( _ID + "=" + uri.getPathSegments().get(1));


break;


default:


throw new IllegalArgumentException("Unknown URI " + uri);


}


if (sortOrder == null || sortOrder == "")


{


/** * By default sort on student names */ sortOrder = NAME;


}


Cursor c = qb.query(db, projection, selection, selectionArgs,null, null, sortOrder);


/** * register to watch a content URI for changes */ c.setNotificationUri(getContext().getContentResolver(), uri);


return c;


}


@Override public int delete(Uri uri, String selection, String[] selectionArgs) {


int count = 0;


switch (uriMatcher.match(uri)) {


case STUDENTS:


count = db.delete(STUDENTS_TABLE_NAME, selection, selectionArgs);


break;


case STUDENT_ID:


String id = uri.getPathSegments().get(1);


count = db.delete( STUDENTS_TABLE_NAME, _ID + " = " + id +


(!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);


break;


default:


throw new IllegalArgumentException("Unknown URI " + uri);


}


getContext().getContentResolver().notifyChange(uri, null);


return count; }


@Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {


int count = 0;


switch (uriMatcher.match(uri)){


case STUDENTS:


count = db.update(STUDENTS_TABLE_NAME, values, selection, selectionArgs);


break;


case STUDENT_ID:


count = db.update(STUDENTS_TABLE_NAME, values, _ID + " = " + uri.getPathSegments().get(1) +


(!TextUtils.isEmpty(selection) ? " AND (" +selection + ')' : ""), selectionArgs);


break;


default:


throw new IllegalArgumentException("Unknown URI " + uri );


}


getContext().getContentResolver().notifyChange(uri, null);


return count; }


@Override public String getType(Uri uri) {


switch (uriMatcher.match(uri)) {


/** * Get all student records */


case STUDENTS:


return "vnd.android.cursor.dir/vnd.example.students";


/** * Get a particular student */


case STUDENT_ID:


return "vnd.android.cursor.item/vnd.example.students";


default:


throw new IllegalArgumentException("Unsupported URI: " + uri);


} }


}


manifests.xml :

<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.myandrioid.abhinaw">

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:supportsRtl="true"

android:theme="@style/AppTheme">

<activity android:name=".MainActivity">

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

<provider android:authorities="com.myandrioid.provider.College"

android:name=".StudentsProvider">

</provider>

</application>

</manifest>

Run and compile the code and you can able to perform the operation like add and retrieve
using content-provider and sqlite database.
So conclusion is,
Content providers are one of the primary building blocks of Android applications,
providing content to applications. They encapsulate data and provide it to applications
through the single ContentResolver interface. A content provider is only required if you
need to share data between multiple applications.