CONTENT PROVIDER

A content provider component supplies data from one application to others on request.Such requests are handled by the methods of the ContentResolver class.

cparch

Content Provider

  • Content Provider contains 6 methods : onCreate, insert, delete, update, query, getType.
  • SQLiteOpenHelper is a class that manages DB creation and version management.
  • SQLiteDatabase has methods to create, delete, execute SQL commands.
  • onCreate of Content Provider is called when App is first installed. In this method, SQLiteOpenHelper is created, which further creates  our database and SQLiteDatabase.
  • Data is stored in the form of key value pair in object known as ContentValues .
  • Requests for data retrieval are handled by ContentResolver.It contains 4 methods : insert, delete, update, query.
  • When data has to be inserted into table in DB, ContentValues are passed along with URI of Content Provider by ContentReolver to Content Provider. Content Provider further requests SQLiteDatabase to insert the data in particular table. Then, its work of SQLiteDatabase to insert the data in required table .

 

BROADCAST RECEIVER

Broadcast Receivers simply respond to broadcast messages from other applications or from the system itself.  It receives Action. Action can be –

  • User defined /created by developer /Broadcasted by developer
  • System defined /pre-defined /Broadcasted by android system

Example :

In this example, there is a Receiver (Receiver.java) which receives broadcast actions which are defined in its Intent filter . Actions  defined in Intent filter on BroadcastReceiver can be any ; it may be user defined or system defined. In the given example, there is an action named “action1“. When this action is triggered, Receiver.class will receive the broadcast message and notification is displayed.

In AndroidManifest.xml , intent filter of Receiver.java is as under:


<receiver android:name=".Receiver" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="action1" />
</intent-filter>
</receiver>

MainActivity.java whose title is “Receiver”


//Here in this activity ,there's a button ,by clicking on that "action1" is triggered and Receiver will receive broadcast message.

public void onClick(View v){
Intent i=new Intent("action1");
sendBroadcast(i);
}

Receiver.java


public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {

String action=intent.getAction();

if(action.equals("action1")){
Toast.makeText(context,"Action1 is triggered",Toast.LENGTH_SHORT).show();

NotificationCompat.Builder builder=new NotificationCompat.Builder(context);
//ActivityDemo starts when "ADD" option in notification is clicked
Intent i=new Intent(context,ActivityDemo.class);
PendingIntent pi=PendingIntent.getActivity(context,1001,i,0);

//Call Intent - By clicking on "CALL" icon , keypad will open and the specified mobile number will be automatically written
Intent call=new Intent(Intent.ACTION_DIAL);
call.setData(Uri.parse("tel:924xxxxxxx"));
PendingIntent piCall=PendingIntent.getActivity(context,101,call,0);

builder.setContentIntent(pi);
builder.setDefaults(Notification.DEFAULT_ALL);
builder.setSmallIcon(R.drawable.music);
builder.setContentTitle("Title");
builder.setContentText("This is a notification.");

builder.setStyle(new NotificationCompat.BigTextStyle().bigText("This is a big text .This text gives complete information in multiple lines."));
builder.addAction(android.R.drawable.ic_menu_add, "Add", pi);
builder.addAction(android.R.drawable.ic_menu_call, "Call", piCall);

Notification notification=builder.build();

NotificationManager manager=(NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
manager.notify(100,notification);
}
}
}

mainactivity

MainActivity

notification

Notification

SERVICE

A service is a component that runs in the background without needing to interact with the user and it works even if application is destroyed.

Service can take  two states :

  • Start Service : Once started, a service can run in the background indefinitely, even if the component that started it is destroyed.
  • Bind Service : A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC).

For starting a service:

startService(new Intent(getBaseContext(), MyService.class));

For stopping a service :

stopService(new Intent(getBaseContext(), MyService.class));

Example :

When service  is started, MediaPlayer is started and selected song is played. When service is destroyed, MediaPlayer is stopped and all the resources are released. 
MyService.java

public class MyService extends Service {

    MediaPlayer player;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        player = new MediaPlayer();
        String songName = intent.getStringExtra("keySong");
        String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+songName;

        try{
            player.setDataSource(path);
            player.prepare();
            player.start();   //player started
        }catch (Exception e){

        }
	 return super.onStartCommand(intent,flags,startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
       
        player.stop();
        player.release();
    }

    @Override
    public IBinder onBind(Intent intent) {
	 return null;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }
}

READING EXTERNAL STORAGE

For reading or writing external storage, add permissions in Manifest file

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

This code firstly initialize the path . Then it displays al the image files(.jpg) in listView by storing the objects in an ArrayList(listOfContents). Object(SdObjects) contains the information about images present in external memory.


{//initialize path
String path= Environment.getExternalStorageDirectory().getAbsolutePath();
initList(path);
}

    void initList(String path){
        try {
            File file = new File(path);
            File[] filesArray=file.listFiles();
            String fileName;
            int icon=R.drawable.img;
            for(File file1:filesArray) {
                if (file1.isDirectory()) {
                    initList(file1.getAbsolutePath());
                } else {
                        fileName=file1.getName();
                        if ((fileName.endsWith(".jpg"))
                     		listOfContents.add(new SdObjects(icon,    file1.getName(), file1.getAbsolutePath()));
                        }

                }
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

filemanager

LIST VIEW IN ANDROID

adapter

  • Data to be inserted is first stored in object.
  • ArrayList stores references of those objects in indexed approach from 0 to (n-1).
  • Adapter contains processing  API called getView().
  • Adapter needs three arguments : Reference of Activity, Reference of list_item, Reference of data structure eg. ArrayList.
  • getView() takes the object one by one, binds the data to the list_item and also list_item to list view.

Example :

In NewsAggregator.java ,  populate arraylist with objects and  set adapter on ListView as :


listView=(ListView)findViewById(R.id.listview);
list=new ArrayList<>();

//Adding object references to ArrayList
list.add(new NewsObjects(R.drawable.tribune,"English","The Tribune","http://www.tribuneindia.com/mobi/"));
list.add(new NewsObjects(R.drawable.dainikbhaskar,"Hindi","Dainik Bhaskar","http://m.bhaskar.com"));
list.add(new NewsObjects(R.drawable.kerelaexpress,"Malayalam","Kerala Express","http://www.keralax.com"));
list.add(new NewsObjects(R.drawable.lokmatmarathi,"Marathi","Lokmat","http://www.lokmat.com"));

//Rest of the objects

adapter=new NewsAdapter(NewsAggregator.this,R.layout.list_item,list); //Initializing Adapter
listView.setAdapter(adapter); //Setting adapter on List View

NewsObjects.java


public class NewsObjects {
int icon;
String language,newspaper,url;

public NewsObjects(int icon, String language, String newspaper, String url) {
this.icon = icon;
this.language = language;
this.newspaper = newspaper;
this.url = url;
}
//getters and setters
}

NewsAdapter.java


//constructor here

//getView()

public View getView(int position, View convertView, ViewGroup parent) {
View item;

item= LayoutInflater.from(cxt).inflate(res,parent,false);
ImageView icon=(ImageView)item.findViewById(R.id.imageViewIcon);
TextView language=(TextView)item.findViewById(R.id.textViewlanguage);
TextView newspaper=(TextView)item.findViewById(R.id.textViewNewspaper);

NewsObjects ob=list.get(position);
icon.setBackgroundResource(ob.getIcon());
language.setText(ob.getLanguage());
newspaper.setText(ob.getNewspaper());

return item;

}

newsaggregator

BACKWARD PASSING OF INTENT

ActivityOne invokes ActivityTwo for result  ,let say on the click of button.

Code for ActivityOne goes as :


//Previous code

public void onClick(View v)   {     //onClick of a button ActivityTwo is started
Intent i = new Intent(ActivityOne.this,ActivityTwo.class);
startActivityForResult(i,100);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {    //This method runs when data is passed from ActivityTwo to ActivityOne
if(requestCode ==100 &&  resultCode==101){
String data = data.getStringExtra("keyData");
}

//Rest of the code
}

Now, ActivityTwo has to send data to ActivityOne when a particular event occurs , let say on Click of button.

Code of ActivityTwo goes as :


//Previous code

public void onClick(View v) {          //Intent is passed to first Activity when button is clicked
Intent data = new Intent();
data.putExtra("keyData","data string");
setResult(101,data);     // -> invokes onActivityResult of that Activity which started it
finish();
}

//Rest of the code

VIEWS IN ANDROID

WEBVIEW:

WebView is a view that can dynamically load web pages.For using webview , Go to Manifest file and add user-permission of internet as follows :


<user-permission android:name ="android.permission.INTERNET">

Example: One Activity passes the url and name of a newspaper’s website . The below given activity gets intent and WebView is initialized.


Intent data=getIntent();
String url=data.getStringExtra("keyUrl");
String newspaper=data.getStringExtra("keyNewspaper");

setTitle(newspaper);
webView.getSettings().setJavaScriptEnabled(true);

WebViewClient client=new WebViewClient();
webView.setWebViewClient(client);

webView.loadUrl(url);

CHECKBOX :

For including checkboxes in android, the class should implement OnCheckedChangedListener.  


public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int id = buttonView.getId();

switch (id){
case R.id.checkBoxOne:
//stuff for checkbox One
break;

case R.id.checkBoxTwo:
//stuff for checkbox Two
break;
}
}

RadioButton :

Implements CompundButton.onCheckedChangedListener


&nbsp;

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int id = buttonView.getId();

switch (id){

case R.id.male :

//Code for male

case .id.female :

//Code for female

}

}

Rating Bar :

Implements onRatingChangedListener.


public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
Toast.makeText(this,"Rating: "+rating,Toast.LENGTH_LONG).show();
}

Spinner :

Touching the spinner displays a dropdown menu with all other available values.Data to be shown is fed to adapter which does the binding of data to the listview.

AutoCompleteTextView :

It shows a list of completion suggestions automatically while the user is typing.

LAYOUT

View groups are Layouts.

  • Linear Layout :This layout aligns all the views in it either horizontally or vertically.

android: orientation = “horizontal” set the layout orientation to horizontal . All the views will be added horizontally.

  • Relative Layout : Displays all the child views in relative positions.
  • Table Layout : Groups views into rows and columns.

<TableRow>

//add the views

</TableRow>

  • Framelayout : Mainy used to display single view . Overlapping can be produced. Limit of framelayout is 9 views divided into particular regions.

CARDVIEW

Cardview puts the view in card. This gives embossed look to the view.

For using cardview in xml file , add the library dependencies for cardview.

CardView containsonly one child.

 

MENU

Functions for adding menu

  • onCreateOptionsMenu(Menu menu)
  • onOptionsItemSelected(MenuItem item)

Explicit way

In onCreateOptionsMenu() , add the items as :

menu.add(GroupId,itemId,order,name);

In onOptionsItemSelected() , write the following code :

int id= item.getItemId();
switch(id){

case 0:
//do the code here

case 1:
//do the code here
}

Implicit way

Create an xml file for menu. Add items in that menu resource file.

And in onCreateOptionsMenu(), write code as :


MenuInflator inflator = getMenuInflator();
inflator.inflate(R.menu.file , menu );

Inflating a view means taking the xml file and creating the actual objects so that they are actually visible on Activity screen.

INTENT

Intent is an object in android that contains data that allows various components of App to communicate.

intent

Intent can be passed by two methods :

1.Implicit Intent : This intent allows other app to open specific component from another app. This is achieved through intent filter. We specify action and category for that particular component which we want to be accessible by other apps installed in device.

2.Explicit Intent : Specify the component which has to be started. Used to invoke the component of the same App . eg.

Intent i=new Intent(ActivityOne.this, ActivityTwo.class);
i.putExtra("key",value);
startActivity(i);

Bundle : We can put data in Bundle and Bundle in Intent, and then pass data from one Activity to another.


Intent i=new Intent(ActivityOne.this , ActivityTwo.class);
Bundle b=new Bundle();
b.putString("key" , "data");
i.putExtra("keyBundle",b);