Professional Documents
Culture Documents
1. Started
2. Bound
1) Started Service
2) Bound Service
A service is bound when another component (e.g. client) calls bindService() method.
The client can unbind the service by calling the unbindService() method.
The service cannot be stopped until all clients unbind the service.
Suppose, I want to play music in the background, so call startService() method. But I
want to get information of the current song being played, I will bind the service that
provides information about the current song.
Drag the 3 buttons from the pallete, now the activity_main.xml will look like this:
File: activity_main.xml
1. <?xml version="1.0" encoding="utf-8"?>
2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.androidservice.MainActivity">
8.
9.
10. <Button
11. android:id="@+id/buttonStart"
12. android:layout_width="wrap_content"
13. android:layout_height="wrap_content"
14. android:layout_alignParentTop="true"
15. android:layout_centerHorizontal="true"
16. android:layout_marginTop="74dp"
17. android:text="Start Service" />
18.
19. <Button
20. android:id="@+id/buttonStop"
21. android:layout_width="wrap_content"
22. android:layout_height="wrap_content"
23. android:layout_centerHorizontal="true"
24. android:layout_centerVertical="true"
25. android:text="Stop Service" />
26.
27. <Button
28. android:id="@+id/buttonNext"
29. android:layout_width="wrap_content"
30. android:layout_height="wrap_content"
31. android:layout_alignParentBottom="true"
32. android:layout_centerHorizontal="true"
33. android:layout_marginBottom="63dp"
34. android:text="Next Page" />
35. </RelativeLayout>
activity_next.xml
File: activity_next.xml
1. <?xml version="1.0" encoding="utf-8"?>
2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.androidservice.NextPage">
8.
9. <TextView
10. android:id="@+id/textView"
11. android:layout_width="wrap_content"
12. android:layout_height="wrap_content"
13. android:layout_marginEnd="8dp"
14. android:layout_marginStart="8dp"
15. android:layout_marginTop="200dp"
16. android:text="Next Page"
17. app:layout_constraintEnd_toEndOf="parent"
18. app:layout_constraintStart_toStartOf="parent"
19. app:layout_constraintTop_toTopOf="parent" />
20. </android.support.constraint.ConstraintLayout>
Service class
Now create the service implemenation class by inheriting the Service class and
overridding its callback methods.
1. File: MyService.java
2. package example.javatpoint.com.androidservice;
3.
4. import android.app.Service;
5. import android.content.Intent;
6. import android.media.MediaPlayer;
7. import android.os.IBinder;
8. import android.support.annotation.Nullable;
9. import android.widget.Toast;
10.
11. public class MyService extends Service {
12. MediaPlayer myPlayer;
13. @Nullable
14. @Override
15. public IBinder onBind(Intent intent) {
16. return null;
17. }
18. @Override
19. public void onCreate() {
20. Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
21.
22. myPlayer = MediaPlayer.create(this, R.raw.sun);
23. myPlayer.setLooping(false); // Set looping
24. }
25. @Override
26. public void onStart(Intent intent, int startid) {
27. Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
28. myPlayer.start();
29. }
30. @Override
31. public void onDestroy() {
32. Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
33. myPlayer.stop();
34. }
35. }
36.
File: NextPage.java
package example.javatpoint.com.androidservice;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class NextPage extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
}
}
File: AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="example.javatpoint.com.androidservice">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
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>
<activity android:name=".NextPage"></activity>
<service
android:name=".MyService"
android:enabled="true" />
</application>
</manifest>
Output:
1 MODE_APPEND
This will append the new preferences with the already existing preferences
2 MODE_ENABLE_WRITE_AHEAD_LOGGING
Database open flag. When it is set , it would enable write ahead logging by default
3 MODE_MULTI_PROCESS
This method will check for modification of preferences even if the
sharedpreference instance has already been loaded
4 MODE_PRIVATE
By setting this mode, the file can only be accessed using calling application
5 MODE_WORLD_READABLE
This mode allow other application to read the preferences
6 MODE_WORLD_WRITEABLE
This mode allow other application to write the preferences
1 apply()
It is an abstract method. It will commit your changes back from editor to the
sharedPreference object you are calling
2 clear()
It will remove all values from the editor
3 remove(String key)
It will remove the value whose key has been passed as a parameter
Example
This example demonstrates the use of the Shared Preferences. It display a screen
with some text fields, whose value are saved when the application is closed and
brought back when it is opened again.
To experiment with this example, you need to run this on an actual device on after
developing the application according to the steps below −
Steps Description
1 You will use Android studio to create an Android application under a package
com.example.sairamkrishna.myapplication.
4 Run the application and choose a running android device and install the
application on it and verify the results.
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
SharedPreferences sharedpreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);
b1=(Button)findViewById(R.id.button);
sharedpreferences = getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String n = ed1.getText().toString();
String ph = ed2.getText().toString();
String e = ed3.getText().toString();
SharedPreferences.Editor editor =
sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.commit();
Toast.makeText(MainActivity.this,"Thanks",Toast.LENGTH_LONG).show
();
}
});
}
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Shared Preference "
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="35dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/textView2"
android:layout_marginTop="67dp"
android:hint="Name"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:layout_below="@+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Pass" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText3"
android:layout_below="@+id/editText2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Email" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="@+id/button"
android:layout_below="@+id/editText3"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp" />
</RelativeLayout>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android
Mobile device with your computer. To run the app from Android studio, open one of
your project's activity files and click Run icon from the toolbar. Before starting
your application, Android studio will display following window to select an option
where you want to run your Android application.
Select your mobile device as an option and then check your mobile device which
will display following screen −
Now just put in some text in the field. Like i put some random name and other
information and click on save button.
Now when you press save button, the text will be saved in the shared preferences.
Now press back button and exit the application. Now open it again and you will see
all the text you have written back in your application.
Android - Internal Storage
Android provides many kinds of storage for applications to store their data. These
storage places are shared preferences, internal and external storage, SQLite
storage, and storage via network connection.
In this chapter we are going to look at the internal storage. Internal storage is the
storage of the private data on the device memory.
By default these files are private and are accessed by only your application and get
deleted , when user delete your application.
Writing file
In order to use internal storage to write some data in the file, call the
openFileOutput() method with the name of the file and the mode. The mode could
be private , public e.t.c. Its syntax is given below −
FileOutputStream fOut = openFileOutput("file name
here",MODE_WORLD_READABLE);
Reading file
In order to read from the file you just created , call the openFileInput() method with
the name of the file. It returns an instance of FileInputStream. Its syntax is given
below −
FileInputStream fin = openFileInput(file);
After that, you can call read method to read one character at a time from the file and
then you can print it. Its syntax is given below −
int c;
String temp="";
while( (c = fin.read()) != -1){
temp = temp + Character.toString((char)c);
}
Apart from the the methods of write and close, there are other methods provided by
the FileOutputStream class for better writing files. These methods are listed below
−
getChannel()
2 This method returns a write-only FileChannel that shares its position with this
stream
getFD()
3
This method returns the underlying file descriptor
Apart from the the methods of read and close, there are other methods provided by
the FileInputStream class for better reading files. These methods are listed below
−
getChannel()
2 This method returns a read-only FileChannel that shares its position with this
stream
getFD()
3
This method returns the underlying file descriptor
Example
Here is an example demonstrating the use of internal storage to store and read
files. It creates a basic storage application that allows you to read and write from
internal storage.
To experiment with this example, you can run this on an actual device or in an
emulator.
Steps Description
1 You will use Android Studio IDE to create an Android application under a package
com.example.sairamkrishna.myapplication.
4 Run the application and choose a running android device and install the
application on it and verify the results
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
String data;
private String file = "mydata";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);
b2=(Button)findViewById(R.id.button2);
ed1=(EditText)findViewById(R.id.editText);
tv=(TextView)findViewById(R.id.textView2);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
data=ed1.getText().toString();
try {
FileOutputStream fOut =
openFileOutput(file,MODE_WORLD_READABLE);
fOut.write(data.getBytes());
fOut.close();
Toast.makeText(getBaseContext(),"file
saved",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
FileInputStream fin = openFileInput(file);
int c;
String temp="";
while( (c = fin.read()) != -1){
temp = temp + Character.toString((char)c);
}
tv.setText(temp);
Toast.makeText(getBaseContext(),"file
read",Toast.LENGTH_SHORT).show();
}
catch(Exception e){
}
}
});
}
}
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="@+id/button"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/textView"
android:layout_alignStart="@+id/textView" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:hint="Enter Text"
android:focusable="true"
android:textColorHighlight="#ff7eff15"
android:textColorHint="#ffff25e6"
android:layout_below="@+id/imageView"
android:layout_alignRight="@+id/textView"
android:layout_alignEnd="@+id/textView"
android:layout_marginTop="42dp"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="load"
android:id="@+id/button2"
android:layout_alignTop="@+id/button"
android:layout_alignRight="@+id/editText"
android:layout_alignEnd="@+id/editText" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Read"
android:id="@+id/textView2"
android:layout_below="@+id/editText"
android:layout_toLeftOf="@+id/button2"
android:layout_toStartOf="@+id/button2"
android:textColor="#ff5bff1f"
android:textSize="25dp" />
</RelativeLayout>
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run our Storage application we just modified. I assume you had created
your AVD while doing environment setup. To run the app from Android studio, open
one of your project's activity files and click Run icon from the tool bar. Android
studio installs the app on your AVD and starts it and if everything is fine with your
set-up and application, it will display following Emulator window −
Now what you need to do is to enter any text in the field. For example , i have
entered some text. Press the save button. The following notification would appear in
you AVD −
Now when you press the load button, the application will read the file , and display
the data. In case of our, following data would be returned −
Note you can actually view this file by switching to DDMS tab. In DDMS , select file
explorer and navigate this path.
tools>android>android device Monitor
This has also been shown in the image below.
Android External Storage
Like internal storage, we are able to save or read data from the device external
memory such as sdcard. The FileInputStream and FileOutputStream classes are used
to read and write data into the file.
Drag the 2 edittexts, 2 textviews and 2 buttons from the pallete, now the
activity_main.xml file will like this:
File: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.javatpoint.com.externalstorage.MainActivity">
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="20dp"
android:layout_marginTop="24dp"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginTop="24dp"
android:ems="10" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText1"
android:layout_alignBottom="@+id/editText1"
android:layout_alignParentLeft="true"
android:text="File Name:" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText2"
android:layout_alignBottom="@+id/editText2"
android:layout_alignParentLeft="true"
android:text="Data:" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText2"
android:layout_below="@+id/editText2"
android:layout_marginLeft="70dp"
android:layout_marginTop="16dp"
android:text="save" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button1"
android:layout_alignBottom="@+id/button1"
android:layout_toRightOf="@+id/button1"
android:text="read" />
</RelativeLayout>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
File: Activity_Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="example.javatpoint.com.externalstorage">
<uses-permission android:nam
e="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
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>
Activity class
Let's write the code to write and read data from the android external storage.
Skip Ad
File: MainActivity.java
package example.javatpoint.com.externalstorage;
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;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class MainActivity extends AppCompatActivity {
EditText editTextFileName,editTextData;
Button saveButton,readButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextFileName=findViewById(R.id.editText1);
editTextData=findViewById(R.id.editText2);
saveButton=findViewById(R.id.button1);
readButton=findViewById(R.id.button2);
//Performing action on save button
saveButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View arg0) {
String filename=editTextFileName.getText().toString();
String data=editTextData.getText().toString();
FileOutputStream fos;
try {
File myFile = new File("/sdcard/"+filename);
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.close();
Toast.makeText(getApplicationContext(),filename + "saved",Toast.LENGTH_LONG).sh
ow();
} catch (FileNotFoundException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
}
});
//Performing action on Read Button
readButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View arg0) {
String filename=editTextFileName.getText().toString();
StringBuffer stringBuffer = new StringBuffer();
String aDataRow = "";
String aBuffer = "";
try {
File myFile = new File("/sdcard/"+filename);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
myReader.close();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(),aBuffer,Toast.LENGTH_LONG).show();
}
});
}
}
Android - Content Providers
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.
ContentProvider
Content URIs
To query a content provider, you specify the query string in the form of a URI which
has following format −
<prefix>://<authority>/<data_type>/<id>
1 prefix
This is always set to content://
authority
data_type
3 This indicates the type of data that this particular provider provides. For example,
if you are getting all the contacts from the Contacts content provider, then the
data path would be people and URI would look like thiscontent://contacts/people
id
4 This specifies the specific record requested. For example, if you are looking for
contact number 5 in the Contacts content provider then URI would look like
this content://contacts/people/5.
Example
This example will explain you how to create your own ContentProvider. So let's
follow the following steps to similar to what we followed while creating Hello World
Example−
Step Description
1 You will use Android StudioIDE to create an Android application and name it as My
Application under a package com.example.MyApplication, with blank Activity.
7 Run the application to launch Android emulator and verify the result of the changes
done in the application.
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.database.Cursor;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClickAddName(View view) {
// Add a new student record
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());
Toast.makeText(getBaseContext(),
uri.toString(), Toast.LENGTH_LONG).show();
}
public void onClickRetrieveStudents(View view) {
// Retrieve student records
String URL =
"content://com.example.MyApplication.StudentsProvider";
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());
}
}
}
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;
/**
* Database specific constant declarations
*/
/**
* Helper class that actually creates and manages
* the provider's underlying data repository.
*/
@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;
}
switch (uriMatcher.match(uri)) {
case STUDENTS:
qb.setProjectionMap(STUDENTS_PROJECTION_MAP);
break;
case STUDENT_ID:
qb.appendWhere( _ID + "=" +
uri.getPathSegments().get(1));
break;
default:
}
@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);
}
}
}
<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:name="StudentsProvider"
android:authorities="com.example.MyApplication.StudentsProvider"/
>
</application>
</manifest>
<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="Tutorials point "
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="@drawable/abc"
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>
activity_main.xml
Add the following code in an activity_main.xml file.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/
apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.javatpoint.com.androidnotification.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ANDROID NOTIFICATION"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.091"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:layout_marginBottom="112dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:text="Notify"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</android.support.constraint.ConstraintLayout>
activity_notification_view.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/
apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.javatpoint.com.androidnotification.NotificationView">
<TextView
android:id="@+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="your detail of notification..."
android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.096"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView2"
app:layout_constraintVertical_bias="0.206"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"/>
</android.support.constraint.ConstraintLayout>
MainActivity.java
In the MainActivity.java class adds the following code. In this class, clicking the
button calls the addNotification() method where we implement the
NotificationCompat.Builder object to set the notification properties. The
NotificationManager.notify() method is used to display the notification. The Intent
class is used to call another activity (NotificationView.java) on taping the notification.
package example.javatpoint.com.androidnotification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addNotification();
}
});
}
private void addNotification() {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.messageicon) //set icon for notification
.setContentTitle("Notifications Example") //set title of notification
.setContentText("This is a notification message")//this is notification message
.setAutoCancel(true) // makes auto cancel of notification
.setPriority(NotificationCompat.PRIORITY_DEFAULT); //set priority of notification
Intent notificationIntent = new Intent(this, NotificationView.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//notification message will get at NotificationView
notificationIntent.putExtra("message", "This is a notification message");
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
// Add as notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFIC
ATION_SERVICE);
manager.notify(0, builder.build());
}
}
NotificationView.java
The NotificationView.java class receives the notification message and is displayed
in TextView. This class is invoked while taping the notification.
package example.javatpoint.com.androidnotification;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class NotificationView extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification_view);
textView = findViewById(R.id.textView);
//getting the notification message
String message=getIntent().getStringExtra("message");
textView.setText(message);
}
}
strings.xml
<resources>
<string name="app_name">AndroidNotification</string>
<string name="notification_activity">NotificationView</string>
</resources>
AndroidManifest.xml
Add the following code in AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="example.javatpoint.com.androidnotification">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
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>
<activity android:name=".NotificationView"
android:label="@string/notification_activity"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity"/>
</activity>
</application>
</manifest>
Output:
Playing Audio / Media Player
Android AlarmManager
Android AlarmManager allows you to access system alarm.
The Android AlarmManager holds a CPU wake lock that provides guarantee not to
sleep the phone until broadcast is handled.
activity_main.xml
File: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.javatpoint.com.alarmmanager.MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="103dp" />
<EditText
android:id="@+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:ems="10" />
</RelativeLayout>
Activity class
The activity class starts the alarm service when user clicks on the button.
File: MainActivity.java
package example.javatpoint.com.alarmmanager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
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 {
Button start;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start= findViewById(R.id.button);
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startAlert();
}
});
}
public void startAlert(){
EditText text = findViewById(R.id.time);
int i = Integer.parseInt(text.getText().toString());
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVIC
E);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ (i * 1000), pendingIntent);
Toast.makeText(this, "Alarm set in " + i + " seconds",Toast.LENGTH_LONG).show();
}
}
File: MyBroadcastReceiver.java
package example.javatpoint.com.alarmmanager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.widget.Toast;
public class MyBroadcastReceiver extends BroadcastReceiver {
MediaPlayer mp;
@Override
public void onReceive(Context context, Intent intent) {
mp=MediaPlayer.create(context, R.raw.alarm);
mp.start();
Toast.makeText(context, "Alarm....", Toast.LENGTH_LONG).show();
}
}
File: AndroidManifest.xml
<receiver android:name="MyBroadcastReceiver" >
</receiver>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="example.javatpoint.com.alarmmanager">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
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>
<receiver android:name="MyBroadcastReceiver" >
</receiver>
</application>
</manifest>
Output:
GalleryView in Android with Example
Last Updated : 13 Jul, 2021
In Android, Gallery is a view that can show items in a center locked, horizontal
scrolling list, and hence the user can able to select a view, and then the user selected
view will be shown in the center of the Horizontal list. “N” number of items can be
added by using the Adapter. The adapter is a bridging component between UI
component and data source(It can be an array of items defined in java code or from a
database). The items given in the adapter will be shown in the gallery in the example.
Important Point: Gallery class was deprecated in API level 16. Instead other
horizontally scrolling widgets are HorizontalScrollView and ViewPager from the
support library are available.
Want a more fast-paced & competitive environment to learn the fundamentals of
Android?
Click here to head to a guide uniquely curated by our experts with the aim to make
you industry ready in no time!
Way to define a Gallery tag
XML
<Gallery
android:id="@+id/languagesGallery"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:unselectedAlpha="50"
android:spacing="5dp"
android:animationDuration="2000"
android:padding="10dp" />
To set the alpha on the items that are not selected. This can
be set in xml
Let us see the implementation of important methods:
Java
// set 3000 milliseconds for animation duration between each items of Gallery
simpleGallery.setAnimationDuration(2000);
// set space between the items of Gallery
simpleGallery.setSpacing(15);
simpleGallery.setUnselectedAlpha(0.25f);
Attributes of GalleryView
Attributes Description
To set the padding from the left, right, the top or bottom side of a
padding Gallery.
simpleGallery.setBackgroundColor(Color.GFGGreencolor); // set
background the desired color
To set the duration for how long a transition animation should run
(in milliseconds)
Via java,
animationDuration simpleGallery.setAnimationDuration(<No of milliseconds>);
Example