//*------------------------------------------------------------------------------------*
//* Book: Android from A to D (First Edition) *
//* Author: Scott L. Hecht *
//* Example code from text. *
//*------------------------------------------------------------------------------------*
//*------------------------------------------------------------------------------------*
//* Chapter 1: Installing the Android SDK on Windows - pg 11 *
//*------------------------------------------------------------------------------------*
//No code in this chapter.
//*------------------------------------------------------------------------------------*
//* Chapter 2: Creating Our First Android Application - pg 37 *
//*------------------------------------------------------------------------------------*
//p.47
//p.48
//p.48
My First Android Application
HELLO, WORLD!!
Settings
MainActivity
//p.49
package com.example.andapp1;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
//p.49
//p.50
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("MYAPPTAG","MY IMPORTANT MESSAGE GOES HERE!");
}
//*------------------------------------------------------------------------------------*
//* Chapter 3: Quick Start Guide to Java Programming - pg 53 *
//*------------------------------------------------------------------------------------*
//p.53
int iCounter;
iCounter=1;
//p.53
int iCounter = 1;
//p.53
int iCounter = 1; //My counter variable set to 1.
//p.53
/* This program is used to do something
wonderful and people will be amazed at
how great it is! */ int iCounter=1;
//p.54
/**
* iCounter keeps track of counting things.
*
*/
int iCounter=1;
//p.54
if (condition)
statement;
//p.54
if (condition)
statement-1;
else
statement-2;
//p.54
if (condition) {
statement-1;
statement-2;
...
}
//p.54
if (condition) {
statement-1;
statement-2;
...
}
else {
statement-3;
statement-4;
...
}
//p.55
if (condition-1) {
statement-1;
statement-2;
...
}
else if (condition-2) {
statement-3;
statement-4;
...
}
else if (condition-3) {
statement-3;
statement-4;
...
}
//p.55
if (condition-1) {
statement-1;
statement-2;
...
}
else if (condition-2) {
statement-3;
statement-4;
...
}
else if (condition-3) {
statement-3;
statement-4;
...
}
else {
statement-5;
statement-6;
...
}
//p.55
switch(expression) {
case constant-1:
statement-1;
statement-2;
...
break;
case constant-2:
statement-3;
statement-4;
...
break;
...
default:
statement-1;
statement-2;
...
break;
}
//p.55
conditional-true-false-test ? condition-is-true : condition-is-false;
//p.56
int iMinLenWid = iLength < iWidth ? iLength : iWidth;
//p.56
for (initialize; stopping-condition; increments) {
statements;
}
//p.56
for (int i=0; i<10; i++) {
iTotal += i;
}
//p.56
while (condition) {
statements;
}
//p.56
while (i<10) {
iTotal += i;
i++;
}
//p.56
do {
statements;
} while (condition);
//p.56
do {
iTotal += i;
i++;
} while (i<10);
//p.56-57
while (i<10) {
iTotal += i;
i++;
if (i==5) {
break;
}
}
//p.57
iCounter += x;
//p.57
iCounter = iCounter + x;
//p.57
iCounter = iCounter2 = iCounter3 = 0;
//p.58
String sGreeting = "Bonjour";
String sTitle = "Monsieur";
//p.58
String sFullGreeting = sGreeting + " ," + sTitle;
//p.58
int[] aNums = new int[10];
//p.58
int X = aNums[5];
//p.58
for(i=0; i<10; i++) {
iTotal += aNums[i];
}
//p.58-59
class jpgm6 {
public static void main(String args[]) {
try {
//Divide by zero
int iNum = 5/0;
}
catch(ArithmeticException e) {
System.out.println("Arithmetic Exception Detected: " + e);
}
catch(Exception e) {
System.out.println("Generic Exception Detected: " + e);
}
finally {
System.out.println("Finally!");
}
}
}
//p.60
class Car {
String exteriorColor;
int numberOfCylinders;
boolean start_engine() { ...code to start the engine... }
boolean turn_on_radio() { ...code to turn on the radio... }
}
//p.60
Car MyCar = new Car();
//p.60
class Car {
String exteriorColor;
int numberOfCylinders;
//Our constructor is below
Car() {
exteriorColor = "LimeGreen";
numberOfCylinders = 5;
}
boolean start_engine() { ...code to start the engine... }
boolean turn_on_radio() { ...code to turn on the radio... }
}
//p.60
class Car {
String exteriorColor;
int numberOfCylinders;
//Our constructor is below
Car(String pExtClr,int pNumCyl) {
exteriorColor = pExtClr;
numberOfCylinders = pNumCyl;
}
boolean start_engine() { ...code to start the engine... }
boolean turn_on_radio() { ...code to turn on the radio... }
}
//p.60
Car MyCar = new Car("LimeGreen",5);
//p.61
class Car {
String exteriorColor;
int numberOfCylinders;
//Our constructor is below
Car(String pExtClr,int pNumCyl) {
exteriorColor = pExtClr;
numberOfCylinders = pNumCyl;
}
public String getExteriorColor() {
return(exteriorColor);
}
public int getNumberOfCylinders() {
return(numberOfCylinders);
}
boolean start_engine() { ...code to start the engine... }
boolean turn_on_radio() { ...code to turn on the radio... }
}
//p.61
Car MyCar = new Car("PurplePassion",4);
System.out.println(MyCar.getExteriorColor());
System.out.println(MyCar.getNumberOfCylinders());
//p.61
public void setExteriorColor(String pExtClr) {
exteriorColor = pExtClr;
}
public void setNumberOfCylinders(int pNumCyl) {
numberOfCylinders = pNumCyl;
}
//p.62
private String exteriorColor;
private int numberOfCylinders;
//p.62
Car MyCar1 = new Car("PurplePassion",4);
Car MyCar2 = new Car("VomitYellow",8);
//p.62
public static int objectCount = 0;
//p.62-63
Car MyCar1 = new Car("PurplePassion",4);
System.out.println("Number of Objects = " + MyCar1.objectCount);
Car MyCar2 = new Car("YellowVomit",8);
System.out.println("Number of Objects = " + MyCar2.objectCount);
//p.63
class NumberInfo {
public static double PI = 3.1415;
public static double SquareIt(double pNum) {
return(pNum*pNum);
}
}
System.out.println("Cheap PI = " + NumberInfo.PI);
System.out.println("Square of 5 = " + NumberInfo.SquareIt(5));
//p.63-64
class Vehicle {
private String exteriorColor;
private int numberOfCylinders;
//Our constructor is below
public Vehicle(String pExtClr,int pNumCyl) {
exteriorColor = pExtClr;
numberOfCylinders = pNumCyl;
}
//Getters
public String getExteriorColor() {
return(exteriorColor);
}
public int getNumberOfCylinders() {
return(numberOfCylinders);
}
//Setters
public void setExteriorColor(String pExtClr) {
exteriorColor = pExtClr;
}
public void setNumberOfCylinders(int pNumCyl) {
numberOfCylinders = pNumCyl;
}
}
//p.64
class Car extends Vehicle {
private boolean ipodCharger;
public Car(String pExtClr,int pNumCyl,boolean pIPC) {
super(pExtClr,pNumCyl);
ipodCharger = pIPC;
}
public boolean getIpodCharger() {
return(ipodCharger);
}
public void setIpodCharger(boolean pIPC) {
ipodCharger = pIPC;
}
}
//p.64
class Truck extends Vehicle {
private double grossVehicularWeight;
public Truck(String pExtClr,int pNumCyl,double pGVW) {
super(pExtClr,pNumCyl);
grossVehicularWeight = pGVW;
}
public Double getGrossVehicularWeight() {
return(grossVehicularWeight);
}
public void setGrossVehicularWeight(double pGVW) {
grossVehicularWeight = pGVW;
}
}
//p.65
super(pExtClr,pNumCyl);
//p.65-66
class Car extends Vehicle {
private boolean ipodCharger;
public Car(String pExtClr,int pNumCyl,boolean pIPC) {
super(pExtClr,pNumCyl);
ipodCharger = pIPC;
}
public boolean getIpodCharger() {
return(ipodCharger);
}
public void getIpodCharger(boolean pIPC) {
ipodCharger = pIPC;
}
//Override the getExteriorColor method appearing
// in the Vehicle class with my own method.
@Override
public String getExteriorColor() {
return("The exterior color for this CAR is " + super.getExteriorColor());
}
}
class Truck extends Vehicle {
private double grossVehicularWeight;
public Truck(String pExtClr,int pNumCyl,double pGVW) {
super(pExtClr,pNumCyl);
grossVehicularWeight = pGVW;
}
public Double getGrossVehicularWeight() {
return(grossVehicularWeight);
}
public void getGrossVehicularWeight(double pGVW) {
grossVehicularWeight = pGVW;
}
//Override the getExteriorColor method appearing
// in the Vehicle class with my own method.
@Override
public String getExteriorColor() {
return("The exterior color for this TRUCK is " + super.getExteriorColor());
}
}
//p.67
access-modifier interface interface-name {
//Define your attributes
data-type var-name-1 = value-1;
data-type var-name-2 = value-2;
...
//Define your methods
return-data-type method-name-1(parameter-list-1);
return-data-type method-name-2(parameter-list-2);
...
}
//p.67
interface IRadio {
public bool bOn=false;
public String sBand="AM";
public float fHertz=1060;
public void turn_on_off(bool bOn);
public void change_station(float fHertz);
public void change_band(String sBand);
}
//p.68
class Car extends Vehicle implements IRadio {
...fill in the methods here...
}
//p.68-69
abstract class Vehicle {
private String exteriorColor;
private int numberOfCylinders;
//Our constructor is below
public Vehicle(String pExtClr,int pNumCyl) {
exteriorColor = pExtClr;
numberOfCylinders = pNumCyl;
}
//Getters
abstract public String getExteriorColor();
public int getNumberOfCylinders() {
return(numberOfCylinders);
}
//Setters
public void setExteriorColor(String pExtClr) {
exteriorColor = pExtClr;
}
public void setNumberOfCylinders(int pNumCyl) {
numberOfCylinders = pNumCyl;
}
}
//p.69-70
import java.util.*;
abstract class Vehicle {
private String exteriorColor;
private int numberOfCylinders;
//Our constructor is below
public Vehicle(String pExtClr,int pNumCyl) {
exteriorColor = pExtClr;
numberOfCylinders = pNumCyl;
}
//Getters
abstract public String getExteriorColor();
public int getNumberOfCylinders() {
return(numberOfCylinders);
}
public String getColor() {
return(exteriorColor);
}
//Setters
public void setExteriorColor(String pExtClr) {
exteriorColor = pExtClr;
}
public void setNumberOfCylinders(int pNumCyl) {
numberOfCylinders = pNumCyl;
}
}
class Car extends Vehicle {
private boolean ipodCharger;
public Car(String pExtClr,int pNumCyl,boolean pIPC) {
super(pExtClr,pNumCyl);
ipodCharger = pIPC;
}
public boolean getIpodCharger() {
return(ipodCharger);
}
public void getIpodCharger(boolean pIPC) {
ipodCharger = pIPC;
}
//Create the code for the abstract method getExteriorColor.
public String getExteriorColor() {
return("The exterior color for this CAR is " + getColor());
}
}
class Truck extends Vehicle {
private double grossVehicularWeight;
public Truck(String pExtClr,int pNumCyl,double pGVW) {
super(pExtClr,pNumCyl);
grossVehicularWeight = pGVW;
}
public Double getGrossVehicularWeight() {
return(grossVehicularWeight);
}
public void getGrossVehicularWeight(double pGVW) {
grossVehicularWeight = pGVW;
}
//Create the code for the abstract method getExteriorColor.
public String getExteriorColor() {
return("The exterior color for this TRUCK is " + getColor());
}
}
class jpgm7 {
public static void main(String args[]) {
Car MyCar = new Car("PurplePassion",5,true);
Truck MyTruck = new Truck("BisonBrown",5,56.7643);
//Print out the exterior color of the car and truck.
System.out.println(MyCar.getExteriorColor());
System.out.println(MyTruck.getExteriorColor());
}
}
//p.70-71
public double SumTotal(double... nums) {
double tot=0.0;
for(int i=0;i
//p.104
My First Android Application
HELLO, WORLD!!
Settings
MainActivity
//*------------------------------------------------------------------------------------*
//* Chapter 6: Android Layouts - pg 106 *
//*------------------------------------------------------------------------------------*
//p.107
//p.108
//p.109
My First Android Application
HELLO, WORLD!!
Settings
MainActivity
Button
//p.109
android:text="Button"
//p.109
android:text="@string/button_text"
//p.110-111
//p.112-114
//p.114-116
//p.119
//p.119
//p.119-120
//p.120-121
//p.122
//p.124
//p.125
//p.126
//p.126-127
- AMERIGROUP CORP
- PENN VIRGINIA RESOURCE PARTN
- CONVERGYS CORP
- INGREDION INC
- NUVEEN CAL MUNI MKT OPPOR FD
- CITIGROUP CAPITAL IX, 6.00% TRUPS CAPITAL SEC
- FOREST OIL CORP
- FLY LEASING LTD-ADR
- MACERICH CO/THE
- FELCOR LODGING TRUST INC
- KILROY REALTY CORP
- SEALED AIR CORP
- MORGAN STANLEY CAPITAL TRUST III
//p.128-129
...and so on...
//*------------------------------------------------------------------------------------*
//* Chapter 7: Views Parade and the Eclipse Palette - pg 132 *
//*------------------------------------------------------------------------------------*
//No code examples in this chapter.
//*------------------------------------------------------------------------------------*
//* Chapter 8: Activities - pg 139 *
//*------------------------------------------------------------------------------------*
//p.139
package com.example.andapp1;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
//p.140
//p.141
//p.141
package com.example.andapp1;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
//p.142
setContentView(R.layout.activity_main);
//p.142
super.onCreate(savedInstanceState);
//p.142-143
My First Android Application
HELLO, WORLD!!
Settings
MainActivity
Button
//p.143
...additional XML...
//p.143
false
true
//p.143-144
- AMERIGROUP CORP
- PENN VIRGINIA RESOURCE PARTN
- CONVERGYS CORP
- INGREDION INC
- NUVEEN CAL MUNI MKT OPPOR FD
- CITIGROUP CAPITAL IX, 6.00% TRUPS CAPITAL SEC
- FOREST OIL CORP
- FLY LEASING LTD-ADR
- MACERICH CO/THE
- FELCOR LODGING TRUST INC
- KILROY REALTY CORP
- SEALED AIR CORP
- MORGAN STANLEY CAPITAL TRUST III
//p.144
...more layout goes here...
//p.144
//p.144
//p.144
TextView oTxtVw = (TextView) findViewById(R.id.myTxtVw);
//p.146
//p.149
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String sText = "Now is the time...";
Toast toast = Toast.makeText(getApplicationContext(), sText, Toast.LENGTH_LONG);
toast.show();
}
//p.150
import android.widget.Toast;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LayoutInflater inflater = getLayoutInflater();
View layout=inflater.inflate(R.layout.toast_layout,
(ViewGroup) findViewById(R.id.toast_layout_root));
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
//p.150
//*------------------------------------------------------------------------------------*
//* Chapter 9: Wiring-Up Event Handlers - pg 152 *
//*------------------------------------------------------------------------------------*
//p.152
//Create a method used to handle the onClick for the Button
public void changeText(View view) {
TextView oTxtVw = (TextView) findViewById(R.id.TheTextView);
oTxtVw.setText("DISREGARD NUCLEAR WARNING!!");
}
//p.153
//p.154
//p.154
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Step #1: Create an onClickListener
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View view) {
changeText(view);
}
};
//Step #2: Associate the listener with the button via setOnClickListener
((Button) findViewById(R.id.button1)).setOnClickListener(listener);
}
//Create a method used to handle the onClick for the Button
public void changeText(View view) {
TextView oTxtVw = (TextView) findViewById(R.id.TheTextView);
oTxtVw.setText("DISREGARD NUCLEAR WARNING!!");
}
}
//p.155
//p.155
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Create an onClickListener and associate it with the button
((Button) findViewById(R.id.button1)).setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
changeText(view);
}
}
);
}
//Create a method used to handle the onClick for the Button
public void changeText(View view) {
TextView oTxtVw = (TextView) findViewById(R.id.TheTextView);
oTxtVw.setText("DISREGARD NUCLEAR WARNING!!");
}
}
//*------------------------------------------------------------------------------------*
//* Chapter 10: Intents - pg 157 *
//*------------------------------------------------------------------------------------*
//p.161
package com.example.andapp1;
import android.os.Bundle;
import android.app.Activity;
public class SubActivity1 extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub1);
}
}
//p.161
package com.example.andapp1;
import android.os.Bundle;
import android.app.Activity;
import android.view.Gravity;
import android.view.Menu;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.content.Intent;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Create an onClickListener and associate it with the button
//This will inflate activity_sub1.
((Button) findViewById(R.id.button1)).setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,SubActivity1.class);
startActivity(intent);
}
}
);
}
}
//p.162-163
//p.163
package com.example.andapp1;
import android.widget.Button;
import android.os.Bundle;
import android.app.Activity;
import android.view.Gravity;
import android.view.Menu;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.content.Intent;
public class SubActivity1 extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub1);
//Create an onClickListener and associate it with the button
//This will create the data, insert it into the intent and close
//the sub-activity returning us back to the main activity.
((Button) findViewById(R.id.btnSubAct)).setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
String sText="Now is the time...";
Intent results = new Intent(); //null Intent created here!
results.putExtra("RETURNED_TEXT",sText); //insert key/value pair.
setResult(RESULT_OK,results); //set results for return to main
finish(); //close this activity
}
});
};
}
//p.164-165
package com.example.andapp1;
import android.os.Bundle;
import android.app.Activity;
import android.view.Gravity;
import android.view.Menu;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.content.Intent;
public class MainActivity extends Activity {
private static final int SUBACTIVITY_ID=1000; //ID number for activity_sub1.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Create an onClickListener and associate it with the button
//This will inflate activity_sub1.
((Button) findViewById(R.id.button1)).setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,SubActivity1.class);
startActivityForResult(intent,SUBACTIVITY_ID);
}
}
);
}
@Override
public void onActivityResult(int requestCode,int resultCode,Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Based on the sub-activity returning here, pull out their data.
switch(requestCode) {
//Pull in the data coming from activity_sub1 (ID # 1000)
case (SUBACTIVITY_ID): {
if (resultCode == Activity.RESULT_OK) {
//Here is where we pull the string data based on the key RETURNED_TEXT.
String sTextFromSubAct1 = data.getStringExtra("RETURNED_TEXT");
//Place the returned text into the text view @+id/TheTextView.
TextView oTxtVw = (TextView) findViewById(R.id.TheTextView);
oTxtVw.setText(sTextFromSubAct1);
}
else {
//Oops...things didn't go well...RESULT_CANCELED was returned!!
//Place the returned text into the text view @+id/TheTextView.
TextView oTxtVw = (TextView) findViewById(R.id.TheTextView);
oTxtVw.setText("NO DATA RETURNED");
}
break;
}
}
}
}
//p.167
//Create an onClickListener and associate it with the button
//This will open up a pdf file.
((Button) findViewById(R.id.btnPDF)).setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
//Set up a path to the pdf file ON THE DEVICE
//You wouldn't necessarily hard-code this!
String path = "/mnt/sdcard/download/Reporting_Suite_Highlights.pdf";
File targetFile = new File(path);
Uri targetUri = Uri.fromFile(targetFile);
//Set up the intent with a default action of ACTION_VIEW.
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(targetUri, "application/pdf");
//start the activity...even though it isn't an activity we created!
startActivity(intent);
}
});
//p.171
//Create an onClickListener and associate it with the button
//This will search Google based on the word minestrone.
((Button) findViewById(R.id.btnSEARCH)).setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
//Set up your search term
String search_term = "minestrone";
//Set up the intent with a default action of ACTION_WEB_SEARCH.
//Insert the search term into the intent
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY,search_term);
//start the activity...even though it isn't an activity we created!
startActivity(intent);
}
});
//p.172
//p.174-175
//p.175
package com.example.andapp1;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.widget.TextView;
public class IntentExampleActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intent_example);
//Get the intent and data
Intent intent = getIntent();
String data = intent.getData().toString();
//Replace the data in the text view (txtIntTxtVw) with the data.
TextView oTxtVw = (TextView) findViewById(R.id.txtIntTxtVw);
oTxtVw.setText(data);
}
}
//p.175-176
//p.178-179
package com.example.andapp1;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.support.v4.app.NavUtils;
import android.app.ListActivity;
import android.content.Context;
import android.content.pm.*;
public class AppListActivity extends ListActivity {
ArrayList listItems = new ArrayList();
ArrayAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_list);
//Package info
PackageManager oPackMan = getPackageManager();
List oPackInfoList = oPackMan.getInstalledPackages(
PackageManager.GET_ACTIVITIES |
PackageManager.GET_GIDS |
PackageManager.GET_CONFIGURATIONS |
PackageManager.GET_INSTRUMENTATION |
PackageManager.GET_PERMISSIONS |
PackageManager.GET_PROVIDERS |
PackageManager.GET_RECEIVERS |
PackageManager.GET_SERVICES |
PackageManager.GET_SIGNATURES |
PackageManager.GET_UNINSTALLED_PACKAGES
);
String sTextPackageName = "";
for(int i=0; i < oPackInfoList.size(); i++) {
sTextPackageName = oPackInfoList.get(i).packageName;
listItems.add(sTextPackageName);
}
//Associate the listItems with the adapter.
//Note that we specify simple_list_item_1 as the layout.
//See the image below.
adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1,
listItems);
//Sort the list
adapter.sort(new Comparator() {
public int compare(String object1, String object2) {
return object1.compareTo(object2);
};
});
setListAdapter(adapter);
//Un-comment the line below if your listItems is updated occasionally.
//adapter.notifyDataSetChanged();
}
}
//p.179
//*------------------------------------------------------------------------------------*
//* Chapter 11: The Android Manifest - pg 181 *
//*------------------------------------------------------------------------------------*
//No code in this chapter, just XML from the Android documentation.
//*------------------------------------------------------------------------------------*
//* Chapter 12: Android Menus - pg 210 *
//*------------------------------------------------------------------------------------*
//p.210
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
//p.210
//p.211
//p.211
//p.213
//p.213
//p.214-215
//p.216
-
//p.217
//p.218
//p.218
//p.219
public void myClickHandler(MenuItem item) {
if (item.isChecked()) {
item.setChecked(false);
}
else {
item.setChecked(true);
}
}
//p.219
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_checkbox:
Log.d("APP_MSGS","checkbox");
if (item.isChecked()) {
item.setChecked(false);
}
else {
item.setChecked(true);
}
return true;
case R.id.chocolate:
Log.d("APP_MSGS","chocolate");
if (item.isChecked()) {
item.setChecked(false);
}
else {
item.setChecked(true);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//p.221
TextView oTxtVw = (TextView) findViewById(R.id.textView1);
registerForContextMenu(oTxtVw);
//p.221
@Override
public void onCreateContextMenu(ContextMenu menu,
View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.txtvw1_context_menu, menu);
}
//p.221-222
//p.222
@Override
public boolean onContextItemSelected(MenuItem item) {
TextView oTxtVw = (TextView) findViewById(R.id.textView1);
switch (item.getItemId()) {
case R.id.txtvw1cmClear:
oTxtVw.setText("");
return true;
case R.id.txtvw1cmReset:
oTxtVw.setText("Sometown, Somestate USA");
return true;
default:
return super.onContextItemSelected(item);
}
}
//*------------------------------------------------------------------------------------*
//* Chapter 13: Saving State: Bundle, SharedPreference and PreferenceActivity - pg 224 *
//*------------------------------------------------------------------------------------*
//p.225
@Override
protected void onSaveInstanceState(Bundle outState) {
//Send debugging info to the LogCat
Log.d("MYAPPTAG","IN ONSAVEINSTANCESTATE!");
//Save the value of PI to the Bundle
outState.putDouble("PI", Math.PI);
//Save the Stock Symbol the user was perusing
outState.putString("SYMBOL", "GOOG");
//Call the superclass!
super.onSaveInstanceState(outState);
}
//p.225
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Retrieve data from a non-null Bundle
if (savedInstanceState != null) {
//Send debugging info to the LogCat
Log.d("MYAPPTAG","IN IF STATEMENT IN ONCREATE!");
double PI_SAVED = savedInstanceState.getDouble("PI ");
String SYMBOL_SAVED = savedInstanceState.getString("SYMBOL ");
//Substitute the SYMBOL_SAVED for the text in textView1
TextView oTxtVw = (TextView) findViewById(R.id.textView1);
oTxtVw.setText(SYMBOL_SAVED);
}
...snip...
//p.228
private void SaveSettings() {
//Start editing mode on the SharedPreferences object.
SharedPreferences.Editor oSPEditor =
getPreferences(Context.MODE_PRIVATE).edit();
//Add in a key-value pair using the appropriate put* method.
oSPEditor.putString("SYMBOL_SAVED", "MSFT");
//Commit the changes to the SharedPreferences object.
oSPEditor.commit();
}
//p.229
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Retrieve the SharedPreferences
String SYMBOL_SAVED =
getPreferences(Context.MODE_PRIVATE).getString("SYMBOL_SAVED","????");
//Update the text view.
TextView oTxtVw = (TextView) findViewById(R.id.textView1);
oTxtVw.setText(SYMBOL_SAVED);
...snip...
//p.229
private void SaveSettings() {
//Start editing mode on the SharedPreferences object.
SharedPreferences.Editor oSPEditor =
getPreferences("MY_PREF_GROUP",Context.MODE_PRIVATE).edit();
//Add in a key-value pair using the appropriate put* method.
oSPEditor.putString("SYMBOL_SAVED", "MSFT");
//Commit the changes to the SharedPreferences object.
oSPEditor.commit();
}
//p.230
String SYMBOL_SAVED =
getSharedPreferences("MY_PREF_GROUP",
Context.MODE_PRIVATE).getString("SYMBOL_SAVED", "????");
//p.230
//Get the SharedPreferences object
SharedPreferences oSP =
getSharedPreferences("EQUITYYO_PORTFOLIO",Context.MODE_PRIVATE);
//When using Map<>, place the SuppressWarnings "unchecked" annotation
//to tell Java that the generic Map will work with no problems.
@SuppressWarnings("unchecked")
Map oSP_ALL = (Map) oSP.getAll();
//Initialize the final String
String sAllKeys = "Symbols: ";
//Loop for each element in the Map to get the keys using the keyset() method.
for(String sKey : oSP_ALL.keySet()) {
sAllKeys = sAllKeys + "-" + sKey;
}
//p.232
//p.234
package com.example.andapp1;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class PrefsActivity extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Add the preferences located in the preferences.xml file.
addPreferencesFromResource(R.xml.preferences);
}
}
//p.234-235
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_settings:
startActivity(new Intent(MainActivity.this,PrefsActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//p.235
- Single-Threaded
- Multi-Threaded
- 1
- 2
//p.237
//Retrieve the key/value pairs from the PreferenceActivity for
//this application.
Context oCtx = getApplicationContext();
SharedPreferences oAppPrefs =
PreferenceManager.getDefaultSharedPreferences(oCtx);
//Display the key/value pairs to the LogCat
Boolean bFTPVal = oAppPrefs.getBoolean("PREF_FTP_HTTP", false);
String sFTPVal = Boolean.toString(bFTPVal);
Log.d("MYAPPTAG","PREF_FTP_HTTP=" + sFTPVal);
Log.d("MYAPPTAG","PREF_UID=" + oAppPrefs.getString("PREF_UID", "UNKNOWN"));
Log.d("MYAPPTAG","PREF_PWD=" + oAppPrefs.getString("PREF_PWD", "UNKNOWN"));
String sTHREADSVal = oAppPrefs.getString("PREF_NTHREADS", "UNKNOWN");
Log.d("MYAPPTAG","PREF_NTHREADS=" + sTHREADSVal);
//p.238
public class MainActivity extends Activity implements
OnSharedPreferenceChangeListener {
//p.238
//Retrieve the key/value pairs from the PreferenceActivity for this application.
Context oCtx = getApplicationContext();
SharedPreferences oAppPrefs =
PreferenceManager.getDefaultSharedPreferences(oCtx);
//Register the onSharedPreferenceChangeListener
oAppPrefs.registerOnSharedPreferenceChangeListener(this);
//p.238
public void onSharedPreferenceChanged(SharedPreferences prefs,String key) {
if (key.contentEquals("PREF_FTP_HTTP")) {
Log.d("MYAPPTAG","PREF_FTP_HTTP WAS CHANGED!!");
}
else if (key.contentEquals("PREF_UID")) {
Log.d("MYAPPTAG","PREF_UID WAS CHANGED!!");
}
else if (key.contentEquals("PREF_PWD")) {
Log.d("MYAPPTAG","PREF_PWD WAS CHANGED!!");
}
else if (key.contentEquals("PREF_NTHREADS")) {
Log.d("MYAPPTAG","PREF_NTHREADS WAS CHANGED!!");
}
}
//*------------------------------------------------------------------------------------*
//* Chapter 14: Working with the SQLite Database - pg 241 *
//*------------------------------------------------------------------------------------*
//p.251
SQLite Command Line Description
.backup ?DB? FILE Backup DB (default "main") to FILE
.bail ON|OFF Stop after hitting an error. Default: OFF
.databases List names and files of attached databases
.dump ?TABLE? ... Dump the database in an SQL text format. If TABLE specified, only dump tables matching LIKE pattern TABLE.
.echo ON|OFF Turn command echo on or off
.exit Exit this program
.explain ?ON|OFF? Turn output mode suitable for EXPLAIN on or off. With no args, it turns EXPLAIN on.
.header(s) ON|OFF Turn display of headers on or off
.help Show this message
.import FILE TABLE Import data from FILE into TABLE
.indices ?TABLE? Show names of all indices. If TABLE specified, only show indices for tables matching LIKE pattern TABLE.
.load FILE ?ENTRY? Load an extension library
.log FILE|off Turn logging on or off. FILE can be stderr/stdout
.mode MODE ?TABLE? Set output mode where MODE is one of:
csv – comma-separated values
column – Left-aligned columns. (See .width)
html – HTML code
insert – SQL insert statements for TABLE
line – One value per line
list – Values delimited by .separator string
tabs – Tab-separated values
tcl – TCL list elements
.nullvalue STRING Print STRING in place of NULL values
.output FILENAME Send output to FILENAME
.output stdout Send output to the screen
.prompt MAIN CONTINUE Replace the standard prompts
.quit Exit this program
.read FILENAME Execute SQL in FILENAME
.restore ?DB? FILE Restore content of DB (default "main") from FILE
.schema ?TABLE? Show the CREATE statements. If TABLE specified, only show tables matching LIKE pattern TABLE.
.separator STRING Change separator used by output mode and .import
.show Show the current values for various settings
.stats ON|OFF Turn stats on or off
.tables ?TABLE? List names of tables. If TABLE specified, only list tables matching LIKE pattern TABLE.
.timeout MS Try opening locked tables for MS milliseconds
.trace FILE|off Output each SQL statement as it is run
.vfsname ?AUX? Print the name of the VFS stack
.width NUM1 NUM2 ... Set column widths for "column" mode
.timer ON|OFF Turn the CPU timer measurement on or off
.backup ?DB? FILE Backup DB (default "main") to FILE
//p.266
SQLiteDatabase oSQLiteDB;
//p.266
private static SQLiteDatabase oSQLiteDB;
//p.266
//Open the database in read/write mode
oSQLiteDB =
SQLiteDatabase.openDatabase("/data/data/com.example.andapp1/MySQLite3TestDB.db3",
null,
SQLiteDatabase.OPEN_READWRITE);
//p.266
//Close the database
if (oSQLiteDB != null) {
oSQLiteDB.close();
}
//p.267
//Create the SQL string
String sSQL = "SELECT DISTINCT STOCK_SYMBOL FROM HISTORICAL_STOCK_PRICES";
//p.267
//Get a cursor to the returned data
Cursor oCSR = oSQLiteDB.rawQuery(sSQL,null);
//p.267
//Initialize the sAllStockSymbols variable with the number of rows pulled back.
String sAllStockSymbols = Integer.toString(oCSR.getCount()) + ": ";
//p.267
//Loop for each row in the cursor to create a large string of stock symbols
if (oCSR.getCount() > 0) {
while(oCSR.moveToNext()) {
sAllStockSymbols +=
oCSR.getString(oCSR.getColumnIndex("STOCK_SYMBOL")) + " ";
}
}
//p.267
//Let's display the stock symbols using a Toast
Toast toast = Toast.makeText(getApplicationContext(), sAllStockSymbols, Toast.LENGTH_LONG);
toast.show();
//p.268
//Let's insert a new row into the database using execSQL
String sSQL_INSERT="INSERT INTO HISTORICAL_STOCK_PRICES " +
"VALUES('INTC',julianday('now','0 seconds'),22.81);";
oSQLiteDB.execSQL(sSQL_INSERT);
//p.268
//Create a ContentValues object to hold key-value pairs
//ContentValues is located in android.content.
ContentValues oCV = new ContentValues();
//Put the key/value pairs into oCV
oCV.put("STOCK_SYMBOL", "CSCO");
oCV.put("PRICE_DATE", "2456196");
oCV.put("STOCK_PRICE", "18.65");
//Insert the row of data into the table.
long lRowID = oSQLiteDB.insert("HISTORICAL_STOCK_PRICES", null, oCV);
//p.268
//Let's query the database using query() instead of rawquery()
Cursor oCSR2 = oSQLiteDB.query(true,
"HISTORICAL_STOCK_PRICES",
new String[] {"STOCK_SYMBOL"},
null,
null,
null,
null,
"STOCK_SYMBOL",
null);
//p.269
String sAllStockSymbols2 = Integer.toString(oCSR2.getCount()) + ": ";
if (oCSR2.getCount() > 0) {
while(oCSR2.moveToNext()) {
sAllStockSymbols2 +=
oCSR2.getString(oCSR2.getColumnIndex("STOCK_SYMBOL")) + " ";
}
}
Toast toast2 = Toast.makeText(getApplicationContext(), sAllStockSymbols2, Toast.LENGTH_LONG);
toast2.show();
//p.270
//Let's get back the count of the number of row in the table using
// compiled statement
String sSQL_ROWCOUNT = "SELECT COUNT(*) AS ROWCNT FROM HISTORICAL_STOCK_PRICES";
//Generate a compiled SQL statement using the compileStatement() method.
SQLiteStatement oSLS_RC = oSQLiteDB.compileStatement(sSQL_ROWCOUNT);
//Retrieve the row count into the long variable lRowCount.
long lRowCount = oSLS_RC.simpleQueryForLong();
Toast toast3 = Toast.makeText(getApplicationContext(), "Number of Rows=" + Long.toString(lRowCount), Toast.LENGTH_LONG);
toast3.show();
//p.270
Cursor oCSR2 = oSQLiteDB.query(true,
"HISTORICAL_STOCK_PRICES",
new String[] {"STOCK_SYMBOL"},
"STOCK_SYMBOL=? OR STOCK_SYMBOL=?",
new String[] {"MSFT","CSCO"},
null,
null,
"STOCK_SYMBOL",
null);
//p.270
//Delete INTC and CSCO
int iNbrRowsDel = oSQLiteDB.delete("HISTORICAL_STOCK_PRICES",
"STOCK_SYMBOL IN (?,?)",
new String[] {"INTC","CSCO"});
//p.271
//Update MSFT's stock price
ContentValues oCV_UPDATE = new ContentValues();
oCV_UPDATE.put("STOCK_PRICE", 2.56);
int iNbrRowsUpdated = oSQLiteDB.update("HISTORICAL_STOCK_PRICES",
oCV_UPDATE,
"STOCK_SYMBOL=?",
new String[] {"MSFT"});
//p.271
String sBuiltSQL = SQLiteQueryBuilder.buildQueryString(
false,
"HISTORICAL_STOCK_PRICES",
new String[] {"STOCK_SYMBOL","STOCK_PRICE"},
"STOCK_SYMBOL IN ('MSFT','GOOG')",
null,
null,
"STOCK_SYMBOL,STOCK_PRICE DESC",
"2");
//p.273-275
package com.example.andapp1;
import android.content.Context;
import android.database.sqlite.*;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.*;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.content.ContentValues;
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
private SQLiteDatabase oDB;
//public constructor
public MySQLiteOpenHelper(Context context,
String sDBName,
CursorFactory factory,
int iDBVersion) {
super(context,sDBName,null,iDBVersion);
}
//onCreate - called when the database is created for the first time
@Override
public void onCreate(SQLiteDatabase db) {
Log.d("MYSQLTAG","IN ONCREATE!!");
}
//onUpgrade
@Override
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion) {
Log.d("MYSQLTAG","IN ONUPGRADE!!");
}
//onOpen
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
oDB=db;
Log.d("MYSQLTAG","IN ONOPEN==>" + oDB.getPath());
}
//getReadableDatabase
@Override
public SQLiteDatabase getReadableDatabase() {
Log.d("MYSQLTAG","IN GETREADABLEDATABASE!!");
return super.getReadableDatabase();
}
//getWriteableDatabase
@Override
public SQLiteDatabase getWritableDatabase() {
Log.d("MYSQLTAG","IN GETWRITABLEDATABASE!!");
return super.getWritableDatabase();
}
//enumerateTables
public String enumerateTables() {
//use oDB since the database is already opened.
String sTables = "";
//Using the SQLite sqlite_master table to get a list of tables in the database.
//Note that we exclude sqlite_stat1 and android_metadata from the list.
String sSQL = "SELECT name" +
" FROM sqlite_master" +
" WHERE type='table'" +
" and name not in ('sqlite_stat1','android_metadata')
ORDER BY name";
//Get a cursor
Cursor oCSR = oDB.rawQuery(sSQL,null);
//Loop for each row in the cursor to create a large string of stock symbols
if (oCSR.getCount() > 0) {
while(oCSR.moveToNext()) {
sTables += oCSR.getString(oCSR.getColumnIndex("name")) + " ";
}
}
return sTables;
}
//getDB - returns the oDB object if you need it.
public SQLiteDatabase getDB() {
return oDB;
}
//insertStock
public long insertStock(String sSymbol) {
ContentValues oCV = new ContentValues();
oCV.put("STOCK_SYMBOL", sSymbol);
oCV.put("PRICE_DATE", "2456197");
oCV.put("STOCK_PRICE", "12.34");
long lRowID = oDB.insert("HISTORICAL_STOCK_PRICES", null, oCV);
return lRowID;
}
//enumerateStocks
public String enumerateStocks() {
//use oDB since the database is already opened.
String sStocks = "";
String sSQL = "SELECT DISTINCT STOCK_SYMBOL" +
" FROM HISTORICAL_STOCK_PRICES" +
" ORDER BY STOCK_SYMBOL";
//Get a cursor
Cursor oCSR = oDB.rawQuery(sSQL,null);
//Loop for each row in the cursor to create a large string of stock symbols
if (oCSR.getCount() > 0) {
while(oCSR.moveToNext()) {
sStocks += oCSR.getString(oCSR.getColumnIndex("STOCK_SYMBOL")) + " ";
}
}
return sStocks;
}
//close
@Override
public void close() {
oDB.close();
super.close();
}
}
//p.275
//Instantiate the MySQLiteOpenHelper class
MySQLiteOpenHelper oMSOH =
new MySQLiteOpenHelper(this,
"/data/data/com.example.andapp1/MySQLite3TestDB2.db3",
null,
1);
//Open the database in read/write mode.
oMSOH.getWritableDatabase();
//Get a list of tables in the database and display them.
String sTables = oMSOH.enumerateTables();
Toast toast=Toast.makeText(getApplicationContext(),"SQL Tables="+sTables, Toast.LENGTH_LONG);
toast.show();
//p.275
//insert a stock symbol into HISTORICAL_STOCK_PRICES
oMSOH.insertStock("YYYY");
//Get a list of stocks in the HISTORICAL_STOCK_PRICES table and display them.
String sStocks = oMSOH.enumerateStocks();
toast=Toast.makeText(getApplicationContext(),"Stock Symbols="+sStocks, Toast.LENGTH_LONG);
toast.show();
//p.275
//close the database
oMSOH.close();
//p.276
oMSOH.getWritableDatabase().execSQL(sql);
//p.276
//MUST ADD android_metadata table into database!
CREATE TABLE android_metadata (locale TEXT);
INSERT INTO android_metadata VALUES('en_US');
//p.276
oSQLiteDB = SQLiteDatabase.openDatabase("/data/data/pkg-name/dbname",
null,
SQLiteDatabase.NO_LOCALIZED_COLLATORS);
//p.277
oSQLiteDB = SQLiteDatabase.openDatabase("/data/data/pkg-name/dbname",
null,
SQLiteDatabase.NO_LOCALIZED_COLLATORS |
SQLiteDatabase.OPEN_READONLY);
//*------------------------------------------------------------------------------------*
//* Chapter 15: Content Providers - pg 278 *
//*------------------------------------------------------------------------------------*
//p.279
content://com.example.andapp1.provider/stocksymbols
content://com.example.andapp1.provider/stocksymbols/#
//p.279
vnd.android.cursor.dir/vnd.com.example.andapp1.provider.stocksymbols
vnd.android.cursor.item/vnd.com.example.andapp1.provider.stocksymbols
//p.281
scheme://authority/path?query#fragment
//p.281
Uri uContentUri =
Uri.parse("content://com.example.andapp1.provider/stocksymbols");
//p.281
// content://com.example.andapp1.provider/stocksymbols
String sContentUri = uContentUri.toString();
// content
String sScheme= uContentUri.getScheme();
// com.example.andapp1.provider
String sAuthority = uContentUri.getAuthority();
// /stocksymbols
String sPath = uContentUri.getPath();
// stocksymbols
String sLastPath = uContentUri.getLastPathSegment();
//p.281
Uri uContentUri =
Uri.parse("content://com.example.andapp1.provider/stocksymbols/amex");
List lPaths = uContentUri.getPathSegments();
//process each path segment using a for loop
for(String sThisPath : lPaths) {
//Process code using sThisPath
//First time through loop, sThisPath=stocksymbols
//Second time through loop, sThisPath=amex
}
//p.281
Uri uContentUri_ExchangeSpecific = Uri.withAppendedPath(uContentUri, "nyse");
//p.282
Uri.Builder ubContentUriBuilder = new Uri.Builder();
//p.282
// content
ubContentUriBuilder.scheme(sScheme);
// com.example.andapp1.provider
ubContentUriBuilder.authority(sAuthority);
// stocksymbols
ubContentUriBuilder.path(sLastPath);
//p.282
ubContentUriBuilder.build();
//p.282
Uri.Builder ubContentFromUri = uContentUri.buildUpon();
//p.282
ubContentFromUri.appendPath("nyse");
//p.283
Uri uContentUri =
Uri.parse("content://com.example.andapp1.provider/stocksymbols");
Uri uContentUriWithID = ContentUris.withAppendedId(uContentUri, 4);
//p.283
long lID = ContentUris.parseId(uContentUriWithID);
//p.283
//All stock symbols from all exchanges
private static final int STOCK_SYMBOLS_ALL = 1;
//All stock symbols for stock symbol _ID
private static final int STOCK_SYMBOLS_ALL_ID = 2;
//NYSE stock symbols only
private static final int STOCK_SYMBOLS_NYSE = 3;
//NYSE for stock symbol _ID
private static final int STOCK_SYMBOLS_NYSE_ID = 4;
//NASDAQ stock symbols only
private static final int STOCK_SYMBOLS_NASDAQ = 5;
//NASDAQ for stock symbol _ID
private static final int STOCK_SYMBOLS_NASDAQ_ID = 6;
//AMEX stock symbols only
private static final int STOCK_SYMBOLS_AMEX = 7;
//AMEX for stock symbol _ID
private static final int STOCK_SYMBOLS_AMEX_ID = 8;
//p.284
//Initial by passing NO_MATCH
UriMatcher umStock = new UriMatcher(UriMatcher.NO_MATCH);
umStock.addURI("com.example.andapp1.provider",
"stocksymbols",
STOCK_SYMBOLS_ALL);
umStock.addURI("com.example.andapp1.provider",
"stocksymbols/nyse",
STOCK_SYMBOLS_NYSE);
umStock.addURI("com.example.andapp1.provider",
"stocksymbols/nasdaq",
STOCK_SYMBOLS_NASDAQ);
umStock.addURI("com.example.andapp1.provider",
"stocksymbols/amex",
STOCK_SYMBOLS_AMEX);
umStock.addURI("com.example.andapp1.provider",
"stocksymbols/#",
STOCK_SYMBOLS_ALL_ID);
umStock.addURI("com.example.andapp1.provider",
"stocksymbols/nyse/#",
STOCK_SYMBOLS_NYSE_ID);
umStock.addURI("com.example.andapp1.provider",
"stocksymbols/nasdaq/#",
STOCK_SYMBOLS_NASDAQ_ID);
umStock.addURI("com.example.andapp1.provider",
"stocksymbols/amex/#",
STOCK_SYMBOLS_AMEX_ID);
//p.284
Uri uContentUri =
Uri.parse("content://com.example.andapp1.provider/stocksymbols/amex/5");
//p.284-285
String sType = "";
switch(umStock.match(uContentUri)) {
case STOCK_SYMBOLS_ALL:
sType="vnd.android.cursor.dir/stocksymbol";
break;
case STOCK_SYMBOLS_NYSE:
sType="vnd.android.cursor.dir/stocksymbol/nyse";
break;
case STOCK_SYMBOLS_NASDAQ:
sType="vnd.android.cursor.dir/stocksymbol/nasdaq";
break;
case STOCK_SYMBOLS_AMEX:
sType="vnd.android.cursor.dir/stocksymbol/amex";
break;
case STOCK_SYMBOLS_ALL_ID:
sType="vnd.android.cursor.item/stocksymbol/#";
break;
case STOCK_SYMBOLS_NYSE_ID:
sType="vnd.android.cursor.item/stocksymbol/nyse/#";
break;
case STOCK_SYMBOLS_NASDAQ_ID:
sType="vnd.android.cursor.item/stocksymbol/nasdaq/#";
break;
case STOCK_SYMBOLS_AMEX_ID:
sType="vnd.android.cursor.item/stocksymbol/amex/#";
break;
default:
sType = "???";
break;
}
//p.286-287
DROP TABLE STOCK_SYMBOLS;
CREATE TABLE STOCK_SYMBOLS(_ID INTEGER PRIMARY KEY AUTOINCREMENT,
STOCK_SYMBOL TEXT,
COMPANY_NAME TEXT);
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'MMM','3M');
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'AA','ALCOA');
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'AXP','AMERICAN EXPRESS');
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'T','AT&T');
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'BAC','BANK OF AMERICA');
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'BA','BOEING');
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'CAT','CATERPILLAR');
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'CVX','CHEVRON');
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'KO','COCA-COLA');
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'CSCO','CISCO SYSTEMS');
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'DIS','DISNEY');
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'DD','DU PONT');
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'XOM','EXXON MOBIL');
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'GE','GENERAL ELECTRIC');
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'HPQ','HEWLETT-PACKARD');
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'HD','HOME DEPOT');
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'IBM','IBM');
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'INTC','INTEL');
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'JNJ','JOHNSON & JOHNSON');
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'JPM','JP MORGAN CHASE');
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'UNH','UNITEDHEALTH GROUP');
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'MCD','MCDONALDS');
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'MRK','MERCK');
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'MSFT','MICROSOFT');
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'PFE','PFIZER');
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'PG','PROCTER & GAMBLE');
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'TRV','TRAVELERS');
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'UTX','UNITED TECH');
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'VZ','VERIZON COMMUNICATIONS');
INSERT INTO STOCK_SYMBOLS VALUES(NULL,'WMT','WAL-MART');
CREATE INDEX IX_STKSYMS_STKSYM ON STOCK_SYMBOLS(STOCK_SYMBOL);
ANALYZE STOCK_SYMBOLS;
DROP TABLE STOCK_STATS;
CREATE TABLE STOCK_STATS(_ID INTEGER PRIMARY KEY AUTOINCREMENT,
STOCK_SYMBOL TEXT,
LAST_TRADE_DATE INTEGER,
LAST_PRICE REAL,
VOLUME INTEGER,
MARKETCAP REAL,
PERATIO REAL,
EPS REAL,
YIELD REAL);
INSERT INTO STOCK_STATS VALUES(NULL,'AA',ROUND(JULIANDAY('2012-10-06')+0.5),9.09,19298836,9.70,131.74,0.07,1.30);
INSERT INTO STOCK_STATS VALUES(NULL,'AXP',ROUND(JULIANDAY('2012-10-06')+0.5),58.56,4761539,66.39,13.72,4.27,1.40);
…and so on…
CREATE INDEX IX_STKSTATS_STKSYM ON STOCK_STATS(STOCK_SYMBOL);
ANALYZE STOCK_STATS;
DROP VIEW vwSTOCKSTATSMATCH;
CREATE VIEW vwSTOCKSTATSMATCH AS
SELECT A.STOCK_SYMBOL,
A.COMPANY_NAME,
B.LAST_TRADE_DATE,
B.LAST_PRICE,
B.VOLUME,
B.MARKETCAP,
B.PERATIO,
B.EPS,
B.YIELD
FROM STOCK_SYMBOLS A LEFT JOIN STOCK_STATS B
ON A.STOCK_SYMBOL=B.STOCK_SYMBOL;
//p.287-288
1. content://com.example.andapp1.provider/stocksymbols
2. content://com.example.andapp1.provider/stocksymbols/#
3. content://com.example.andapp1.provider/stockstats
4. content://com.example.andapp1.provider/stockstats/#
5. content://com.example.andapp1.provider/stockalldata
//p.288
1. vnd.android.cursor.dir/stocksymbols
2. vnd.android.cursor.item/stocksymbols
3. vnd.android.cursor.dir/stockstats
4. vnd.android.cursor.item/stockstats
5. vnd.android.cursor.dir/stockalldata
//p.288
1. private static final int STOCKSYMBOLS_ALL=1; //All stock symbols
2. private static final int STOCKSYMBOLS_ID = 2; //All stock symbols specific _ID
3. private static final int STOCKSTATS_ALL = 3; //All stock stats
4. private static final int STOCKSTATS_ID = 4; //All stock stats for specific _ID
5. private static final int STOCKALLDATA = 5; //All view data
//p.289-291
//ContractClassSTOCKSYMBOLS
package com.example.andapp1;
import android.provider.BaseColumns;
import android.net.Uri;
public final class ContractClassSTOCKSYMBOLS implements BaseColumns {
//This class should not be instantiated
private ContractClassSTOCKSYMBOLS() {
}
//Define CONTENT_AUTHORITY
public static final String CONTENT_AUTHORITY = "com.example.andapp1.provider";
//Define BASE_CONTENT_URI as a Uri object
public static final Uri BASE_CONTENT_URI = Uri.parse("content://" +
CONTENT_AUTHORITY);
//Define CONTENT_URI as a Uri object
public static final Uri CONTENT_URI = Uri.parse("content://" +
CONTENT_AUTHORITY + "/stocksymbols");
//Define CONTENT_TYPE to represent the MIME Type for all rows in the table
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/stocksymbols";
//Define CONTENT_ITEM_TYPE to represent the MIME Type for an individual row
// in the table
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/stocksymbols";
//TABLE COLUMN DEFINITIONS:
//_ID: Note that BaseColumns automatically brings in _ID set to "_id",
// so we don't have to do that!
//STOCK_SYMBOL
public static final String STOCKSYMBOL = "STOCK_SYMBOL";
//COMPANY_NAME
public static final String COMPANYNAME = "COMPANY_NAME";
}
//ContractClassSTOCKSTATS
package com.example.andapp1;
import android.provider.BaseColumns;
import android.net.Uri;
public final class ContractClassSTOCKSTATS implements BaseColumns {
//This class should not be instantiated
private ContractClassSTOCKSTATS() {
}
//Define CONTENT_AUTHORITY
public static final String CONTENT_AUTHORITY = "com.example.andapp1.provider";
//Define BASE_CONTENT_URI as a Uri object
public static final Uri BASE_CONTENT_URI = Uri.parse("content://" +
CONTENT_AUTHORITY);
//Define CONTENT_URI as a Uri object
public static final Uri CONTENT_URI = Uri.parse("content://" +
CONTENT_AUTHORITY + "/stockstats");
//Define CONTENT_TYPE to represent the MIME Type for all rows in the table
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/stockstats";
//Define CONTENT_ITEM_TYPE to represent the MIME Type for an individual row
// in the table
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/stockstats";
//TABLE COLUMN DEFINITIONS
//_ID: Note that BaseColumns automatically brings in _ID set to "_id",
// so we don't have to do that!
//STOCK_SYMBOL
public static final String STOCKSYMBOL = "STOCK_SYMBOL";
//LAST_TRADE_DATE
public static final String LASTTRADEDATE = "LAST_TRADE_DATE";
//LAST_PRICE
public static final String LASTPRICE = "LAST_PRICE";
//VOLUME
public static final String VOLUME = "VOLUME";
//MARKETCAP (in billions)
public static final String MARKETCAP = "MARKETCAP";
//PERATIO
public static final String PERATIO = "PERATIO";
//EPS
public static final String EPS = "EPS";
//YIELD (as a percent)
public static final String YIELD = "YIELD";
}
//ContractClassSTOCKALLDATA
package com.example.andapp1;
import android.provider.BaseColumns;
import android.net.Uri;
public final class ContractClassSTOCKALLDATA implements BaseColumns {
//This class should not be instantiated
private ContractClassSTOCKALLDATA() {
}
//Define CONTENT_AUTHORITY
public static final String CONTENT_AUTHORITY = "com.example.andapp1.provider";
//Define BASE_CONTENT_URI as a Uri object
public static final Uri BASE_CONTENT_URI = Uri.parse("content://" +
CONTENT_AUTHORITY);
//Define CONTENT_URI as a Uri object
public static final Uri CONTENT_URI = Uri.parse("content://" +
CONTENT_AUTHORITY + "/stockalldata");
//Define CONTENT_TYPE to represent the MIME Type for all rows in the table
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/stockalldata";
//Define CONTENT_ITEM_TYPE to represent the MIME Type for an individual row
// in the table
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/stockalldata";
//TABLE COLUMN DEFINITIONS
//_ID: Note that BaseColumns automatically brings in _ID set to "_id",
// so we don't have to do that!
//STOCK_SYMBOL
public static final String STOCKSYMBOL = "STOCK_SYMBOL";
//COMPANY_NAME
public static final String COMPANYNAME = "COMPANY_NAME";
//LAST_TRADE_DATE
public static final String LASTTRADEDATE = "LAST_TRADE_DATE";
//LAST_PRICE
public static final String LASTPRICE = "LAST_PRICE";
//VOLUME
public static final String VOLUME = "VOLUME";
//MARKETCAP (in billions)
public static final String MARKETCAP = "MARKETCAP";
//PERATIO
public static final String PERATIO = "PERATIO";
//EPS
public static final String EPS = "EPS";
//YIELD (as a percent)
public static final String YIELD = "YIELD";
}
//p.292
//All stock symbols
private static final int STOCKSYMBOLS_ALL=1;
//All stock symbols specific _ID
private static final int STOCKSYMBOLS_ID = 2;
//All stock stats
private static final int STOCKSTATS_ALL = 3;
//All stock stats for specific _ID
private static final int STOCKSTATS_ID = 4;
//All view data
private static final int STOCKALLDATA = 5;
//p.292-295
package com.example.andapp1;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.net.Uri;
import android.database.sqlite.*;
import android.database.*;
import android.content.ContentUris;
public class MyContentProviderClass extends ContentProvider {
//Database Object
private SQLiteDatabase oSQLiteDB;
//Mappings used by the addURI() method
//All stock symbols
private static final int STOCKSYMBOLS_ALL=1;
//All stock symbols specific _ID
private static final int STOCKSYMBOLS_ID = 2;
//All stock stats
private static final int STOCKSTATS_ALL = 3;
//All stock stats for specific _ID
private static final int STOCKSTATS_ID = 4;
//All view data
private static final int STOCKALLDATA = 5;
//PACKAGE_NAME
private static final String PACKAGE_NAME = "com.example.andapp1";
//CONTENT_AUTHORITY
private static final String CONTENT_AUTHORITY = "com.example.andapp1.provider";
//Database information
private static final String DATABASE_NAME = "EQUITY_DATABASE.db3";
private static final int DATABASE_VERSION = 1;
//UriMatcher used to compare requested content URI with those that are
// allowed by this content provider.
UriMatcher umStock = new UriMatcher(UriMatcher.NO_MATCH);
public MyContentProviderClass() {
}
@Override
public String getType(Uri uri) {
String sType = "";
switch(umStock.match(uri)) {
case STOCKSYMBOLS_ALL:
sType="vnd.android.cursor.dir/stocksymbol";
break;
case STOCKSYMBOLS_ID:
sType="vnd.android.cursor.item/stocksymbol/#";
break;
case STOCKSTATS_ALL:
sType="vnd.android.cursor.dir/stockstats";
break;
case STOCKSTATS_ID:
sType="vnd.android.cursor.item/stockstats/#";
break;
case STOCKALLDATA:
sType="vnd.android.cursor.dir/stockalldata";
break;
default:
sType = null;
break;
}
return sType;
}
@Override
public boolean onCreate() {
//Add content URIs to the UriMatcher object
umStock.addURI(CONTENT_AUTHORITY, "stocksymbols", STOCKSYMBOLS_ALL);
umStock.addURI(CONTENT_AUTHORITY, "stocksymbols/#", STOCKSYMBOLS_ID);
umStock.addURI(CONTENT_AUTHORITY, "stockstats", STOCKSTATS_ALL);
umStock.addURI(CONTENT_AUTHORITY, "stockstats/#", STOCKSTATS_ID);
umStock.addURI(CONTENT_AUTHORITY, "stockalldata", STOCKALLDATA);
//Open the database. YOU MAY NEED TO MODIFY THE FIRST PARAMETER!!
oSQLiteDB = SQLiteDatabase.openDatabase(
"/data/data/" + PACKAGE_NAME + "/" + DATABASE_NAME,
null,
SQLiteDatabase.OPEN_READONLY);
return true;
}
public Cursor query(Uri uri, String[] projection,
String selection,
String[] selectionArgs,
String sortOrder) {
String sSQL = "";
String sID = "";
Cursor oCSR = null;
switch(umStock.match(uri)) {
case STOCKSYMBOLS_ALL:
sSQL = "SELECT STOCK_SYMBOL,COMPANY_NAME FROM STOCK_SYMBOLS";
if (selection != null) {
sSQL += " WHERE " + selection;
}
oCSR = oSQLiteDB.rawQuery(sSQL,null);
break;
case STOCKSYMBOLS_ID:
sID = uri.getLastPathSegment();
sSQL = "SELECT STOCK_SYMBOL,COMPANY_NAME FROM STOCK_SYMBOLS WHERE _ID= " +
sID;
oCSR = oSQLiteDB.rawQuery(sSQL,null);
break;
case STOCKSTATS_ALL:
sSQL = "SELECT STOCK_SYMBOL,LAST_TRADE_DATE,LAST_PRICE,VOLUME,MARKETCAP," +
"PERATIO, EPS, YIELD FROM STOCK_STATS";
if (selection != null) {
sSQL += " WHERE STOCK_SYMBOL='" + selection + "'";
}
oCSR = oSQLiteDB.rawQuery(sSQL,null);
break;
case STOCKSTATS_ID:
sID = uri.getLastPathSegment();
sSQL = "SELECT STOCK_SYMBOL,LAST_TRADE_DATE,LAST_PRICE,VOLUME,MARKETCAP," +
"PERATIO,EPS,YIELD FROM STOCK_STATS WHERE _ID=" + sID;
oCSR = oSQLiteDB.rawQuery(sSQL,null);
break;
case STOCKALLDATA:
sSQL = "SELECT STOCK_SYMBOL,COMPANY_NAME,LAST_TRADE_DATE,LAST_PRICE," +
"VOLUME,MARKETCAP,PERATIO,EPS,YIELD FROM vwSTOCKSTATSMATCH";
oCSR = oSQLiteDB.rawQuery(sSQL,null);
break;
}
//Ensure that if there is a change in the database, then the content
// resolver is notified!!
if (oCSR != null) {
oCSR.setNotificationUri(getContext().getContentResolver(), uri);
}
return oCSR;
}
//These methods are not implemented in our test program!
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
return null;
}
@Override
public int update(Uri uri,
ContentValues values,
String selection,
String[] selectionArgs) {
return 0;
}
}
//p.295
.provider.permission.
//p.295
com.example.andapp1.provider.permission.READ_PROVIDER
//p.295-296
//p.296
//p.297
//p.298-299
package com.example.andapp2;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.content.ContentResolver;
import android.database.Cursor;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Add a listener for the click event of button1.
((Button) findViewById(R.id.button1)).setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
Toast toast;
String sStockSymbol;
String sStockName;
String sStock;
//content resolver code goes here
ContentResolver oCR_EQDB = getContentResolver();
//Create a cursor to the data
Cursor oCSR = oCR_EQDB.query(
ContractClassSTOCKSYMBOLS.CONTENT_URI,
new String[] {ContractClassSTOCKSYMBOLS.STOCKSYMBOL,
ContractClassSTOCKSYMBOLS.COMPANYNAME},
null,
null,
null);
//Show toasts for each of the entries
if (oCSR.getCount() > 0) {
while(oCSR.moveToNext()) {
sStockSymbol = oCSR.getString(
oCSR.getColumnIndex(ContractClassSTOCKSYMBOLS.STOCKSYMBOL));
sStockName = oCSR.getString(
oCSR.getColumnIndex(ContractClassSTOCKSYMBOLS.COMPANYNAME));
sStock = sStockSymbol + "/" + sStockName;
toast = Toast.makeText(getApplicationContext(),
sStock,
Toast.LENGTH_SHORT);
toast.show();
}
}
}
}
);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
//p.303-304
public class MainActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get a cursor to the stock symbol/company name in STOCK_SYMBOLS
ContentResolver oCR_EQDB = getContentResolver();
Cursor oCSR = oCR_EQDB.query(
ContractClassSTOCKSYMBOLS.CONTENT_URI,
new String[] {ContractClassSTOCKSYMBOLS._ID,
ContractClassSTOCKSYMBOLS.STOCKSYMBOL,
ContractClassSTOCKSYMBOLS.COMPANYNAME},
null, null, null);
//Manage the cursor
startManagingCursor(oCSR);
//List of columns to be displayed in the List View
String[] sDisplayColumns = new String[] {ContractClassSTOCKSYMBOLS.STOCKSYMBOL,
ContractClassSTOCKSYMBOLS.COMPANYNAME};
//Create an integer array to hold the IDs of android.R.id.text1
// and android.R.id.text2. Note that they are in the same order as
// the columns that appear in sDisplayColumns.
int[] iLayoutIDs = new int[] {android.R.id.text1,android.R.id.text2};
//Set up a cursor adapter for the ListView using oCSR
SimpleCursorAdapter oSCAdapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
oCSR,
sDisplayColumns,
iLayoutIDs);
//Set the list adapter to our simple cursor adapter oSCAdapter.
setListAdapter(oSCAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
String sID = Long.toString(id);
Toast toast = Toast.makeText(getApplicationContext(),
"_ID=" + sID,
Toast.LENGTH_SHORT);
toast.show();
}
}
//p.304-306
public class MainActivity extends ExpandableListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get a cursor to the stock symbol/company name in STOCK_SYMBOLS
Cursor parentCursor = getContentResolver().query(
ContractClassSTOCKSYMBOLS.CONTENT_URI,
new String[] {ContractClassSTOCKSYMBOLS._ID,
ContractClassSTOCKSYMBOLS.STOCKSYMBOL,
ContractClassSTOCKSYMBOLS.COMPANYNAME},
null, null, null);
//Manage the cursor
startManagingCursor(parentCursor);
//PARENT: List of columns to be displayed in the List View
String[] sGroupFrom = new String[] {ContractClassSTOCKSYMBOLS.STOCKSYMBOL};
//PARENT: Create an integer array to hold the IDs of android.R.id.text1
// and android.R.id.text2. Note that they are in the same order as the
// columns that appear in sDisplayColumns.
int[] iGroupTo = new int[] {android.R.id.text1};
//CHILD: List of columns to be displayed in the List View
String[] sChildFrom = new String[] {ContractClassSTOCKSTATS.LASTPRICE,
ContractClassSTOCKSTATS.VOLUME};
//CHILD: Create an integer array to hold the IDs of android.R.id.text1
// and android.R.id.text2. Note that they are in the same order as the
// columns that appear in sDisplayColumns.
int[] iChildTo = new int[] {android.R.id.text1,android.R.id.text2};
//Set up a cursor tree adapter for the ExpanableListView
MySimpleCursorTreeAdapter oExpandableListAdapter =
new MySimpleCursorTreeAdapter(
this,
parentCursor,
android.R.layout.simple_expandable_list_item_1,
sGroupFrom,
iGroupTo,
android.R.layout.simple_expandable_list_item_2,
sChildFrom,
iChildTo);
//Set the list adapter to our simple cursor adapter oSCAdapter.
setListAdapter(oExpandableListAdapter);
}
//Create my own subclass of the SimpleCursorTreeAdapter.
//At a minimum, you need to have the constructor super to the base and
//the method called getChildrenCursor which returns a cursor to the child's data
//based on the parent parameter passed into it.
//Note that SimpleCursorTreeAdapter implements ExpandableListAdapter, so the
//code above will work.
public class MySimpleCursorTreeAdapter extends SimpleCursorTreeAdapter {
//Constructor passes onto base constructor
public MySimpleCursorTreeAdapter(Context context,
Cursor cursor,
int groupLayout,
String[] groupFrom,
int[] groupTo,
int childLayout,
String[] childFrom,int[] childto) {
super(context,cursor,groupLayout,groupFrom,
groupTo,childLayout,childFrom,childto);
}
//getChildrenCursor
@Override
protected Cursor getChildrenCursor(Cursor parentCursor) {
//Get the _ID from the parentCursor (the STOCK_SYMBOLS table)
long parentID = parentCursor.getLong(
parentCursor.getColumnIndex(ContractClassSTOCKSYMBOLS._ID));
//Get a cursor for the child's data based on the parent's _ID. Note that there
// must be a correspondence of the _ID's between the STOCK_SYMBOLS table and
// the STOCK_STATS table. I ensured that there was, but that might not always
// be the case. If not, then pull the child's data based on the stock symbol
// instead.
//Create a new Uri from the CONTENT_URI for the STOCK_STATS table by appending
// the parent _ID to it.
Uri uriWithParentID =
Uri.withAppendedPath(ContractClassSTOCKSTATS.CONTENT_URI,
Long.toString(parentID));
//Query the table STOCK_STATS
Cursor childCursor = getContentResolver().query(
uriWithParentID,
new String[] {ContractClassSTOCKSTATS._ID,
ContractClassSTOCKSTATS.STOCKSYMBOL,
ContractClassSTOCKSTATS.LASTTRADEDATE,
ContractClassSTOCKSTATS.VOLUME},
null, null, null);
//Manage the cursor
startManagingCursor(childCursor);
//return the child cursor
return childCursor;
}
}
}
//*------------------------------------------------------------------------------------*
//* Chapter 16: Styles and Themes - pg 308 *
//*------------------------------------------------------------------------------------*
//p.308
//p.308
//p.309
//p.309
//p.309-310
//p.310
//p.310
//p.311
...
//p.311
...
//p.311
...
//p.311
//p.312
//p.312
//p.313
//Get reference to the ListView
ListView oLV = (ListView) findViewById(android.R.id.list);
//Create a new ColorDrawable to represent our color.
ColorDrawable oRedAlert = new
ColorDrawable(this.getResources().getColor(R.color.red_alert));
//Set the color of the ListView's divider to our color red_alert.
oLV.setDivider(oRedAlert);
//Since a color does not have an "intrinsic" height, unlike an image,
//you must set the height of the divider to 3 pixels.
oLV.setDividerHeight(3);
//p.314
#FF0000
//p.314
//p.314-315
//*------------------------------------------------------------------------------------*
//* Chapter 17: Adapters - pg 316 *
//*------------------------------------------------------------------------------------*
//p.317
TextView oTxtVw = (TextView) findViewById(R.id.text-view-id);
oTxtVw.setText("your-text-goes-here");
//p.317-318
//p.318
String[] sArray = {"INTC","MSFT","GOOG","CSCO","FB"};
//p.318
//Create an array to hold all of the stocks.
//These are entered in by hand.
String[] sArray = {"INTC","MSFT","GOOG","CSCO","FB"};
//Set up an object to the ListView
ListView oLV = (ListView) findViewById(R.id.lvSS);
//Set up the ArrayAdapter
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1,
sArray);
//Load the array data into the ListView
oLV.setAdapter(adapter);
//p.318
String[] sArray = getResources().getStringArray(R.array.your-array-name);
//p.318
//p.319
//Set up the ArrayAdapter
ArrayAdapter adapter = new ArrayAdapter(this,
R.layout.mytextview,
sArray);
//p.319
public class MyClass {
String sText = "";
public MyClass(String pText) {
sText = pText;
}
@Override
public String toString() {
return "New York Stock Exchange: " + sText;
}
}
//p.319
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Create an array to hold all of the stocks.
MyClass[] sArray = new MyClass[5];
sArray[0] = new MyClass("INTC");
sArray[1] = new MyClass("MSFT");
sArray[2] = new MyClass("GOOG");
sArray[3] = new MyClass("CSCO");
sArray[4] = new MyClass("FB");
//Set up an object to the ListView
ListView oLV = (ListView) findViewById(R.id.lvSS);
//Set up the ArrayAdapter
ArrayAdapter adapter = new
ArrayAdapter(this,R.layout.mytextview,sArray);
//Load the array data into the ListView
oLV.setAdapter(adapter);
}
//p.320
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class StockAdapter extends ArrayAdapter {
private String[] sArray;
private Context context;
public StockAdapter(Context context, int textViewResourceId,String[] objects) {
super(context, textViewResourceId, objects);
this.sArray = objects;
this.context = context;
}
public int getCount() {
return sArray.length;
}
@Override
public String getItem(int position) {
return sArray[position];
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
//If convertView is null, inflate it with mytextview.
if (view == null) {
LayoutInflater inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Inflate the layout.
view = inflater.inflate(R.layout.mytextview, null);
}
//Get the current item based on the position passed in
String sItem = sArray[position];
//Create a variable to point to our TextView tvSS.
TextView oTVSS = (TextView) view.findViewById(R.id.tvSS);
//Set the text to whatever you want in mytextview
oTVSS.setText("Nasdaq Stock Exchange Symbol: " + sItem);
return view;
}
}
//p.321
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Create an array to hold all of the stocks.
//These are entered in by hand.
String[] sArray = {"AAAA","BBBB","CCCC","DDDD","EEEE","FFFF","GGGG","HHHH"};
//Set up an object to the ListView
ListView oLV = (ListView) findViewById(R.id.lvSS);
//Set up the ArrayAdapter using our StockAdapter class instead
StockAdapter adapter = new StockAdapter(this,R.layout.mytextview,sArray);
//Load the array data into the ListView
oLV.setAdapter(adapter);
}
//p.321-322
//Get a cursor to the stock symbol/company name in STOCK_SYMBOLS
ContentResolver oCR_EQDB = getContentResolver();
Cursor oCSR = oCR_EQDB.query(
ContractClassSTOCKSYMBOLS.CONTENT_URI,
new String[] {ContractClassSTOCKSYMBOLS._ID,
ContractClassSTOCKSYMBOLS.STOCKSYMBOL,
ContractClassSTOCKSYMBOLS.COMPANYNAME},
null, null, null);
//Manage the cursor
startManagingCursor(oCSR);
//List of columns to be displayed in the List View
String[] sDisplayColumns = new String[] {ContractClassSTOCKSYMBOLS.STOCKSYMBOL,
ContractClassSTOCKSYMBOLS.COMPANYNAME};
//Create an integer array to hold the IDs of android.R.id.text1 and
// android.R.id.text2. Note that they are in the same order as the columns
// that appear in sDisplayColumns.
int[] iLayoutIDs = new int[] {android.R.id.text1,android.R.id.text2};
//Set up a cursor adapter for the ListView using oCSR
SimpleCursorAdapter oSCAdapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
oCSR,
sDisplayColumns,
iLayoutIDs);
//Set the list adapter to our simple cursor adapter oSCAdapter.
setListAdapter(oSCAdapter);
//p.322-324
public class MainActivity extends ExpandableListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get a cursor to the stock symbol/company name in STOCK_SYMBOLS
Cursor parentCursor = getContentResolver().query(
ContractClassSTOCKSYMBOLS.CONTENT_URI,
new String[] {ContractClassSTOCKSYMBOLS._ID,
ContractClassSTOCKSYMBOLS.STOCKSYMBOL,
ContractClassSTOCKSYMBOLS.COMPANYNAME},
null, null, null);
//Manage the cursor
startManagingCursor(parentCursor);
//PARENT: List of columns to be displayed in the List View
String[] sGroupFrom = new String[] {ContractClassSTOCKSYMBOLS.STOCKSYMBOL};
//PARENT:Create an integer array to hold the IDs of android.R.id.text1 and
// android.R.id.text2. Note that they are in the same order as the columns
// that appear in sDisplayColumns.
int[] iGroupTo = new int[] {android.R.id.text1};
//CHILD: List of columns to be displayed in the List View
String[] sChildFrom = new String[] {ContractClassSTOCKSTATS.LASTPRICE,
ContractClassSTOCKSTATS.VOLUME};
//CHILD:Create an integer array to hold the IDs of android.R.id.text1 and
// android.R.id.text2. Note that they are in the same order as the columns
// that appear in sDisplayColumns.
int[] iChildTo = new int[] {android.R.id.text1,android.R.id.text2};
//Set up a cursor tree adapter for the ExpandableListView
MySimpleCursorTreeAdapter oExpandableListAdapter = new
MySimpleCursorTreeAdapter(this,
parentCursor,
android.R.layout.simple_expandable_list_item_1,
sGroupFrom,
iGroupTo,
android.R.layout.simple_expandable_list_item_2,
sChildFrom,
iChildTo);
//Set the list adapter to our simple cursor adapter oSCAdapter.
setListAdapter(oExpandableListAdapter);
}
//Create my own subclass of the SimpleCursorTreeAdapter.
//At a minimum, you need to have the constructor super to the base and
//the method called getChildrenCursor which returns a cursor to the child's data
//based on the parent parameter passed into it.
//Note that SimpleCursorTreeAdapter implements ExpandableListAdapter, so the
//code above will work.
public class MySimpleCursorTreeAdapter extends SimpleCursorTreeAdapter {
//Constructor passes onto base constructor
public MySimpleCursorTreeAdapter(Context context,
Cursor cursor,
int groupLayout,
String[] groupFrom,
int[] groupTo,
int childLayout,
String[] childFrom,
int[] childto) {
super(context,cursor,groupLayout,groupFrom,groupTo,
childLayout,childFrom,childto);
}
//getChildrenCursor
@Override
protected Cursor getChildrenCursor(Cursor parentCursor) {
//Get the _ID from the parentCursor (the STOCK_SYMBOLS table)
long parentID = parentCursor.getLong(
parentCursor.getColumnIndex(ContractClassSTOCKSYMBOLS._ID));
//Get a cursor for the child's data based on the parent's _ID. Note that there
// must be a correspondence of the _ID's between the STOCK_SYMBOLS table and
// the STOCK_STATS table. I ensured that there was, but that might not always
// be the case. If not, then pull the child's data based on the stock
// symbol instead.
//Create a new Uri from the CONTENT_URI for the STOCK_STATS table by appending
// the parent _ID to it.
Uri uriWithParentID = Uri.withAppendedPath(
ContractClassSTOCKSTATS.CONTENT_URI,
Long.toString(parentID));
//Query the table STOCK_STATS
Cursor childCursor = getContentResolver().query(
uriWithParentID,
new String[] {ContractClassSTOCKSTATS._ID,
ContractClassSTOCKSTATS.STOCKSYMBOL,
ContractClassSTOCKSTATS.LASTTRADEDATE,
ContractClassSTOCKSTATS.VOLUME},
null, null, null);
//Manage the cursor
startManagingCursor(childCursor);
//return the child cursor
return childCursor;
}
}
}
//p.325-326
import java.text.DecimalFormat;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
import android.widget.ResourceCursorTreeAdapter;
import android.widget.TextView;
public class MyResourceCursorTreeAdapter extends ResourceCursorTreeAdapter {
//Create a private variable for a SQLite Database
private SQLiteDatabase oSQLiteDB;
public MyResourceCursorTreeAdapter(SQLiteDatabase pSQLiteDB,
Context context, Cursor cursor,
int igroupLayout,
int ichildLayout) {
super(context, cursor, igroupLayout, ichildLayout);
//Set the SQLiteDB object to the open database from the main activity.
oSQLiteDB = pSQLiteDB;
}
@Override
protected void bindChildView(View view,
Context context,
Cursor childCursor,
boolean isLastChild) {
//Retrieve the last trade date and volume from the cursor
String sLastPrice = "Last Price: " + childCursor.getString(
childCursor.getColumnIndex("LAST_PRICE"));
int iVolume = childCursor.getInt(childCursor.getColumnIndex("VOLUME"));
//Format the volume to be comma-delimited.
DecimalFormat oNF = new DecimalFormat("###,###,###,###");
String sVolume = "Volume: " + oNF.format(iVolume);
//Gain access to the two text views for the child
TextView oLastPrice = (TextView) view.findViewById(android.R.id.text1);
TextView oVolume = (TextView) view.findViewById(android.R.id.text2);
//Change the font size
oLastPrice.setTextSize(10);
oVolume.setTextSize(10);
//Set the two text views to the last trade date and the volume
oLastPrice.setText(sLastPrice);
oVolume.setText(sVolume);
}
@Override
protected void bindGroupView(View view,
Context context,
Cursor parentCursor,
boolean isExpanded) {
//Get the stock symbol from the parent cursor
String sStockSymbol = "Symbol: " + parentCursor.getString(
parentCursor.getColumnIndex("STOCK_SYMBOL"));
//Gain access to the single TextView that displays the stock symbol
TextView oStockSymbol = (TextView) view.findViewById(android.R.id.text1);
//Set the text in the TextView.
oStockSymbol.setText(sStockSymbol);
}
@Override
protected Cursor getChildrenCursor(Cursor parentCursor) {
//Get the _ID from the parentCursor (the STOCK_SYMBOLS table)
long parentID = parentCursor.getLong(parentCursor.getColumnIndex("_id"));
//Create the SQL string to pull data from the database for this parent _ID.
String sSQL = "SELECT _id,STOCK_SYMBOL,LAST_PRICE,VOLUME FROM STOCK_STATS " +
" WHERE _ID=" + Long.toString(parentID);
//Pull the data from the database into a cursor
Cursor childCursor = oSQLiteDB.rawQuery(sSQL,null);
//return the child cursor
return childCursor;
}
}
//p.326-327
package com.example.andapp6;
import android.os.Bundle;
import android.app.ExpandableListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class MainActivity extends ExpandableListActivity {
private SQLiteDatabase oSQLiteDB;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Open up the database
oSQLiteDB = SQLiteDatabase.openDatabase(
"/data/data/com.example.andapp6/EQUITY_DATABASE.db3",
null,
SQLiteDatabase.OPEN_READONLY);
//Get a cursor to the stock symbol/company name in STOCK_SYMBOLS
String sSQL = "SELECT _id,STOCK_SYMBOL FROM STOCK_SYMBOLS";
Cursor parentCursor = oSQLiteDB.rawQuery(sSQL,null);
//Manage the cursor
startManagingCursor(parentCursor);
//Instantiate the class MyResourceCursorTreeAdapter
MyResourceCursorTreeAdapter oExpandableListAdapter =
new MyResourceCursorTreeAdapter(
oSQLiteDB,
this,
parentCursor,
android.R.layout.simple_expandable_list_item_1,
android.R.layout.simple_expandable_list_item_2);
//Set the expandable list adapter to our resource cursor tree adapter.
setListAdapter(oExpandableListAdapter);
}
}
//p.327-328
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Instantiate the Spinner as an object
Spinner oSP = (Spinner) findViewById(R.id.spinner1);
//Set up an ArrayAdapter from the array to the spinner. The layout
// simple_spinner_item is used to display a single item in the spinner.
// This has nothing to do with how the spinner displays multiple items
// when the drop-down arrow is clicked. See below.
ArrayAdapter adapter =
ArrayAdapter.createFromResource(this,
R.array.DJIA,
android.R.layout.simple_spinner_item);
//Indicate which layout to use when the drop-down arrow is clicked.
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Assign adapter as the adapter to the spinner.
oSP.setAdapter(adapter);
}
//p.329
//p.329-330
private SQLiteDatabase oSQLiteDB;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Open up the database…YOU MAY HAVE TO CHANGE THE FIRST PARAMETER!!
oSQLiteDB = SQLiteDatabase.openDatabase(
"/data/data/com.example.andapp7/EQUITY_DATABASE.db3",
null,
SQLiteDatabase.OPEN_READONLY);
//Set up SQL query and query the database.
String sSQL = "SELECT _id,STOCK_SYMBOL FROM STOCK_SYMBOLS " +
"ORDER BY STOCK_SYMBOL DESC";
Cursor cursorStocks = oSQLiteDB.rawQuery(sSQL,null);
//Manage the cursor
startManagingCursor(cursorStocks);
//Instantiate the Spinner as an object
Spinner oSP = (Spinner) findViewById(R.id.spinner1);
//Set up a cursor adapter for the ListView using oCSR
SimpleCursorAdapter adapter =
new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item,
cursorStocks,
new String[] {"STOCK_SYMBOL"},
new int[] {android.R.id.text1},0);
//Indicate which layout to use when the drop-down arrow is clicked.
adapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
//Assign adapter as the adapter to the spinner.
oSP.setAdapter(adapter);
}
//*------------------------------------------------------------------------------------*
//* Chapter 18: Distributing Your Android Application - pg 331 *
//*------------------------------------------------------------------------------------*
//p.331
keytool -genkeypair -v -keystore com_example_andapp1.keystore -alias com_example_andapp1 -keyalg RSA -keysize 2048 -validity 10000
//p.332
keytool -list -keystore com_example_andapp1.keystore
//*------------------------------------------------------------------------------------*
//* Chapter 19: Broadcasting Events - pg 341 *
//*------------------------------------------------------------------------------------*
//p.341
//Create our broadcast event string
public static final String DATABASE_UPDATED_ACTION =
"com.example.action.DATABASE_UPDATED";
//p.342
//Create an onClickListener and associate it with the button
//that will send the updated database broadcast event.
((Button) findViewById(R.id.button3)).setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
//Set up a new Intent and load it with useful information for the broadcast.
Intent oBC_EVT = new Intent(DATABASE_UPDATED_ACTION);
oBC_EVT.putExtra("UPDATED_DATABASE_LOCATION",
"/data/data/com.example.andapp1");
oBC_EVT.putExtra("UPDATED_DATABASE_FILENAME","EQUITY_DATABASE_v2.db3");
//Initiate the broadcast
sendBroadcast(oBC_EVT);
}
}
);
//p.342
//p.342-343
package com.example.andapp7;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class DatabaseUpdatedBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//If this method is executed, then the database has been updated.
//Take some useful action, buddy.
String sUPDATED_DATABASE_LOCATION =
intent.getStringExtra("UPDATED_DATABASE_LOCATION");
String sUPDATED_DATABASE_FILENAME =
intent.getStringExtra("UPDATED_DATABASE_FILENAME");
//Use a toast to show this new file on the screen.
Toast toast = Toast.makeText(context,
"New Database=" + sUPDATED_DATABASE_LOCATION
+ "/"
+ sUPDATED_DATABASE_FILENAME,
Toast.LENGTH_LONG);
toast.show();
}
}
//p.346
//p.346
//p.346
//p.346-347
//Method to start the downloading of the file
public void StartDownload(View view) {
//Get an instance of the DownloadManager Service using getSystemService()
oDM = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
//Ensure that the external folder exists
Boolean bRC = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS).mkdirs();
//Set up a download request to our file to download (stored in sFileToDownload)
DownloadManager.Request oDMReq = new DownloadManager.Request(
Uri.parse(sFileToDownload));
//Set preferred options for the DownloadManager.Request object
// Take note of the vertical bar at the end of the first line of code below!
oDMReq.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |
DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle("Download Updated Database")
.setDescription("Downloading latest updated database...")
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
"download_file.pdf");
//Add this download to the queue. When the download is complete, the
// BroadcastReceiver will be fired.
lEnqueueID = oDM.enqueue(oDMReq);
}
//p.347
//String to hold the file to download
private String sFileToDownload = "http://www.example.com/joomla/media/documents/"
+ "InstallingUnixODBCLinux.pdf";
//DownloadManager object
private DownloadManager oDM;
//The ID of the enqueued file to download
private long lEnqueueID;
//p.347-348
//Instantiate the BroadcastReceiver and override the onReceive method
BroadcastReceiver oBR = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//Get a string of the action from the intent
String sAction = intent.getAction();
//If the download has been completed, then open up the PDF file
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(sAction)) {
//Get the location of the PDF file on disk by querying
//the DownloadManager database table
Query oQuery = new Query();
oQuery.setFilterById(lEnqueueID);
Cursor oCSR = oDM.query(oQuery);
oCSR.moveToFirst();
//Get the download ID
long lDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
//Get the index within the cursor of the DownloadManager's
// COLUMN_STATUS column.
int iIndxColumnStatus = oCSR.getColumnIndex(DownloadManager.COLUMN_STATUS);
//If the download was successful, then pull the file location and
// display the file
if (oCSR.getInt(iIndxColumnStatus) == DownloadManager.STATUS_SUCCESSFUL) {
String uriString = oCSR.getString(
oCSR.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
Log.d("MYAPPTAG",uriString);
//Set up the intent with a default action of ACTION_VIEW.
Intent intentShowPDF = new Intent(Intent.ACTION_VIEW);
intentShowPDF.setDataAndType(Uri.parse(uriString), "application/pdf");
//Display the PDF.
startActivity(intentShowPDF);
}
}
}
};
//p.348
//Register our BroadcastReceiver to be fired when the download has completed.
registerReceiver(oBR,
new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
//p.348
String uriString =
oCSR.getString(oCSR.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
//p.348
file:///mnt/sdcard/Download/download_file.pdf
//p.349-350
package com.example.andappA;
import java.io.File;
import java.io.FileNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Query;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
//String to hold the file to download
private String sFileToDownload="http://www.example.com/joomla/media/documents/"
+ "InstallingUnixODBCLinux.pdf";
//DownloadManager object
private DownloadManager oDM;
//The ID of the enqueued file to download
private long lEnqueueID;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Update txtFileToDownload to display the file we will download
TextView oTV = (TextView) findViewById(R.id.txtFileToDownload);
oTV.setText(sFileToDownload);
//Instantiate the BroadcastReceiver and override the onReceive method
BroadcastReceiver oBR = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//Get a string of the action from the intent
String sAction = intent.getAction();
//If the download has been completed, then open up the PDF file
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(sAction)) {
//Get the location of the PDF file on disk by querying
//the DownloadManager database table
Query oQuery = new Query();
oQuery.setFilterById(lEnqueueID);
Cursor oCSR = oDM.query(oQuery);
oCSR.moveToFirst();
//Get the download ID
long lDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,0);
//Get the index within the cursor of the DownloadManager's
// COLUMN_STATUS column.
int iIndxColumnStatus = oCSR.getColumnIndex(DownloadManager.COLUMN_STATUS);
//If the download was successful, then pull the file location and
// display the file
if (oCSR.getInt(iIndxColumnStatus) == DownloadManager.STATUS_SUCCESSFUL) {
String uriString = oCSR.getString(
oCSR.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
Log.d("MYAPPTAG",uriString);
//Set up the intent with a default action of ACTION_VIEW.
Intent intentShowPDF = new Intent(Intent.ACTION_VIEW);
intentShowPDF.setDataAndType(Uri.parse(uriString), "application/pdf");
//Display the PDF.
startActivity(intentShowPDF);
}
}
}
};
//Register our BroadcastReceiver to be fired when the download has completed.
registerReceiver(oBR,
new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
//Method to start the downloading of the file
public void StartDownload(View view) {
//Get an instance of the DownloadManager Service using getSystemService()
oDM = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
//Ensure that the folder exists
Boolean bRC = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS).mkdirs();
//Set up a download request to our file to download
DownloadManager.Request oDMReq = new DownloadManager.Request(
Uri.parse(sFileToDownload));
//Set preferred options for the DownloadManager.Request object
oDMReq.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |
DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle("Download Updated Database")
.setDescription("Downloading latest updated database...")
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
"download_file.pdf");
//Add this download to the queue. When the download is complete the
// BroadcastReceiver will be fired.
lEnqueueID = oDM.enqueue(oDMReq);
}
}
//*------------------------------------------------------------------------------------*
//* Chapter 20: Services - pg 351 *
//*------------------------------------------------------------------------------------*
//p.353-354
package com.example.andapp1;
import java.util.Random;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyServiceClass extends Service {
private String[] saMsgs = {"RED ALERT!","YELLOW ALERT!",
"BLUE ALERT!","ORANGE ALERT!","MAUVE ALERT!"};
private Toast toast;
private int iRndNbr;
private Random oRandom;
private int iStartID;
@Override
public void onCreate() {
//Initialize the random number
oRandom = new Random();
iRndNbr = oRandom.nextInt(5);
}
@Override
public void onDestroy() {
saMsgs = null;
toast = null;
oRandom = null;
}
@Override
public int onStartCommand(Intent intent,int flags, int startId) {
//Save the startId for this service
iStartID = startId;
//Get a random number from 0 to 4 for use in deciding which message to toast.
iRndNbr = oRandom.nextInt(5);
//Show a random toast
toast = Toast.makeText(this, saMsgs[iRndNbr], Toast.LENGTH_SHORT);
toast.show();
return Service.START_STICKY;
}
public void onTrimMemory(int level) {
//Reduce memory usage, if possible.
}
@Override
public void onLowMemory() {
//Reduce memory usage, if possible.
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
//p.354
//p.354
//Create an intent to our service
final Intent intent = new Intent(this,MyServiceClass.class);
//Create an onClickListener to start the service
((Button) findViewById(R.id.btnStartService)).setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
startService(intent);
}
}
);
//p.354
stopService(intent);
//p.355
stopSelf(iStartID);
//p.355-356
import java.util.Random;
import android.app.IntentService;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class MyIntentServiceClass extends IntentService {
private String[] saMsgs = {"RED ALERT!","YELLOW ALERT!",
"BLUE ALERT!","ORANGE ALERT!","MAUVE ALERT!"};
private Toast toast;
private int iRndNbr;
private Random oRandom;
private Context cntx;
public MyIntentServiceClass() {
super("MyWorkerThreadName");
}
@Override
public void onCreate() {
super.onCreate();
//Initialize the random number
oRandom = new Random();
iRndNbr = oRandom.nextInt(5);
Log.d("MYAPPTAG","In onCreate!");
}
@Override
public void onDestroy() {
saMsgs = null;
toast = null;
oRandom = null;
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent,int flags, int startId) {
Log.d("MYAPPTAG","In onStartCommand!");
return super.onStartCommand(intent, flags, startId);
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d("MYAPPTAG","In onHandleIntent!");
ShowToasties();
}
private void ShowToasties() {
for(int i=0;i<5;i++) {
//Get a random number from 0 to 4 for use in deciding which message to toast.
iRndNbr = oRandom.nextInt(5);
//Show a random toast
Log.d("MYAPPTAG",saMsgs[iRndNbr]);
}
}
}
//p.357
final Intent intent = new Intent(this,MyIntentServiceClass.class);
startService(intent);
//p.358
private final IBinder oBinder = new MyBinder();
//p.358-359
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
public class MyBindService extends Service {
private final IBinder oBinder = new MyBinder();
//BELOW ARE THE OVERRIDDEN METHODS OF THE SERVICE CLASS
@Override
public void onCreate() {
}
@Override
public void onDestroy() {
}
@Override
public int onStartCommand(Intent intent,int flags, int startId) {
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return oBinder;
}
//BELOW IS THE BINDER SUBCLASS
public class MyBinder extends Binder {
MyBindService getService() {
return MyBindService.this;
}
}
//ABOVE IS THE BINDER SUBCLASS
//BELOW ARE THE PUBLIC METHODS AVAILABLE TO THE BOUND SERVICE
public double LengthOfHypotenuse(double x,double y) {
return Math.sqrt(x*x + y*y);
}
}
//p.359
public void ShowLength(View v) {
if (bIsBound) {
double len = oMyBindService.LengthOfHypotenuse(3, 4);
Toast.makeText(getApplicationContext(),
"Length of Hypotenuse with sides 3 and 4=" +
Double.toString(len),
Toast.LENGTH_LONG).show();
}
}
//p.359-360
public class MainActivity extends Activity {
//Attributes used with a bound service
MyBindService oMyBindService;
boolean bIsBound = false;
// Defines callback for service binding, passed to bindService()
public ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
//We've bound to LocalService, cast the IBinder and get
// LocalService instance
MyBinder binder = (MyBinder) service;
oMyBindService = binder.getService();
bIsBound = true;
}
public void onServiceDisconnected(ComponentName className) {
bIsBound = false;
}
};
@Override
public void onStop() {
super.onStop();
//For bound service
if (bIsBound) {
unbindService(mConnection);
bIsBound = false;
}
}
@Override
protected void onStart() {
super.onStart();
// Bind to LocalService
Intent intent = new Intent(this, MyBindService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void ShowLength(View v) {
if (bIsBound) {
double len = oMyBindService.LengthOfHypotenuse(3, 4);
Toast.makeText(getApplicationContext(),
"Length of Hypotenuse with sides 3 and 4=" +
Double.toString(len),
Toast.LENGTH_LONG).show();
}
}
}
//*------------------------------------------------------------------------------------*
//* Chapter 21: The Application Class - pg 361 *
//*------------------------------------------------------------------------------------*
//p.361
//p.361-362
import android.app.Application;
import android.content.res.Configuration;
public class MyApplication extends Application {
public static MyApplication singleton;
public String sStockPick = "????";
//Returns the application instance
public static MyApplication getInstance() {
return singleton;
}
//onCreate
@Override
public final void onCreate() {
super.onCreate();
singleton=this;
}
//onTerminate
@Override
public final void onTerminate() {
super.onTerminate();
}
//onLowMemory
@Override
public final void onLowMemory() {
super.onLowMemory();
}
//onConfigurationChanged
@Override
public final void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
}
//p.362-363
//Reset the stock choice
MyApplication.singleton.sStockPick="MSFT";
//Set editText1 to the sStockPick
EditText oET = (EditText) findViewById(R.id.editText1);
oET.setText(MyApplication.singleton.sStockPick);
//Create an onClickListener to save the text to the application
//variable sStockPick
((Button) findViewById(R.id.btnSave)).setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
//Set editText1 to the sStockPick
EditText oET = (EditText) findViewById(R.id.editText1);
Editable sEditText = oET.getText();
MyApplication.singleton.sStockPick = sEditText.toString();
}
}
);
//Create an onClickListener to open activity_activity2
((Button) findViewById(R.id.btnOpenActivity2)).setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
//Open the activity_activity2 layout
Intent intent = new Intent(MainActivity.this,Activity2.class);
startActivity(intent);
}
}
);
//*------------------------------------------------------------------------------------*
//* Chapter 22: Status Notifications - pg 364 *
//*------------------------------------------------------------------------------------*
//p.365
//1. Create a unique ID for the notification
public static final int NOTIFICATION_ID_DATABASE_UPDATE_AVAIALBLE = 1;
//Generate a Status Bar Notification
public void GenerateNotification(View view) {
//2. Get a pointer to the NotificationManager
NotificationManager oNM =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//3a. Instantiate a Notification object
int icon = R.drawable.ic_launcher;
CharSequence tickerText = "New Database Available!";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
//4a. Update the notification and define the PendingIntent
Context context = getApplicationContext();
CharSequence contentTitle = "MyApplication Title";
CharSequence contentText =
"New database downloaded and available for installation!";
Intent notificationIntent = new Intent(this, NotificationActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this,
0,
notificationIntent,
0);
notification.setLatestEventInfo(context,
contentTitle,
contentText,
contentIntent);
//5. Send the Notification to the NotificationManager
oNM.notify(NOTIFICATION_ID_DATABASE_UPDATE_AVAIALBLE, notification);
}
//*------------------------------------------------------------------------------------*
//* Chapter 23: Thread Programming in Android - pg 368 *
//*------------------------------------------------------------------------------------*
//p.369-370
package com.example.andappb;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Ensure that the progressBar is initialized to [0,100].
ProgressBar oPB = (ProgressBar) findViewById(R.id.progressBar);
oPB.setMax(100);
oPB.setProgress(0);
}
//This method starts the simulated download
public void downloadFile(View view) {
//Instantiate the class and execute the download in the background
DownloadAsyncClass oDAC = new DownloadAsyncClass();
oDAC.execute("http://www.microsoft.com/stuff.pdf");
}
//The Generics are as follows:
// 1.String (Params type) - this is the parameter passed in (the http://
// URL of the file to download)
// 2.int (Progess type) - the progress increment
// 3.String (Result type) - the post-download file location on the
// device's storage media
public class DownloadAsyncClass extends AsyncTask {
//doInBackground
@Override
protected String doInBackground(String... params) {
String result = "";
//Simulate the download of a file in ten pieces
for(int i=0;i<10;i++) {
//Similate download
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//Update the progressBar in the user interface
publishProgress( (int) (100*(i+1)/10) );
}
result="myfile.pdf";
return result;
}
//onPreExecute
@Override
protected void onPreExecute() {
super.onPreExecute();
}
//onPostExecute
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
//onProgressUpdate
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
//Get pointer to progressBar
ProgressBar oPB = (ProgressBar) findViewById(R.id.progressBar);
//Set the progress to the parameter which is the percentage of completion.
oPB.setProgress(values[0]);
}
}
}
//p.371
public class DownloadAsyncClass extends AsyncTask {
//p.371
public class DownloadAsyncClass extends AsyncTask {
//p.372
new Thread(new Runnable() {
public void run() {
//your code goes here!!
}
}).start();
//p.372
Thread oThread = new Thread(doInBackground);
oThread.start();
private Runnable doInBackground = new Runnable() {
public void run() {
//your code goes here!!
}
};
//p.373
public class SQLQueryAsyncClass extends AsyncTask {
private Context context;
ProgressDialog oPD;
public SQLQueryAsyncClass(Context ctx) {
context = ctx;
//Set up the progress dialog to display while the SQL Query is running.
oPD = new ProgressDialog(context);
oPD.setMessage("Please wait...");
oPD.setIndeterminate(true);
oPD.setCancelable(false);
}
//p.373
//onPreExecute
@Override
protected void onPreExecute() {
super.onPreExecute();
//Display the ProgressDialog.
oPD.show();
}
//p.373
//onPostExecute
@Override
protected void onPostExecute(Cursor result) {
super.onPostExecute(result);
// ... code goes here ...
//Dismiss the ProgressDialog at this point.
oPD.dismiss();
// ... more code goes here ...
}
//*------------------------------------------------------------------------------------*
//* Chapter 24: Graphics - pg 375 *
//*------------------------------------------------------------------------------------*
//p.376
Resources res = getResources(); //may need to prefix with "this."
//Replace R.drawable.ic_launcher below with your own drawable image
Drawable oDraw = res.getDrawable(R.drawable.ic_launcher);
//p.379
//p.379
private AnimationDrawable oBananaAnimation;
//p.379
ImageView oImageView = (ImageView) findViewById(R.id.imageView1);
oImageView.setBackgroundResource(R.drawable.animated_banana);
oBananaAnimation = (AnimationDrawable) oImageView.getBackground();
//p.379
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus);
oBananaAnimation.start();
}
//p.380
oBananaAnimation = (AnimationDrawable) ((ImageView)
findViewById(R.id.imageView1)).getBackground();
//p.380
//p.381
//p.381-382
//p.382
//p.382
//p.382
ImageView oImageView = (ImageView) findViewById(R.id.imageView1);
oImageView.getBackground().setLevel(0);
//p.382
ImageView oImageView = (ImageView) findViewById(R.id.imageView1);
oImageView.getBackground().setLevel(
oImageView.getBackground().getLevel() + 1000);
//p.383
//p.383
//p.384
//p.384-385
//p.385
//p.385
public void changeLightToGreen(View view) {
ImageView oImageView = (ImageView) findViewById(R.id.ivTrafficLight);
LayerDrawable oLayerDrawable = (LayerDrawable)
getResources().getDrawable(R.drawable.mylayerlist);
Drawable oGreen = oLayerDrawable.getDrawable(0);
Drawable oRed = oLayerDrawable.getDrawable(1);
oImageView.setBackgroundDrawable(oGreen);
}
//p.385
//p.386
//p.386
ImageView oImageView = (ImageView) findViewById(R.id.ivTrafficLight);
oImageView.setImageLevel(3);
//p.386
//p.387
//p.388
//p.388-389
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//ScaleDrawable from our XML file: myscale.xml
ScaleDrawable oSD = (ScaleDrawable) getResources().getDrawable(
R.drawable.myscale);
//Set the level
oSD.getDrawable().setLevel(1);
//Apply the ScaleDrawable to the ImageView
ImageView oIV = (ImageView) findViewById(R.id.imageView1);
oIV.setImageDrawable(oSD);
}
//p.389
//p389-390
//color_default.xml (green):
//color_focus.xml (blue):
//color_pressed.xml (red):
//p.390
//p.391-392
//p.392
Resources res = getResources();
Drawable oDraw = res.getDrawable(R.drawable.name-of-drawable);
Button oBTN = (Button) findViewById(R.id.name-of-button);
oBTN.setBackgroundDrawable(oDraw);
//p.392
ImageView oIV = (ImageView) findViewById(R.id.name-of-ImageView);
oIV.setImageResource(R.drawable.name-of-drawable);
//p.392-393
//p.393
//p.394
//p.395
TransitionDrawable oTransDraw;
ImageView oIV;
//p.395
//Get the TransitionDrawable from mytransition.xml
oTransDraw = (TransitionDrawable)
getResources().getDrawable(R.drawable.mytransition);
//Enable cross-fading
oTransDraw.setCrossFadeEnabled(true);
//Set the ImageView to imageView1
oIV = (ImageView) findViewById(R.id.imageView1);
//Set the image in the imageView1 to the TransitionDrawable, oTransDraw.
oIV.setImageDrawable(oTransDraw);
//p.395
//Run the transition showing the closed folder opening up in 1000
//milliseconds (1 second).
oTransDraw.startTransition(1000);
//p.395
//p.404-405
//Create the graphic
public void createGraphic(View view) {
//Main title to be displayed
String sTitle = "Static Graphic Example #1";
//Bitmap height and width
int iBM_HEIGHT = 250;
int iBM_WIDTH = 250;
//Starting X and Y of Line
float fX_BEG = 0;
float fY_BEG = 0;
//Ending X and Y of Line
float fX_END = 250;
float fY_END = 250;
//Y-Coordinate of text
float fY_TEXT = 25;
//Text Size
float fTextSize = 10;
//Access the image view, imageView1, on the screen
ImageView oIV = (ImageView) findViewById(R.id.imageView1);
//Create a blank bitmap.
Bitmap oBM = Bitmap.createBitmap(iBM_HEIGHT,
iBM_WIDTH,
Bitmap.Config.ARGB_8888);
//Create a Canvas associating the bitmap oBM with it,
Canvas oCV = new Canvas(oBM);
//Set the background color of the Canvas
oCV.drawARGB(255, 0, 0, 255);
//Set up the dash effect
DashPathEffect oDPE = new DashPathEffect(new float[] {5,1},0);
//Create a Paint object for the line (red and dashed)
Paint oPT_LINE = new Paint();
oPT_LINE.setARGB(255, 255, 0, 0);
oPT_LINE.setStrokeWidth(2);
oPT_LINE.setStyle(Style.STROKE);
oPT_LINE.setPathEffect(oDPE);
//Add a line to the canvas using the Paint object
oCV.drawLine(fX_BEG, fY_BEG, fX_END, fY_END, oPT_LINE);
//Create a Paint object for the text (black and bold)
Paint oPT_TEXT = new Paint(Paint.FAKE_BOLD_TEXT_FLAG);
oPT_TEXT.setARGB(255, 255, 255, 255);
oPT_TEXT.setTypeface(Typeface.SANS_SERIF);
oPT_TEXT.setTextSize(fTextSize);
oPT_TEXT.setColor(Color.BLACK);
//Add the title to the canvas ensuring that the text is centered.
float fTitleWidth = oPT_TEXT.measureText(sTitle);
float fX_TEXT = ((float)iBM_WIDTH - fTitleWidth)/2;
oCV.drawText(sTitle, fX_TEXT, fY_TEXT, oPT_TEXT);
//Set the bitmap, oBM, as the image of imageView1.
oIV.setImageBitmap(oBM);
}
//p.405-407
package com.example.andappe;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Picture;
import android.graphics.Typeface;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//Create the graphic
public void createGraphic(View view) {
//Main title to be displayed
String sTitle = "Static Graphic Example #1";
//Bitmap height and width
int iBM_HEIGHT = 250;
int iBM_WIDTH = 250;
//Create static picture (by calling createPicture and to be used later)
Picture oPic = createPicture(iBM_HEIGHT,iBM_WIDTH);
//Starting X and Y of Line
float fX_BEG = 0;
float fY_BEG = 0;
//Ending X and Y of Line
float fX_END = 250;
float fY_END = 250;
//Y-Coordinate of text
float fY_TEXT = 25;
//Text Size
float fTextSize = 10;
//Access the image view, imageView1, on the screen
ImageView oIV = (ImageView) findViewById(R.id.imageView1);
//Create a blank bitmap.
Bitmap oBM = Bitmap.createBitmap(iBM_HEIGHT,
iBM_WIDTH,
Bitmap.Config.ARGB_8888);
//Create a Canvas associating the bitmap oBM with it,
Canvas oCV = new Canvas(oBM);
//Add the picture to the canvas
oCV.drawPicture(oPic);
//Set the background color of the Canvas
oCV.drawARGB(0, 0, 0, 255);
//Set up the dash effect
DashPathEffect oDPE = new DashPathEffect(new float[] {5,1},0);
//Create a Paint object for the line (red and dashed)
Paint oPT_LINE = new Paint();
oPT_LINE.setARGB(255, 255, 0, 0);
oPT_LINE.setStrokeWidth(1);
oPT_LINE.setStyle(Style.STROKE);
oPT_LINE.setPathEffect(oDPE);
//Add a line to the canvas using the Paint object
oCV.drawLine(fX_BEG, fY_BEG, fX_END, fY_END, oPT_LINE);
//Create a Paint object for the text (black and bold)
Paint oPT_TEXT = new Paint();
oPT_TEXT.setARGB(255, 255, 255, 255);
oPT_TEXT.setTypeface(Typeface.DEFAULT);
oPT_TEXT.setTextSize(fTextSize);
oPT_TEXT.setColor(Color.BLACK);
//Add the title to the canvas ensuring that the text is centered.
float fTitleWidth = oPT_TEXT.measureText(sTitle);
float fX_TEXT = ((float)iBM_WIDTH - fTitleWidth)/2;
oCV.drawText(sTitle, fX_TEXT, fY_TEXT, oPT_TEXT);
//Set the bitmap, oBM, as the image of imageView1.
oIV.setImageBitmap(oBM);
}
//Create the static picture
private Picture createPicture(int pBM_HEIGHT,int pBM_WIDTH) {
//Instantiate the blank picture
Picture oPIC = new Picture();
//Get the Canvas for the blank Picture
Canvas oCAN = oPIC.beginRecording(pBM_WIDTH, pBM_HEIGHT);
//Create a paint object for the horizontal and vertical axes
Paint oPT = new Paint();
oPT.setARGB(255, 0, 0, 0);
oPT.setStrokeWidth(1);
oPT.setStyle(Style.STROKE);
//Set the background of the canvas to white
oCAN.drawARGB(255, 255, 255, 255);
//Draw the lines on the canvas
oCAN.drawLine(0,
((float) pBM_HEIGHT)/2,
(float) pBM_WIDTH,
((float) pBM_HEIGHT)/2,
oPT);
oCAN.drawLine(((float) pBM_WIDTH)/2,
0,
((float) pBM_WIDTH)/2,
(float) pBM_HEIGHT,
oPT);
//End the recording
oPIC.endRecording();
return(oPIC);
}
}
//p.408-409
//Save the state of the canvas
oCV.save();
//Rotate the canvas by 45 degrees around the origin of our axes
oCV.rotate(-45, ((float) iBM_WIDTH)/2, ((float) iBM_HEIGHT)/2);
//Draw some text just below the X-axis
String sXAxisText = "Jan2013";
//Modify the Paint object oPT_TEXT so that the text is drawn to the
// LEFT of the (x,y)-coordinate.
oPT_TEXT.setTextAlign(Paint.Align.RIGHT);
//Make the font slightly smaller for the axis text
oPT_TEXT.setTextSize(fTextSize - 2);
//Draw the text under the x-axis.
oCV.drawText(sXAxisText, ((float) iBM_WIDTH)/2 + 20, ((float) iBM_HEIGHT)/2 + oPT_TEXT.measureText(sXAxisText), oPT_TEXT);
//Restore the state of the canvas
oCV.restore();
//p.409
//Bring in the Jura-Regular font
Typeface oTF_JuraRegular = Typeface.createFromAsset(getAssets(),
"fonts/Jura-Regular.ttf");
oPT_TEXT.setTypeface(oTF_JuraRegular);
//p.410
//Create a Path object
Path oPath = new Path();
oPath.moveTo(250, 250);
oPath.lineTo(300, 200);
oPath.lineTo(300, 300);
oPath.close();
//Change the line color to blue and remove the dash effect
oPT_LINE.setColor(Color.BLUE);
oPT_LINE.setPathEffect(null);
//Draw the path on the canvas
oCV.drawPath(oPath, oPT_LINE);
//p.412
...
//p.414
//p.414-415
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void StartViewAnimation(View view) {
Button oBtn = (Button) findViewById(R.id.button1);
Animation oAnim = AnimationUtils.loadAnimation(this,R.anim.myviewanimation);
oBtn.startAnimation(oAnim);
}
}
//p.416
package com.example.andappf;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.view.Menu;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
public class MainActivity extends Activity {
private MySurfaceView oSV;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Prevent the title from being shown and make the surface fullscreen.
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
//Access the SurfaceView
oSV = new MySurfaceView(this);
//Set the content view to the surface
setContentView(oSV);
}
}
//p.416-419
package com.example.andappf;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Toast;
public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder holder;
private MySurfaceViewThread mySurfaceViewThread;
private Bitmap oBM;
private double RandX;
private double RandY;
MySurfaceView(Context context) {
super(context);
//Get the SurfaceHolder from oSV.
holder=getHolder();
//Add the callback
holder.addCallback(this);
//Instantiate the thread
mySurfaceViewThread = new MySurfaceViewThread(holder,this);
//Initialize the bitmap
oBM = BitmapFactory.decodeResource(getResources(),
R.drawable.trafficlightgreen);
oBM = Bitmap.createScaledBitmap(oBM, 100, 100, false);
}
protected void onDraw(Canvas canvas) {
//Draw something on the canvas!
canvas.drawColor(Color.GREEN);
RandX = 500*Math.random();
RandY = 500*Math.random();
canvas.drawBitmap(oBM, (float) RandX,(float) RandY, null);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
mySurfaceViewThread.setRunnable(true);
mySurfaceViewThread.start();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
mySurfaceViewThread.setRunnable(false);
while(retry) {
try {
mySurfaceViewThread.join();
retry=false;
}
catch (InterruptedException ex) {
//nop
}
}
mySurfaceViewThread=null;
}
@Override
public void surfaceChanged(SurfaceHolder holder,
int format,
int width,
int height) {
//TODO
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//MySurfaceViewThread Class
class MySurfaceViewThread extends Thread {
private boolean run=false;
private SurfaceHolder sh;
private MySurfaceView sv;
private Canvas canvas;
//Constructor
MySurfaceViewThread(SurfaceHolder _holder,MySurfaceView _sv) {
super();
sh=_holder;
sv=_sv;
}
void setRunnable(boolean bRun) {
run=bRun;
}
@Override
public void run() {
super.run();
while (run) {
canvas=null;
//Lock the surface view's canvas.
try {
canvas = sh.lockCanvas(null);
synchronized(sh) {
sv.onDraw(canvas);
}
}
finally {
if (canvas != null) {
//Unlock the canvas
sh.unlockCanvasAndPost(canvas);
}
}
}
}
public void onWindowResize(int w,int h) {
//Deal with window resize!
}
}
}
//p.419
WindowManager.LayoutParams.FLAG_FULLSCREEN
//p.419
//Get the width and height of the device
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
int iDeviceWidth = display.getWidth();
int iDeviceHeight = display.getHeight();
//*------------------------------------------------------------------------------------*
//* Chapter 25: Pinch! Zoom! Swipe! – Detecting Gestures - pg 420 *
//*------------------------------------------------------------------------------------*
//p.421-425
package com.example.andappe;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.Picture;
import android.graphics.Typeface;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
private GestureDetector gestureDetector;
public View.OnTouchListener gestureListener;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Instantiate a new GestureDetector object setting the FlingDetector
// class as parameter
gestureDetector = new GestureDetector(new FlingDetector());
//Set up an OnTouchListener for this View.
gestureListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
return true;
}
return false;
}
};
}
//Create the graphic
public void createGraphic(View view) {
//Main title to be displayed
String sTitle = "STATIC GRAPHIC EXAMPLE #1";
//Bitmap height and width
int iBM_HEIGHT = 500;
int iBM_WIDTH = 500;
//Create static picture to be used later
Picture oPic = createPicture(iBM_HEIGHT,iBM_WIDTH);
//Starting X and Y of Line
float fX_BEG = 0;
float fY_BEG = 0;
//Ending X and Y of Line
float fX_END = 250;
float fY_END = 250;
//Y-Coordinate of text
float fY_TEXT = 25;
//Text Size
float fTextSize = 24;
//Access the image view, imageView1, on the screen
ImageView oIV = (ImageView) findViewById(R.id.imageView1);
//Create a blank bitmap.
Bitmap oBM = Bitmap.createBitmap(iBM_HEIGHT,
iBM_WIDTH,
Bitmap.Config.ARGB_8888);
//Create a Canvas associating the bitmap oBM with it,
Canvas oCV = new Canvas(oBM);
//Add the picture to the canvas
oCV.drawPicture(oPic);
//Set the background color of the Canvas
oCV.drawARGB(0, 0, 0, 255);
//Set up the dash effect
DashPathEffect oDPE = new DashPathEffect(new float[] {5,1},0);
//Create a Paint object for the line (red and dashed)
Paint oPT_LINE = new Paint();
oPT_LINE.setARGB(255, 255, 0, 0);
oPT_LINE.setStrokeWidth(2);
oPT_LINE.setStyle(Style.STROKE);
oPT_LINE.setPathEffect(oDPE);
//Add a line to the canvas using the Paint object
oCV.drawLine(fX_BEG, fY_BEG, fX_END, fY_END, oPT_LINE);
//Create a Paint object for the text (black and bold)
Paint oPT_TEXT = new Paint(/* Paint.FAKE_BOLD_TEXT_FLAG */);
oPT_TEXT.setARGB(255, 255, 255, 255);
//Bring in the Jura-Regular font
Typeface oTF_JuraRegular = Typeface.createFromAsset(getAssets(),
"fonts/Jura-Regular.ttf");
oPT_TEXT.setTypeface(oTF_JuraRegular);
oPT_TEXT.setTextSize(fTextSize);
oPT_TEXT.setColor(Color.BLACK);
//Add the title to the canvas ensuring that the text is centered.
float fTitleWidth = oPT_TEXT.measureText(sTitle);
float fX_TEXT = ((float)iBM_WIDTH - fTitleWidth)/2;
oCV.drawText(sTitle, fX_TEXT, fY_TEXT, oPT_TEXT);
//Save the state of the canvas
oCV.save();
//Rotate the canvas by 45 degrees around the origin of our axes
oCV.rotate( -45, ((float) iBM_WIDTH)/2, ((float) iBM_HEIGHT)/2);
//Draw some text just below the X-axis
String sXAxisText = "Jan2013";
//Modify the Paint object oPT_TEXT so that the text is drawn to the LEFT
// of the (x,y)-coordinate.
oPT_TEXT.setTextAlign(Paint.Align.RIGHT);
//Make the font slightly smaller for the axis text
oPT_TEXT.setTextSize(fTextSize - 1);
//Draw the text under the x-axis.
oCV.drawText(sXAxisText, ((float) iBM_WIDTH)/2 + 20,
((float) iBM_HEIGHT)/2 +
oPT_TEXT.measureText(sXAxisText), oPT_TEXT);
//Restore the state of the canvas
oCV.restore();
//Create a Path object
Path oPath = new Path();
oPath.moveTo(250, 250);
oPath.lineTo(300, 200);
oPath.lineTo(300, 300);
oPath.close();
//Change the line color to blue and remove the dash effect
oPT_LINE.setColor(Color.BLUE);
oPT_LINE.setPathEffect(null);
//Draw the path on the canvas
oCV.drawPath(oPath, oPT_LINE);
//Set the bitmap, oBM, as the image of imageView1.
oIV.setImageBitmap(oBM);
}
//Create the static picture
private Picture createPicture(int pBM_HEIGHT,int pBM_WIDTH) {
//Instantiate the blank picture
Picture oPIC = new Picture();
//Get the Canvas for the blank Picture
Canvas oCAN = oPIC.beginRecording(pBM_WIDTH, pBM_HEIGHT);
//Create a paint object for the horizontal and vertical axes
Paint oPT = new Paint();
oPT.setARGB(255, 0, 0, 0);
oPT.setStrokeWidth(1);
oPT.setStyle(Style.STROKE);
//Set the background of the canvas to white
oCAN.drawARGB(255, 255, 255, 255);
//Draw the lines on the canvas
oCAN.drawLine(0,
((float) pBM_HEIGHT)/2,
(float) pBM_WIDTH,
((float) pBM_HEIGHT)/2,
oPT);
oCAN.drawLine(((float) pBM_WIDTH)/2,
0,
((float) pBM_WIDTH)/2,
(float) pBM_HEIGHT, oPT);
//End the recording
oPIC.endRecording();
return(oPIC);
}
//Create a class to detect flings
class FlingDetector extends GestureDetector.SimpleOnGestureListener {
//Implement the onFling method
@Override
public boolean onFling(MotionEvent e1,
MotionEvent e2,
float velocityX,
float velocityY) {
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) return false;
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
//Right to Left Swipe
Toast toast = Toast.makeText(getApplicationContext(),
"RIGHT-TO-LEFT SWIPE!",
Toast.LENGTH_LONG);
toast.show();
return true;
}
else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
//Left to Right Swipe
Toast toast = Toast.makeText(getApplicationContext(),
"LEFT-TO-RIGHT SWIPE!",
Toast.LENGTH_LONG);
toast.show();
return true;
}
} catch (Exception e) {
// do something wonderful!
}
return false;
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (gestureDetector.onTouchEvent(event))
return true;
else
return false;
}
}
//p.425
private ScaleGestureDetector scaleGestureDetector;
public View.OnTouchListener scaleGestureListener;
//p.425
//Instantiate the scaleGestureDetector
scaleGestureDetector = new ScaleGestureDetector(this,new ScaleListener());
//Set up an OnTouchListener for this View.
scaleGestureListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (scaleGestureDetector.onTouchEvent(event)) {
return true;
}
return false;
}
};
//p.425-426
class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
Toast toast1 = Toast.makeText(getApplicationContext(),
"HERE WE ARE!",
Toast.LENGTH_LONG);
toast1.show();
//Get the scale factor ratio
float mScaleFactor = detector.getScaleFactor();
if (mScaleFactor == 1.0f) {
//No change
Toast toast = Toast.makeText(getApplicationContext(),
"SCALE: NO CHANGE!",
Toast.LENGTH_LONG);
toast.show();
}
else if (mScaleFactor > 1.0f) {
//zoom indicated by fingers broadening
Toast toast = Toast.makeText(getApplicationContext(),
"SCALE: ZOOM!",
Toast.LENGTH_LONG);
toast.show();
}
else if (mScaleFactor < 1.0f) {
//pinch indicated by fingers contracting
Toast toast = Toast.makeText(getApplicationContext(),
"SCALE: PINCH!",
Toast.LENGTH_LONG);
toast.show();
}
}
}
//p.426
@Override
public boolean onTouchEvent(MotionEvent event) {
if (gestureDetector.onTouchEvent(event))
return true;
else if (scaleGestureDetector.onTouchEvent(event))
return true;
else
return false;
}
//p.427
//p.427
//Set the maximum number of lines that can be displayed
// (analogous to android:maxLines)
StockInfoTextView.setMaxLines(10);
//Set the movement method to ScrollingMovementMethod
StockInfoTextView.setMovementMethod(ScrollingMovementMethod.getInstance());
//You want to disallow intercept touch for this TextView
StockInfoTextView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event)
{
v.getParent().requestDisallowInterceptTouchEvent(true);
return false;
}
});
//*------------------------------------------------------------------------------------*
//* Chapter 26: Detecting Device Rotation - pg 429 *
//*------------------------------------------------------------------------------------*
//p.429
//p.429
public class MainActivity extends Activity implements ComponentCallbacks {
//p.430
//Handle orientation changes
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
//Handle orientation changes
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
//handle landscape orientation
}
else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
//handle portrait orientation
}
}
//p.430
android:configChanges="orientation|keyboardHidden"
//p.430
android:configChanges="orientation|keyboardHidden|screenSize"
//p.430
android:screenOrientation="landscape"
android:screenOrientation="portrait"
//p.430
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//*------------------------------------------------------------------------------------*
//* Chapter 27: The GridView and ExpandableHeightGridView - pg 431 *
//*------------------------------------------------------------------------------------*
//See http://stackoverflow.com/questions/4523609/grid-of-images-inside-scrollview/4536955#4536955
//p.431
//p.432
//p.432-443
public class GridAdapter extends BaseAdapter {
String[] textArray;
Context contxt;
public GridAdapter(String[] textArr, Context context) {
textArray = textArr;
contxt=context;
}
@Override
public int getCount() {
return textArray.length;
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//Create a new LayoutInflater
LayoutInflater inflater = (LayoutInflater)
contxt.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
gridView = null;
convertView = null;// avoids recycling of grid view
if (convertView == null) {
gridView = new View(contxt);
// inflating grid view item
gridView = inflater.inflate(R.layout.grid_item, null);
// set value into textview
TextView textView = (TextView) gridView.findViewById(R.id.textView_id);
textView.setText(textArray[position]);
}
return gridView;
}
}
//p.433
public class MainActivity extends Activity {
static final String[] numbers = new String[] { "one", "two", "three", "four",
"five", "six","seven", "eight", "nine", "ten", "eleven", "twelve",
"thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
"nineteen", "twenty", "twenty one" };
GridView gridView;
GridAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = (GridView) findViewById(R.id.grid_id);
adapter = new GridAdapter(numbers, this);
gridView.setAdapter(adapter);
}
}
//p.435
public class ExpandableHeightGridView extends GridView {
boolean expanded = false;
public ExpandableHeightGridView(Context context) {
super(context);
}
public ExpandableHeightGridView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ExpandableHeightGridView(Context context,
AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
public boolean isExpanded() {
return expanded;
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// HACK! TAKE THAT ANDROID!
if (isExpanded())
{
// Calculate entire height by providing a very large height hint.
// But do not use the highest 2 bits of this integer; those are
// reserved for the MeasureSpec mode.
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
}
else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public void setExpanded(boolean expanded) {
this.expanded = expanded;
}
}
//p.435
private class cGridInfo {
private String sGridLabel;
private int iGridResourceImage;
cGridInfo(int pPosition,String pLabel,int pResource) {
sGridLabel=pLabel;
iGridResourceImage=pResource;
}
}
//p.436
//Create an adapter used to fill in the grid.
private class EquityYoGridAdapter extends BaseAdapter {
private Context context;
private final cGridInfo[] GridInfo;
EquityYoGridAdapter(Context pContext,cGridInfo[] pGridInfo) {
context=pContext;
GridInfo=pGridInfo;
}
public View getView(int position,View convertView,ViewGroup parent) {
//Access the layout inflater system service.
LayoutInflater inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
//Create a new, empty view
gridView = new View(context);
//Set the empty view to the maingrid_contents layout
gridView = inflater.inflate(R.layout.maingrid_contents, null);
//Fill in the TextView based on the text located at position.
TextView textView = (TextView) gridView.findViewById(R.id.grid_item_label);
textView.setText(GridInfo[position].sGridLabel);
//Fill in the ImageView based on the resource located at position.
ImageView imageView = (ImageView) gridView.findViewById(R.id.grid_item_image);
imageView.setImageResource(GridInfo[position].iGridResourceImage);
} else {
gridView = (View) convertView;
}
return gridView;
}
@Override
public int getCount() {
return GridInfo.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
}
//p.437
ExpandableHeightGridView gridView1, //Statistics
gridView2, //External Websites
gridView3; //EquityYO! Users Guide, Video, etc.
//Populate the grid with the text and resource image number.
private cGridInfo GridInfo1[] = {
new cGridInfo(0,"Stocks\n\n",R.drawable.dollar_currency_sign),
new cGridInfo(1,"Closed-End\nFunds\n",R.drawable.euro_currency_sign),
new cGridInfo(2,"Mutual\nFunds\n",R.drawable.sterling_pound_currency_sign),
new cGridInfo(3,"Exchange\nTraded\nFunds",R.drawable.yen_currency_sign),
new cGridInfo(4,"Market\nIndexes\n",R.drawable.chart)
};
private cGridInfo GridInfo2[] = {
new cGridInfo(0,"Yahoo!\nFinance\nWebsite",R.drawable.world),
new cGridInfo(1,"Google\nFinance\nWebsite",R.drawable.world),
new cGridInfo(2,"NASDAQ\nWebsite\n",R.drawable.world),
new cGridInfo(3,"NYSE\nWebsite\n ",R.drawable.world),
new cGridInfo(4,"SEC\nWebsite\n ",R.drawable.world),
new cGridInfo(6,"iShares\nWebsite\n ",R.drawable.world),
new cGridInfo(5,"CEF\nConnect\nWebsite",R.drawable.world)
};
private cGridInfo GridInfo3[] = {
new cGridInfo(0,"EquityYO!\nUser's\nGuide",R.drawable.info),
new cGridInfo(1,"EquityYO!\nManage\nPortfolio",R.drawable.briefcase),
new cGridInfo(2,"EquityYO!\nSettings\n ",R.drawable.settings),
new cGridInfo(3,"EquityYO!\nMetadata\n ",R.drawable.puzzle)
};
//p.437
//Access the grids.
gridView1 = (ExpandableHeightGridView) findViewById(R.id.maingrid1);
gridView2 = (ExpandableHeightGridView) findViewById(R.id.maingrid2);
gridView3 = (ExpandableHeightGridView) findViewById(R.id.maingrid3);
//Fill in the grid by using our class
gridView1.setAdapter(new EquityYoGridAdapter(this,GridInfo1));
gridView2.setAdapter(new EquityYoGridAdapter(this,GridInfo2));
gridView3.setAdapter(new EquityYoGridAdapter(this,GridInfo3));
//Turn setExpanded to true for all three grids.
gridView1.setExpanded(true);
gridView2.setExpanded(true);
gridView3.setExpanded(true);
//p.437
//*------------------------------------------------------------------------------------*
//* Chapter 28: Using Tabs in an Activity - pg 439 *
//*------------------------------------------------------------------------------------*
//p.439
//p.439-441
public class StocksActivity extends TabActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stocks);
//Get the TabHost object
TabHost tabHost = getTabHost();
//Create the two tabs, one to hold the results of the Selector
// SlidingDrawer and the other to provide the details.
TabSpec tabspecStockSymbolList = tabHost.newTabSpec("Symbols");
TabSpec tabspecStockSymbolDetail = tabHost.newTabSpec("Details");
//Add text, icons and wire up the intents to the appropriate activities.
tabspecStockSymbolList.setIndicator("SYMBOLS",
getResources().getDrawable(R.drawable.pages));
Intent intentSymbolList = new Intent(this,StockSymbolListActivity.class);
tabspecStockSymbolList.setContent(intentSymbolList);
tabspecStockSymbolDetail.setIndicator("DETAILS",
getResources().getDrawable(R.drawable.page));
Intent intentSymbolDetail = new Intent(this,StockSymbolDetailActivity.class);
tabspecStockSymbolDetail.setContent(intentSymbolDetail);
//Add the tabs to the tab widget
tabHost.addTab(tabspecStockSymbolList);
tabHost.addTab(tabspecStockSymbolDetail);
tabHost.getTabWidget().setDividerDrawable(R.drawable.tabdivider);
tabHost.getTabWidget().setStripEnabled(true);
tabHost.getTabWidget().setLeftStripDrawable(R.drawable.tabstrip);
tabHost.getTabWidget().setRightStripDrawable(R.drawable.tabstrip);
//Initialize the colors for the tabs and set the padding a bit larger.
for(int i=0; i < tabHost.getTabWidget().getChildCount(); i++) {
tabHost.getTabWidget().getChildAt(i).setBackgroundResource(
R.drawable.tab_selector);
tabHost.getTabWidget().getChildAt(i).setPadding(0, 0, 0, 0);
}
//Set the font color for the tabs.
View vwTabWidget;
TextView tvTabText;
for(int i=0; i < tabHost.getTabWidget().getChildCount(); i++) {
vwTabWidget = tabHost.getTabWidget().getChildAt(i);
tvTabText = (TextView) vwTabWidget.findViewById(android.R.id.title);
tvTabText.setTextSize(12);
tvTabText.setTypeface(null, Typeface.BOLD_ITALIC);
if (i==0) {
tvTabText.setTextColor(Color.parseColor("#FFFFFFFF"));
}
else if (i==1) {
tvTabText.setTextColor(Color.parseColor("#FF212121"));
}
}
//Set up a listener for the Details tab
getTabHost().setOnTabChangedListener(new OnTabChangeListener() {
@Override
public void onTabChanged(String tabId) {
int i = getTabHost().getCurrentTab();
if (i == 0) {
//Current tab is the tab on the left (0).
( (TextView) ( (View) getTabHost().getTabWidget().getChildAt(0) )
.findViewById(android.R.id.title))
.setTextColor(Color.parseColor("#FFFFFFFF"));
( (TextView) ( (View) getTabHost().getTabWidget().getChildAt(1) )
.findViewById(android.R.id.title))
.setTextColor(Color.parseColor("#FF212121"));
}
else if (i == 1) {
if (StocksActivity.oEquityYoSQLCursor != null) {
if (StocksActivity.oEquityYoSQLCursor.getCount() > 0) {
//Current tab is the tab on the right (1).
( (TextView) ( (View) getTabHost().getTabWidget().getChildAt(0) )
.findViewById(android.R.id.title))
.setTextColor(Color.parseColor("#FF212121"));
( (TextView) ( (View) getTabHost().getTabWidget().getChildAt(1) )
.findViewById(android.R.id.title))
.setTextColor(Color.parseColor("#FFFFFFFF"));
}
else {
getTabHost().setCurrentTab(0);
Toast.makeText(getApplicationContext(),
"Use the fly-out window to select desired data first.",
Toast.LENGTH_SHORT).show();
}
}
else {
getTabHost().setCurrentTab(0);
Toast.makeText(getApplicationContext(),
"Use the fly-out window to select desired data first.",
Toast.LENGTH_SHORT).show();
}
}
}
});
}
//p.441-442
public class cTabWidgetFix extends TabWidget {
private final View dummy;
public cTabWidgetFix(Context context) {
super(context);
dummy = new View(context);
}
public cTabWidgetFix(Context context, AttributeSet attrs) {
super(context, attrs);
dummy = new View(context);
}
public cTabWidgetFix(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
dummy = new View(context);
}
@Override
public View getChildTabViewAt(int i) {
if (i < 0 || i >= getChildCount()) {
return dummy;
}
return super.getChildTabViewAt(i);
}
@Override
public View getChildAt(int i) {
if (i < 0 || i >= getChildCount()) {
return dummy;
}
return super.getChildAt(i);
}
}
//p.442
//*------------------------------------------------------------------------------------*
//* Chapter 29: Using the SlidingDrawer - pg 443 *
//*------------------------------------------------------------------------------------*
//p.443-444
//p.445
slideButton = (Button) findViewById(R.id.slideButton); //Button
slidingDrawer = (SlidingDrawer) findViewById(R.id.SlidingDrawer); //SlidingDrawer
//Set up listeners for the opening and closing of the sliding drawer.
//These two listeners will change the drawer icon displayed.
slidingDrawer.setOnDrawerOpenListener(new OnDrawerOpenListener() {
public void onDrawerOpened() {
//change the button
slideButton.setBackgroundResource(R.drawable.slidingdrawer_arrow_close3);
}
});
slidingDrawer.setOnDrawerCloseListener(new OnDrawerCloseListener() {
public void onDrawerClosed() {
//change the button
slideButton.setBackgroundResource(R.drawable.slidingdrawer_arrow_open3);
}
});
//*------------------------------------------------------------------------------------*
//* Chapter 30: Using - pg 446 *
//*------------------------------------------------------------------------------------*
//p.446-451
You'll note that both the radio buttons as well as the the Submit/Reset buttons are in separate XML resource files and are included using the . For example, here is the XML for the radio buttons (located in criteria_selector.xml):
//p.453
//p.453
//p.454
//Set up a listener for the radio group @+id/rgCriteriaSelector
RadioGroup oRGCS = (RadioGroup) findViewById(R.id.rgCriteriaSelector);
OnCheckedChangeListener listener = new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup rGroup, int checkedId) {
//Modify the sSelectionCriteria based on the radio button clicked.
RadioButton checkedRadioButton = (RadioButton)rGroup.findViewById(checkedId);
String sRBTag = checkedRadioButton.getTag().toString();
sSelectionCriteria = sRBTag;
symbolList.sSelectionCriteria = sSelectionCriteria;
symbolList.onCheckedChanged(rGroup, checkedId);
}
};
oRGCS.setOnCheckedChangeListener(listener);
//p.454
@Override
public void onCheckedChanged(RadioGroup rGroup, int checkedId) {
//Get Activity from the context.
Activity oACT = (Activity) context;
// This will get the radiobutton that has changed in its check state
RadioButton checkedRadioButton = (RadioButton)rGroup.findViewById(checkedId);
//Get the tag from the radio button
String sRBTag = checkedRadioButton.getTag().toString();
//Based on the tag, replace the current subsetting criteria
//with the desired subsetting criteria.
LayoutInflater inflater = oACT.getLayoutInflater();
LinearLayout ll = (LinearLayout)
oACT.findViewById(R.id.layout_criteria_selection);
if (sRBTag.contentEquals("SHORT")) {
//Remove all of the views within the layout
ll.removeAllViews();
//Add in the views from the new layout.
ll.addView(inflater.inflate(R.layout.criteria_selection_short_stock, null));
...and so on...
//p.455
//Remove all of the views within the layout
ll.removeAllViews();
//Add in the views from the new layout.
ll.addView(inflater.inflate(R.layout.criteria_selection_short_stock, null));
//*------------------------------------------------------------------------------------*
//* Chapter 31: Working with WebView and WebViewClient - pg 456 *
//*------------------------------------------------------------------------------------*
//p.456-457
//p.457
public class UsersGuideActivity extends Activity {
private WebView oWVMD;
private ProgressDialog progressDialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_users_guide);
progressDialog = ProgressDialog.show(this, "Loading", "...one moment...");
oWVMD = (WebView) findViewById(R.id.webViewUsersGuide);
//Display a progress dialog while the webpage is being loaded into the browser.
oWVMD.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
super.shouldOverrideUrlLoading(view, url);
oWVMD.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
});
oWVMD.loadUrl("file:///android_asset/eyug.html");
}
}