Android Notes
Android Notes
Phones come in a variety of colors and choosing the best one can
often be a struggle. Black, silver, and white give off a more classic
vibe, but they’re also boring. Red, green, or purple colorways stand
out more, but can give devices a toyish, less professional look. With
smartphones of the future, you may not have to choose anymore.
Imagine a phone with a completely transparent back made from a
glass-like material that fully absorbs light. The device would have
one or more LED lights inside, the color of which you could change
in the settings of the phone (or maybe with your mind!). When you
choose orange, the entire back cover would completely absorb the
color of the light and look exactly the same, almost as if it were
painted on.
10. OLED and E-ink in one
OLED displays are great for watching videos and playing games, but they
aren’t the best for reading.
E-ink displays like those in Amazon’s Kindle e-readers are a much better
option. I’ve been using a Kindle Paperwhite for years now and love the fact
my eyes don’t get strained after reading for a few hours. It also lets me
read outside, under direct sunlight.
This is more or less impossible with OLED displays. Sure, features like night
mode filter out blue light and can even turn the screen to monochrome,
but even when enabled OLED displays still don’t come close to matching e-
ink technology in terms of reading comfort.
The smartphones of the future I envision would combine OLED and e-ink
technology into one, likely killing dedicated e-readers. With a simple tap in
the settings, you could transform an OLED display into an e-ink screen for
reading books, articles, and various documents without all that light
shining into your face.
An e-ink display is also a lot less power hungry, which could mean longer
battery life.
11. Will there even be smartphones in the
future?
Linux kernel
• is responsible for device drivers, power management & resource access
etc.
• Device drivers are: display driver, cam driver, keypad driver, wi-fi driver,
audio driver, flash memory driver etc.
• This is the Kernel on which android is based.
Native libraries
• On the top of linux kernel, there are Native libraries such as
WebKit, OpenGL, FreeType, SQLite, Media, C runtime library (libc)
etc.
• The WebKit library is responsible for browser support, SQLite is for
database, FreeType for font support, Media for playing and
recording audio and video formats.
Android Stack(Architecture) continued…….
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
(1) Activity is a java class that creates and default window on the screen where we can place different
components such as Button, EditText, TextView, Spinner etc. It is like the Frame of Java AWT.
It provides life cycle methods for activity such as onCreate, onStop, OnResume etc.
(2) The onCreate method is called when Activity class is first created.
(3) The setContentView(R.layout.activity_main) gives information about our layout resource. Here, our layout
resources are defined in activity_main.xml file.
• File: activity_main.xml
<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
</RelativeLayout>
As you can see, a textview is created by the framework automatically. But the message for this string is
defined in the strings.xml file. The @string/hello_world provides information about the textview
message. The value of the attribute hello_world is defined in the strings.xml file.
File: strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">helloandroid</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
</resources>
You can change the value of the hello_world attribute from this file.
Generated R.java file
It is the auto-generated file that contains IDs for all the resources of res directory. It is generated by aapt(Android Asset Packaging
Tool).
Whenever you create any component on activity_main, a corresponding ID is created in the R.java file which can be used in the
Java Source file later.
File: R.java
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.example.helloandroid;
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int ic_launcher=0x7f020000;
}
public static final class id {
public static final int menu_settings=0x7f070000;
}
public static final class layout {
public static final int activity_main=0x7f030000;
}
public static final class menu {
public static final int activity_main=0x7f060000;
}
public static final class string {
public static final int app_name=0x7f040000;
public static final int hello_world=0x7f040001;
public static final int menu_settings=0x7f040002;
}
•
APK File
• An apk file is created by the framework automatically.
If you want to run the android application on the
mobile, transfer and install it.
Resources
• It contains resource files including activity_main,
strings, styles etc.
Manifest file
• It contains information about package including
components such as activities, services, content
providers etc.
Installing software for Android
following operating systems support android app development:
• Microsoft Windows XP or later version.
• Mac OS X 10.5.8 or later version with Intel chip.
• Linux including GNU C Library 2.7 or later.
Software Requirement:
• Java JDK5 or JDK6
• Android SDK
• Eclipse IDE for Java Developers (optional)
• Android Development Tools (ADT) Eclipse Plugin (optional)
Installing software for Android Contd.....
Click on install 7 packages -> accept license agreement and click on install.
SDK is installed.
Installing software for Android Contd.....
The Android Assets Packaging Tool (aapt) handles the packaging process.
Application Context
• Context is an interface to global information about an application environment. It's
an abstract class whose implementation is provided by the Android system.
• Context allows access to application-specific resources and classes, as well as calls
for application-level operations such as launching activities, broadcasting and
receiving intents, etc.
Ex-
public class MyActivity extends Activity {
public void Testing()
{
Context actContext = this; /*returns the Activity Context since Activity extends Context.*/
Context appContext = getApplicationContext(); /*returns the context of the single, global Application object of
the current process. */
Button BtnShowAct1 = (Button) findViewById(R.id.btnGoToAct1);
Context BtnContext = BtnShowAct1.getContext(); /*returns the context of the View. */
}
}
To understand Context
• Another way to describe is, consider context as
remote of a TV & channel's in the television are
resources, services, using intents etc - - -
• Here remote acts as an access to get access to all
the different resources into foreground.
• So, Remote has access to channels such as
resources, services, using intents etc ....
• Likewise ..... Whoever has access to remote
naturally has access to all the things such as
resources, services, using intents etc
Activity Life Cycle
Activity Life Cycle
• We can control and manage the resource through the life
cycle methods of activity.
• There are 7 life cycle methods of android.app.Activity class.
They are as follows:
Method Description
onResume called when activity will start interacting with the user.
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("lifecycle","onCreate invoked");
}
@Override
protected void onStart() {
super.onStart();
Log.d("lifecycle","onStart invoked");
}
@Override
protected void onResume() {
super.onResume();
Log.d("lifecycle","onResume invoked");
}
@Override
protected void onPause() {
super.onPause();
Log.d("lifecycle","onPause invoked");
}
@Override
protected void onStop() {
super.onStop();
Log.d("lifecycle","onStop invoked");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d("lifecycle","onRestart invoked");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("lifecycle","onDestroy invoked");
}
}
Intents
Intent is the message that is passed between components
such as activities, content providers, broadcast receivers,
services etc.
The dictionary meaning of intent is intention or purpose. So,
it can be described as the intention to do action.
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
String url=editText1.getText().toString();
Intent intent=new Intent(Intent.ACTION_VIEW,Uri.parse(url));
startActivity(intent);
}
});
}
}
Android Explicit Intent Example
ActivityOne class ActivityTwo class
File: MainActivityOne.java File: MainActivityTwo.java
package com.example.explicitintent2; package com.example.explicitintent2;
import android.os.Bundle; import android.app.Activity;
import android.app.Activity; import android.content.Intent;
import android.content.Intent; import android.os.Bundle;
import android.view.View;
import android.view.Menu; import android.view.View.OnClickListener;
import android.view.View; import android.widget.Button;
import android.view.View.OnClickListener; import android.widget.EditText;
import android.widget.Button; import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
public class ActivityTwo extends Activity {
public class ActivityOne extends Activity { @Override
public void onCreate(Bundle bundle) {
@Override super.onCreate(bundle);
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); TextView tv=new TextView(this);
setContentView(R.layout.activity_main); tv.setText("second activity");
setContentView(R.layout.activity_two);
Button button1=(Button)findViewById(R.id.Button01); Bundle extras = getIntent().getExtras();
button1.setOnClickListener(new OnClickListener(){ String value1 = extras.getString("Value1");
public void onClick(View view) { String value2 = extras.getString("Value2");
Intent i = new Intent(getApplicationContext(), ActivityTwo.class); Toast.makeText(getApplicationContext(),"Values are:\n F
i.putExtra("Value1", "Android By Javatpoint"); irst value: "+value1+
"\n Second Value: "+value2,Toast.LENGTH_LONG).show();
i.putExtra("Value2", "Simple Tutorial");
// Set the request code to any code you like, you can identify the Button button1=(Button)findViewById(R.id.Button01);
// callback via this code
startActivity(i); button1.setOnClickListener(new OnClickListener(){
public void onClick(View view) {
} Intent i = new Intent(getApplicationContext(), ActivityOn
}); e.class);
} startActivity(i);
} }
});
}
}
Toast
• A Toast is a transient message, meaning that it displays and disappears on its
own without user interaction. Moreover, it does not take focus away from the
currently active Activity, so if the user is busy writing the next Great
Programming Guide, keystrokes will not be “eaten” by the message.
• Since a Toast is transient, you have no way of knowing if the user even notices it.
You get no acknowledgment from the user, nor does the message stick around
for a long time to pester the user.
• Hence, the Toast is mostly for advisory messages, such as indicating a long-
running background task is completed, the battery has dropped to a low level,
and so on.
Syntax to create a toast:
Toast.makeText(getApplicationContext(), ”Message”, Toast.LENGTH_SHORT).show();
Alert
AlertDialog pops up, grabs the focus, and stays there until closed by the user.
You might use this for a critical error, like a validation message that cannot be effectively
displayed in the base activity UI, or some other situation where you are sure that the
user needs to see the message immediately.
How to create an alert in android app?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButtonClick();
}
public void addListenerOnButtonClick()
{ //Getting the ToggleButton and Button instance from the layout xml file
toggleButton1=(ToggleButton)findViewById(R.id.toggleButton1);
toggleButton2=(ToggleButton)findViewById(R.id.toggleButton2);
buttonSubmit=(Button)findViewById(R.id.button1);
Button buttonOrder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButtonClick();
}
public void addListenerOnButtonClick(){
//Getting instance of CheckBoxes and Button from the activty_main.xml file
pizza=(CheckBox)findViewById(R.id.checkBox1);
coffee=(CheckBox)findViewById(R.id.checkBox2);
burger=(CheckBox)findViewById(R.id.checkBox3);
buttonOrder=(Button)findViewById(R.id.button1);
//Applying the Listener on the Button click
buttonOrder.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View view) {
int totalamount=0;
StringBuilder result=new StringBuilder();
result.append("Selected Items:");
if(pizza.isChecked()){
result.append("\nPizza 100Rs");
totalamount+=100;
}
if(coffe.isChecked()){
result.append("\nCoffe 50Rs");
totalamount+=50;
}
if(burger.isChecked()){
result.append("\nBurger 120Rs");
totalamount+=120;
}
result.append("\nTotal: "+totalamount+"Rs");
//Displaying the message on the toast
Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_LONG).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
Android Spinner Example
Spinner is like the combox box of AWT or Swing. It can be used to display the multiple
options to the user. Only one item can be selected by the user.
activity_main.xml
<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="83dp" />
</RelativeLayout>
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Getting the instance of Spinner and applying OnItemSelectedListener on it
Spinner spin = (Spinner) findViewById(R.id.spinner1);
spin.setOnItemSelectedListener(this);
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Gallery & Image view
Gallery is a view that shows items (such as images)
in a center –locked, horizontal scrolling list.
• nf.setLatestEventInfo(MainStatus.this, notificationTitle,
notificationMessage, pendingIntent);
• nm.notify(9999, nf);
Supporting multiple screen sizes
• Android runs on a variety of devices that offer different screen sizes and
densities. For applications, the Android system provides a consistent
development environment across devices and handles most of the work to
adjust each application's user interface to the screen on which it is
displayed.
• At the same time, the system provides APIs that allow us to control our
application's UI for specific screen sizes and densities, in order to optimize
our UI design for different screen configurations.
Terms:
• Screen size
• Density
• Orientation
Multiple Screen Size
Best Practices
• The objective of supporting multiple screens is to create an
application that can function properly and look good on any
of the generalized screen configurations supported by
Android.
Here is a quick checklist about how we can ensure that our
application displays properly on different screens:
• Use wrap_content, fill_parent, or dp units when specifying
dimensions in an XML layout file
• Do not use hard coded pixel values in your application code
• Do not use AbsoluteLayout (it's deprecated)
• Supply alternative bitmap drawables for different screen
densities
Unit-III(menus, medias)
Localization
(the process of translating a product into different languages or adapting a product for a
specific country or region)
• Android loads text and media resources from the project’s
‘res’ directory.
• For example, if the code loads a string called ‘R.string.title’,
Android will choose the correct value for that string at
runtime by loading the appropriate strings.xml file from a
matching ‘res/values’ directory.
• In order to have a multilingual Android app we need to
provide Android with the localized resource files.
If the locale is ‘en-US’, Android will look for a value of
“R.string.title” by searching the files in the following order:
1. ‘res/values-en-rUS/strings.xml’
2. ‘res/values-en/strings.xml’
3. ‘res/values/strings.xml’
• Table shows the paths to the different resource
files and which ones are used for which locale.
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.menutst.MainMenu" >
<item android:id="@+id/item1"
android:title="option1"/>
<item android:id="@+id/item2"
android:title="option2"/>
<item android:id="@+id/item3"
android:title="option3"/>
</menu>
MainMenu.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
switch(id)
{
case R.id.item1: Toast.makeText(getApplicationContext(), "option1 is selected", Toast.LENGTH_LONG).show();
return true;
case R.id.item2:Toast.makeText(getApplicationContext(), "option 2 is selected", Toast.LENGTH_LONG).show();
return true;
case R.id.item3: Toast.makeText(getApplicationContext(), "option 3 is seleced", Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Context menu
• The context menu appears when user press long click on the
element. It is also known as floating menu.
• It doesn't support item shortcuts and icons.
onCreateContextMenu () method of Activity class is used to
create context method and
onContextItemSelected() method of Activity class is used to
implement action on selection of context menu.
Custom Dialog
• Custom dialog is an alert dialog with added button according to users requirement.
• It can have max 3 buttons.
Example-
Ex- <Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="83dp" />
Playing Audio, Video
• Android framework provides various APIs that allows us to add video,
audio, and photo capability to our application for playing and recording
media.
• We can play audio, video files in our application which are stored in raw
resource , file system, or from a data streaming incoming from network.
@Override
protected void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_main_video2);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
vv.requestFocus();
//if we have a position on savedInstanceState, the video playback should start from here
vv.seekTo(position);
if (position == 0) {
vv.start();
} else {
//if we come from a resumed activity, video playback will be paused
vv.pause();
}
}
}
Data Storage Options
Android platform provides multiple mechanism for data
persistence. These mechanism depends on various factors,
such as the amount of data to be stored, frequency of data
accessibility, type of manipulation to be done on database etc.
Different data storage options or mechanism are:
1. The Preference
2. The Internal storage
3. The External storage
4. The SQLite database
5. The content provider
1. Preferences:
• Android provides many ways of storing data of an application. One of this
way is called Shared Preferences. Shared Preferences allow us to save and
retrieve data in the form of key, value pair.
• In order to use shared preferences, we have to call a method
getSharedPreferences() that returns a SharedPreference instance pointing
to the file that contains the values of preferences.
SharedPreferences sp= getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Other modes:
• MODE_APPEND
• MODE_WORLD_READABLE
• MODE_WORLD_WRITEABLE
We can save something in the sharedpreferences by using SharedPreferences.Editor class. we will
call the edit method of SharedPreference instance and will receive it in an editor object. Its syntax
is −
Editor editor = sharedpreferences.edit();
editor.putString("key", "value");
editor.commit();
Other than putString( ), putLong( ), putFloat( ) etc methods can be used for long and float data.
SharedPreferences
• SharedPreferences is an API from Android SDK to
store and retrieve application preferences.
• SharedPreferences are simply sets of data values
that stored persistently. Persistently which mean
data you stored in the SharedPreferences are still
exist even if you stop the application or turn off
the device.
• SharedPreferences available at the Activity level
or shared across all Activity in application
package.
Example- To Write Preferences…………………………………………
public class MainActivity extends AppCompatActivity {
EditText ed1,ed2,ed3;
Button b1;
SharedPreferences sp;
@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);
sp= 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 e= sp.edit();
e.putString(Name, n);
e.putString(Phone, ph);
e.putString(Email, e);
e.commit();
Toast.makeText(MainActivity.this,"Thanks",Toast.LENGTH_LONG).show();
}
});
}
}
Reading Preferences
public class ReadFref extends Activity
{
SharedPreferences sp;
String id,nm,cnt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.readpref);
id=sp.getString("ID",null);
nm=sp.getString("Name", null);
cnt=sp.getString("Contact",null);
Toast.makeText(this,"\nID"+id+"\nName"+nm+"\nContact"+cnt,Toast.LENGTH_LONG).show();
}
}
2. Internal Storage:
• You can save files directly on the device's internal storage. By
default, files saved to the internal storage are private to your
application and other applications cannot access them (nor can the
user). When the user uninstalls your application, these files are
removed.
To create and write a private file to the internal storage:
• Call openFileOutput() with the name of the file and the operating
mode. This returns a FileOutputStream.
• Write to the file with write().
• Close the stream with close().
For example:
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME,
Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
• MODE_PRIVATE will create the file (or replace a
file of the same name) and make it private to
your application.
Other modes available are:
• MODE_APPEND,
• MODE_WORLD_READABLE, and
MODE_WORLD_WRITEABLE.
To read a file from internal storage:
• Call openFileInput() and pass it the name of the
file to read. This returns a FileInputStream.
• Read bytes from the file with read().
• Then close the stream with close().
public void read_file( )
{
try {
FileInputStream fis = context.openFileInput(filename);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
}
3. External Data storage:
Every Android-compatible device supports a shared
"external storage" that you can use to save files. This
can be a removable storage media (such as an SD card)
or an internal (non-removable) storage. Files saved to
the external storage are world-readable and can be
modified by the user when they enable USB mass
storage to transfer files on a computer.
• Caution: External storage can become unavailable if
the user mounts the external storage on a computer or
removes the media, and there's no security enforced
upon files you save to the external storage. All
applications can read and write files placed on the
external storage and the user can remove them.
• Getting access to external storage
• In order to read or write files on the external storage, your
app must acquire the READ_EXTERNAL_STORAGE or
WRITE_EXTERNAL_STORAGE system permissions. For
example:
• If you need to both read and write files, then you need to
request only the WRITE_EXTERNAL_STORAGE permission,
because it implicitly requires read access as well.
myOutWriter.close();
fOut.close();
//Ex of Reading data from SD card
File myFile = new File("/sdcard/mysdfile.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(new
InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
txtData.setText(aBuffer);
saveButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
try {
FileOutputStream fos = new FileOutputStream(myExternalFile);
fos.write(inputText.getText().toString().getBytes());
fos.close();
} catch (IOException e) { e.printStackTrace(); }
inputText.setText("");
response.setText("SampleFile.txt saved to External Storage...");
}
});
readButton = (Button) findViewById(R.id.getExternalStorage);
readButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
try {
FileInputStream fis = new FileInputStream(myExternalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null)
{
myData = myData + strLine;
}
in.close();
} catch (IOException e) { }
inputText.setText(myData);
response.setText("SampleFile.txt data retrieved from Internal Storage...");
}
});
if (!isExternalStorageAvailable() || isExternalStorageReadOnly())
{
saveButton.setEnabled(false);
}
else {
myExternalFile = new File(getExternalFilesDir(filepath), filename);
}
}
private static boolean isExternalStorageReadOnly()
{
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
return true;
} return false;
}
private static boolean isExternalStorageAvailable()
{
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState))
{
return true;
}
return false;
}
}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText textmsg;
static final int READ_BLOCK_SIZE = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textmsg=(EditText)findViewById(R.id.editText1);
}
// write text to file
public void WriteBtn(View v) {
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_APPEND);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(textmsg.getText().toString());
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!“, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
// Read text from file
public void ReadBtn(View v) {
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
Toast.makeText(getBaseContext(), s, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
4. SQLite
• SQLite is a software library that implements a
self-contained, serverless, zero-configuration,
transactional SQL database engine.
• Execute SQL: This is where we'll spend a majority of our time: writing SQL
queries, executing them, and seeing the filtered results.
SQLite Connectivity
• SQLite is a opensource SQL database that stores data to a text file
on a device. Android comes in with built in SQLite database
implementation.
• SQLite supports all the relational database features.
• In order to access this database, we don't need to establish any
kind of connections for it like JDBC,ODBC etc.
Database - Package
• The main package is android.database.sqlite that contains the
classes to manage our own databases.
Database - Creation
• In order to create a database we just need to call this method
openOrCreateDatabase with our database name and mode as a
parameter. It returns an instance of SQLite database which we have
to receive in our own object.
Syntax :
SQLiteDatabase mydatabase = openOrCreateDatabase("your database
name",MODE_PRIVATE,null);
Some other SQLite Function to open DB
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table contacts " +
"(id integer primary key, name text, phone text, email text, street text,
place text)");
}
Example of -onUpgrage
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
Database: deleting record
• Delete method from SQLiteDatabase is used to delete the
record from SQLite. It can be implemented in DatabaseHelper
class.
Ex- Delete function of DatabaseHelper class:
public Integer deleteRecord(Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(“Employee", "id = ? ", new String[] {
Integer.toString(id) });
}
Database: updating records
public boolean updateRecords (Integer id, String name, String phone, String email)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("name", name);
cv.put("phone", phone);
cv.put("email", email);
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.insert("contacts", null, contentValues);
return true;
}
Example of –getData & getRows
public Cursor getData(int id)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts where
id="+id+"", null );
return res;
}
…………………………………………………………………………………………………………
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, tablename);
return numRows;
}
Example of -update
public boolean updateContact (Integer id, String name, String phone, String
email, String street,String place)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.update("contacts", contentValues, "id = ? ", new String[] {
Integer.toString(id) } );
return true;
}
Example of -delete
Enable/Disable zoom
• You can also enable or disable the zoom gestures in the map by
calling the setZoomControlsEnabled(boolean) method. Its syntax is
given below −
• googleMap.getUiSettings().setZoomGesturesEnabled(true);
import com.google.android.gms.maps.model.LatLng;
Code………….
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback
{
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap)
{
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng LL = new LatLng(21, 57);
mMap.addMarker(new
MarkerOptions().position(LL).title(“CMR.EDU"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(LL));
}
}
The Global Positioning System (GPS)
• The Global Positioning System (GPS) is a satellite-based navigation system made up of a network of
24 satellites placed into orbit by the U.S. Department of Defense.
• GPS was originally intended for military applications, but in the 1980s, the government made the
system available for civilian use.
• GPS works in any weather conditions, anywhere in the world, 24 hours a day. There are no
subscription fees or setup charges to use GPS.
How it works
• GPS satellites circle the earth twice a day in a very precise orbit and transmit signal information to
earth.
• GPS receivers take this information and use trilateration to calculate the user's exact location.
Essentially, the GPS receiver compares the time a signal was transmitted by a satellite with the time
it was received. The time difference tells the GPS receiver how far away the satellite is. Now, with
distance measurements from a few more satellites, the receiver can determine the user's position
and display it on the unit's electronic map.
• A GPS receiver must be locked on to the signal of at least 3 satellites to calculate a 2-D position
(latitude and longitude) and track movement. With four or more satellites in view, the receiver can
determine the user's 3-D position (latitude, longitude and altitude). Once the user's position has
been determined, the GPS unit can calculate other information, such as speed, bearing, track, trip
distance, distance to destination, sunrise and sunset time and more.
• How accurate is GPS?
• Today's GPS receivers are extremely accurate.
GPS Implementation
• <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />