//*------------------------------------------------------------------------------------*
//* Book: Android from A to D (Second Edition) *
//* Author: Scott L. Hecht *
//* Example code from text. *
//*------------------------------------------------------------------------------------*
//*------------------------------------------------------------------------------------*
//* Chapter 1: Installing the Android SDK on Windows - pg 13 *
//*------------------------------------------------------------------------------------*
//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 oAL_STATES = new ArrayList();
//p.84
oAL_STATES.add("Ohio");
oAL_STATES.add("Wyoming");
oAL_STATES.add("California");
oAL_STATES.add("Alabama");
//p.84
for(String sThisState : oAL_STATES) {
System.out.println(sThisState);
}
//p.84
for(int i=0; i oHM_STATES = new HashMap();
//p.85
oHM_STATES.put("Ohio","Columbus");
oHM_STATES.put("Wyoming","Cheyenne");
oHM_STATES.put("California","Sacramento");
oHM_STATES.put("Alabama","Montgomery");
//p.85
for(String sThisState : oHM_STATES.keySet()) {
System.out.println(sThisState);
}
//p.85
for(String sThisCapital : oHM_STATES.values()) {
System.out.println(sThisCapital);
}
//p.85
String sWyoming_Capital = oHM_STATES.get("Wyoming");
//p.85
import java.util.*;
import java.text.*;
//p.85
Date oTodaysDateTime = new Date();
//p.85
System.out.println("Today's Date and Time = " + oTodaysDateTime.toString());
//p.86
SimpleDateFormat oSDF1 = new SimpleDateFormat("MM/dd/yyyy");
//p.86
Date oTodaysDate = new Date();
//p.86
String sDateInMMDDYYYYFmt = oSDF1.format(oTodaysDate);
System.out.println("Today's date is " + sDateInMMDDYYYYFmt);
//p.87
Date oTodaysDateTime = new Date();
SimpleDateFormat oSDF = new SimpleDateFormat("EEEE MMMM dd, yyyy hh:mm:ss a");
String oMyDate = oSDF.format(oTodaysDateTime);
System.out.println("Today's Date and Time = " + oMyDate);
//p.87
String sMyDate="04/25/1964";
//p.87
SimpleDateFormat oSDF = new SimpleDateFormat("MM/dd/yyyy");
//p.87
ParsePosition oParsePosition = new ParsePosition(0);
//p.87
Date oMyDate = oSDF.parse(sMyDate,oParsePosition);
System.out.println("04/25/1964 as a Date Object = " + oMyDate.toString());
//*------------------------------------------------------------------------------------*
//* Chapter 5A: Exploring the Eclipse Integrated Development Environment (IDE) - pg 88 *
//*------------------------------------------------------------------------------------*
//No code examples in this chapter.
//*------------------------------------------------------------------------------------*
//* Chapter 5B: Exploring Android Studio - pg 114 *
//*------------------------------------------------------------------------------------*
//No code examples in this chapter.
//*------------------------------------------------------------------------------------*
//* Chapter 6: Introduction to the Android Platform - pg 149 *
//*------------------------------------------------------------------------------------*
//p.153-154
//p.154
My First Android Application
HELLO, WORLD!!
Settings
MainActivity
//*------------------------------------------------------------------------------------*
//* Chapter 7: Android Layouts - pg 156 *
//*------------------------------------------------------------------------------------*
//p.157
//p.158
//p.159
My First Android Application
HELLO, WORLD!!
Settings
MainActivity
Button
//p.159
android:text="Button"
//p.159
android:text="@string/button_text"
//p.160-161
//p.162-164
//p.164-166
//p.169
//p.169
//p.169-170
//p.170-171
//p.172
//p.174
//p.175
//p.176
//p.176-177
- 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.178-179
...and so on...
//*------------------------------------------------------------------------------------*
//* Chapter 8: Views Parade and the Eclipse Palette - pg 182 *
//*------------------------------------------------------------------------------------*
//No code examples in this chapter.
//*------------------------------------------------------------------------------------*
//* Chapter 9: Activities - pg 189 *
//*------------------------------------------------------------------------------------*
//p.189
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.190
//p.191
//p.191
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.192
setContentView(R.layout.activity_main);
//p.192
super.onCreate(savedInstanceState);
//p.192-193
My First Android Application
HELLO, WORLD!!
Settings
MainActivity
Button
//p.193
...additional XML...
//p.193
false
true
//p.193-194
- 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.194
...more layout goes here...
//p.194
//p.194
//p.194
TextView oTxtVw = (TextView) findViewById(R.id.myTxtVw);
//p.196
//p.199
@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.200
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.200
//*------------------------------------------------------------------------------------*
//* Chapter 10: Wiring-Up Event Handlers - pg 202 *
//*------------------------------------------------------------------------------------*
//p.202
//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.203
//p.204
//p.204
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.205
//p.205
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 11: Intents - pg 207 *
//*------------------------------------------------------------------------------------*
//p.211
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.211
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.212-213
//p.213
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.214-215
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.217
//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.221
//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.222
//p.224-225
//p.225
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.225-226
//p.228-229
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.229
//*------------------------------------------------------------------------------------*
//* Chapter 12: The Android Manifest - pg 231 *
//*------------------------------------------------------------------------------------*
//No code in this chapter, just XML from the Android documentation.
//*------------------------------------------------------------------------------------*
//* Chapter 13: Android Menus - pg 260 *
//*------------------------------------------------------------------------------------*
//p.260
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
//p.260
//p.261
//p.261
//p.263
//p.263
//p.264-265
//p.266
-
//p.267
//p.268
//p.268
//p.269
public void myClickHandler(MenuItem item) {
if (item.isChecked()) {
item.setChecked(false);
}
else {
item.setChecked(true);
}
}
//p.269
@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.271
TextView oTxtVw = (TextView) findViewById(R.id.textView1);
registerForContextMenu(oTxtVw);
//p.271
@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.271-272
//p.272
@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 14: Saving State: Bundle, SharedPreference and PreferenceActivity - pg 274 *
//*------------------------------------------------------------------------------------*
//p.275
@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.275
@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.278
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.279
@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.279
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.280
String SYMBOL_SAVED =
getSharedPreferences("MY_PREF_GROUP",
Context.MODE_PRIVATE).getString("SYMBOL_SAVED", "????");
//p.280
//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.282
//p.284
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.284-285
@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.285
- Single-Threaded
- Multi-Threaded
- 1
- 2
//p.287
//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.288
public class MainActivity extends Activity implements
OnSharedPreferenceChangeListener {
//p.288
//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.288
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 15: Working with the SQLite Database - pg 291 *
//*------------------------------------------------------------------------------------*
//p.300
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.316
SQLiteDatabase oSQLiteDB;
//p.316
private static SQLiteDatabase oSQLiteDB;
//p.316
//Open the database in read/write mode
oSQLiteDB =
SQLiteDatabase.openDatabase("/data/data/com.example.andapp1/MySQLite3TestDB.db3",
null,
SQLiteDatabase.OPEN_READWRITE);
//p.316
//Close the database
if (oSQLiteDB != null) {
oSQLiteDB.close();
}
//p.317
//Create the SQL string
String sSQL = "SELECT DISTINCT STOCK_SYMBOL FROM HISTORICAL_STOCK_PRICES";
//p.317
//Get a cursor to the returned data
Cursor oCSR = oSQLiteDB.rawQuery(sSQL,null);
//p.317
//Initialize the sAllStockSymbols variable with the number of rows pulled back.
String sAllStockSymbols = Integer.toString(oCSR.getCount()) + ": ";
//p.317
//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.317
//Let's display the stock symbols using a Toast
Toast toast = Toast.makeText(getApplicationContext(), sAllStockSymbols, Toast.LENGTH_LONG);
toast.show();
//p.318
//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.318
//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.318
//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.319
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.320
//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.320
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.320
//Delete INTC and CSCO
int iNbrRowsDel = oSQLiteDB.delete("HISTORICAL_STOCK_PRICES",
"STOCK_SYMBOL IN (?,?)",
new String[] {"INTC","CSCO"});
//p.321
//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.321
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.323-325
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.325
//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.325
//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.325
//close the database
oMSOH.close();
//p.326
oMSOH.getWritableDatabase().execSQL(sql);
//p.326
//MUST ADD android_metadata table into database!
CREATE TABLE android_metadata (locale TEXT);
INSERT INTO android_metadata VALUES('en_US');
//p.326
oSQLiteDB = SQLiteDatabase.openDatabase("/data/data/pkg-name/dbname",
null,
SQLiteDatabase.NO_LOCALIZED_COLLATORS);
//p.327
oSQLiteDB = SQLiteDatabase.openDatabase("/data/data/pkg-name/dbname",
null,
SQLiteDatabase.NO_LOCALIZED_COLLATORS |
SQLiteDatabase.OPEN_READONLY);
//*------------------------------------------------------------------------------------*
//* Chapter 16: Content Providers - pg 328 *
//*------------------------------------------------------------------------------------*
//p.329
content://com.example.andapp1.provider/stocksymbols
content://com.example.andapp1.provider/stocksymbols/#
//p.329
vnd.android.cursor.dir/vnd.com.example.andapp1.provider.stocksymbols
vnd.android.cursor.item/vnd.com.example.andapp1.provider.stocksymbols
//p.331
scheme://authority/path?query#fragment
//p.331
Uri uContentUri =
Uri.parse("content://com.example.andapp1.provider/stocksymbols");
//p.331
// 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.331
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.331
Uri uContentUri_ExchangeSpecific = Uri.withAppendedPath(uContentUri, "nyse");
//p.332
Uri.Builder ubContentUriBuilder = new Uri.Builder();
//p.332
// content
ubContentUriBuilder.scheme(sScheme);
// com.example.andapp1.provider
ubContentUriBuilder.authority(sAuthority);
// stocksymbols
ubContentUriBuilder.path(sLastPath);
//p.332
ubContentUriBuilder.build();
//p.332
Uri.Builder ubContentFromUri = uContentUri.buildUpon();
//p.332
ubContentFromUri.appendPath("nyse");
//p.333
Uri uContentUri =
Uri.parse("content://com.example.andapp1.provider/stocksymbols");
Uri uContentUriWithID = ContentUris.withAppendedId(uContentUri, 4);
//p.333
long lID = ContentUris.parseId(uContentUriWithID);
//p.333
//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.334
//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.334
Uri uContentUri =
Uri.parse("content://com.example.andapp1.provider/stocksymbols/amex/5");
//p.334-335
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.336-337
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.337-338
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.338
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.338
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.339-341
//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.342
//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.342-345
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.345
.provider.permission.
//p.345
com.example.andapp1.provider.permission.READ_PROVIDER
//p.345-346
//p.346
//p.347
//p.348-349
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.353-354
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.354-356
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 17: Adapters - pg 358 *
//*------------------------------------------------------------------------------------*
//p.359
TextView oTxtVw = (TextView) findViewById(R.id.text-view-id);
oTxtVw.setText("your-text-goes-here");
//p.359-360
//p.360
String[] sArray = {"INTC","MSFT","GOOG","CSCO","FB"};
//p.360
//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.360
String[] sArray = getResources().getStringArray(R.array.your-array-name);
//p.360
//p.361
//Set up the ArrayAdapter
ArrayAdapter adapter = new ArrayAdapter(this,
R.layout.mytextview,
sArray);
//p.361
public class MyClass {
String sText = "";
public MyClass(String pText) {
sText = pText;
}
@Override
public String toString() {
return "New York Stock Exchange: " + sText;
}
}
//p.361
@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.362
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.363
@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.363-364
//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.364-366
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.367-368
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.368-369
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.369-370
@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.3271
//p.371-372
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: Broadcasting Events - pg 373 *
//*------------------------------------------------------------------------------------*
//p.373
//Create our broadcast event string
public static final String DATABASE_UPDATED_ACTION =
"com.example.action.DATABASE_UPDATED";
//p.374
//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.374
//p.374-375
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.378
//p.378
//p.378
//p.378-379
//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.379
//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.379-380
//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.380
//Register our BroadcastReceiver to be fired when the download has completed.
registerReceiver(oBR,
new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
//p.380
String uriString =
oCSR.getString(oCSR.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
//p.380
file:///mnt/sdcard/Download/download_file.pdf
//p.381-382
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 19: Services - pg 383 *
//*------------------------------------------------------------------------------------*
//p.385-386
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.386
//p.386
//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.386
stopService(intent);
//p.387
stopSelf(iStartID);
//p.387-388
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.389
final Intent intent = new Intent(this,MyIntentServiceClass.class);
startService(intent);
//p.390
private final IBinder oBinder = new MyBinder();
//p.390-391
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.391
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.391-392
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 20: The Application Class - pg 393 *
//*------------------------------------------------------------------------------------*
//p.392
//p.393-394
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.394-395
//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 21: Status Notifications - pg 396 *
//*------------------------------------------------------------------------------------*
//p.397
//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 22: Thread Programming in Android - pg 400 *
//*------------------------------------------------------------------------------------*
//p.401-402
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.403
public class DownloadAsyncClass extends AsyncTask {
//p.403
public class DownloadAsyncClass extends AsyncTask {
//p.404
new Thread(new Runnable() {
public void run() {
//your code goes here!!
}
}).start();
//p.404
Thread oThread = new Thread(doInBackground);
oThread.start();
private Runnable doInBackground = new Runnable() {
public void run() {
//your code goes here!!
}
};
//p.405
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.405
//onPreExecute
@Override
protected void onPreExecute() {
super.onPreExecute();
//Display the ProgressDialog.
oPD.show();
}
//p.405
//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 23: Graphics - pg 407 *
//*------------------------------------------------------------------------------------*
//p.408
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.411
//p.411
private AnimationDrawable oBananaAnimation;
//p.411
ImageView oImageView = (ImageView) findViewById(R.id.imageView1);
oImageView.setBackgroundResource(R.drawable.animated_banana);
oBananaAnimation = (AnimationDrawable) oImageView.getBackground();
//p.411
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus);
oBananaAnimation.start();
}
//p.412
oBananaAnimation = (AnimationDrawable) ((ImageView)
findViewById(R.id.imageView1)).getBackground();
//p.412
//p.413
//p.413-414
//p.414
//p.414
//p.414
ImageView oImageView = (ImageView) findViewById(R.id.imageView1);
oImageView.getBackground().setLevel(0);
//p.414
ImageView oImageView = (ImageView) findViewById(R.id.imageView1);
oImageView.getBackground().setLevel(
oImageView.getBackground().getLevel() + 1000);
//p.415
//p.415
//p.416
//p.416-417
//p.417
//p.417
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.417
//p.418
//p.418
ImageView oImageView = (ImageView) findViewById(R.id.ivTrafficLight);
oImageView.setImageLevel(3);
//p.418
//p.419
//p.420
//p.420-421
@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.421
//p421-422
//color_default.xml (green):
//color_focus.xml (blue):
//color_pressed.xml (red):
//p.422
//p.423-424
//p.424
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.424
ImageView oIV = (ImageView) findViewById(R.id.name-of-ImageView);
oIV.setImageResource(R.drawable.name-of-drawable);
//p.424-425
//p.425
//p.426
//p.427
TransitionDrawable oTransDraw;
ImageView oIV;
//p.427
//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.427
//Run the transition showing the closed folder opening up in 1000
//milliseconds (1 second).
oTransDraw.startTransition(1000);
//p.427
//p.436-437
//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.437-439
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.440-441
//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.441
//Bring in the Jura-Regular font
Typeface oTF_JuraRegular = Typeface.createFromAsset(getAssets(),
"fonts/Jura-Regular.ttf");
oPT_TEXT.setTypeface(oTF_JuraRegular);
//p.442
//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.444
...
//p.446
//p.446-447
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.448
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.448-451
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.451
WindowManager.LayoutParams.FLAG_FULLSCREEN
//p.451
//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 24: Pinch! Zoom! Swipe! – Detecting Gestures - pg 452 *
//*------------------------------------------------------------------------------------*
//p.453-457
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.457
private ScaleGestureDetector scaleGestureDetector;
public View.OnTouchListener scaleGestureListener;
//p.457
//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.457-458
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.458
@Override
public boolean onTouchEvent(MotionEvent event) {
if (gestureDetector.onTouchEvent(event))
return true;
else if (scaleGestureDetector.onTouchEvent(event))
return true;
else
return false;
}
//p.459
//p.459
//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 25: Detecting Device Rotation - pg 461 *
//*------------------------------------------------------------------------------------*
//p.461
//p.461
public class MainActivity extends Activity implements ComponentCallbacks {
//p.462
//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.462
android:configChanges="orientation|keyboardHidden"
//p.462
android:configChanges="orientation|keyboardHidden|screenSize"
//p.462
android:screenOrientation="landscape"
android:screenOrientation="portrait"
//p.462
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//*------------------------------------------------------------------------------------*
//* Chapter 26: The GridView and ExpandableHeightGridView - pg 463 *
//*------------------------------------------------------------------------------------*
//See http://stackoverflow.com/questions/4523609/grid-of-images-inside-scrollview/4536955#4536955
//p.463
//p.464
//p.464-465
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.465
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.467
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.467
private class cGridInfo {
private String sGridLabel;
private int iGridResourceImage;
cGridInfo(int pPosition,String pLabel,int pResource) {
sGridLabel=pLabel;
iGridResourceImage=pResource;
}
}
//p.468
//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.469
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.469
//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.469
//*------------------------------------------------------------------------------------*
//* Chapter 27: Using Tabs in an Activity - pg 471 *
//*------------------------------------------------------------------------------------*
//p.471
//p.471-473
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.473-474
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.474
//*------------------------------------------------------------------------------------*
//* Chapter 28: Using the SlidingDrawer - pg 475 *
//*------------------------------------------------------------------------------------*
//p.475-476
//p.477
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 29: Using - pg 478 *
//*------------------------------------------------------------------------------------*
//p.478-483
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.485
//p.485
//p.486
//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.486
@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.487
//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 30: Introduction to Fragments - pg 488 *
//*------------------------------------------------------------------------------------*
//p.492
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
//p.493
//p.493
//p.494
package com.example.fragmenttest1;
import java.util.Random;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//Replaces the text in the fragment’s textview.
public void PopulateFragment(View view) {
Random oRand = new Random();
int iRandomInteger = oRand.nextInt(100);
String sSomeText = "Now is the time..." +
Integer.toString(iRandomInteger);
//Grab the id of the textbox
TextView oTV = (TextView) findViewById(R.id.textview_fragment);
//Change the text of the fragment's textbox
oTV.setText(sSomeText);
}
}
//p.494
package com.example.fragmenttest1;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentControl extends Fragment {
//Force fragment_main.xml to appear in the of activity_main.xml.
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
//Create a View object from fragment_main
View oFragmentMainView =
inflater.inflate(R.layout.fragment_main,container,false);
return oFragmentMainView;
}
}
//p.495
Random oRand = new Random();
int iRandomInteger = oRand.nextInt(100);
String sSomeText = "Now is the time..." + Integer.toString(iRandomInteger);
//Grab the id of the textbox
TextView oTV = (TextView) findViewById(R.id.textview_fragment);
//Change the text of the fragment's textbox
oTV.setText(sSomeText);
//p.496
//Now, let's try to remove the fragment itself.
//Get access to the FragmentManager.
FragmentManager oFM = (FragmentManager) getSupportFragmentManager();
//Get access to our FragmentControl class.
FragmentControl oFC = (FragmentControl) oFM.findFragmentById(R.id.main_fragment);
//Begin a fragment transaction
FragmentTransaction oFT = oFM.beginTransaction();
//Attempt to remove our fragment.
oFT.remove(oFC);
//Commit the transaction.
oFT.commit();
//p.498
//p.498
//p.498
//p.499
//p.499
package com.example.fragmenttest2;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//When user clicks the button, add the three fragments to the LinearLayout.
public void AddFragments(View view) {
//Create a new FragmentControlTextBox# classes
FragmentControlTextBox1 oFC_TB1 = new FragmentControlTextBox1();
FragmentControlTextBox2 oFC_TB2 = new FragmentControlTextBox2();
FragmentControlTextBox3 oFC_TB3 = new FragmentControlTextBox3();
//Get access to the FragmentManager.
FragmentManager oFM = (FragmentManager) getSupportFragmentManager();
//Begin a fragment transaction
FragmentTransaction oFT = oFM.beginTransaction();
//Add our new fragment
oFT.add(R.id.mainframe,oFC_TB1);
oFT.add(R.id.mainframe,oFC_TB2);
oFT.add(R.id.mainframe,oFC_TB3);
//Commit the change.
oFT.commit();
//Execute Pending Transactions
oFM.executePendingTransactions();
}
}
//p.500
package com.example.fragmenttest2;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentControlTextBox1 extends Fragment {
//Inflate fragment_textbox1.
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
//Create a View object from fragment_main
View oFragmentMainView =
inflater.inflate(R.layout.fragment_textbox1,container,false);
return oFragmentMainView;
}
}
//p.500
package com.example.fragmenttest2;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentControlTextBox2 extends Fragment {
//Inflate fragment_textbox1.
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
//Create a View object from fragment_main
View oFragmentMainView =
inflater.inflate(R.layout.fragment_textbox2,container,false);
return oFragmentMainView;
}
}
//p.500-501
package com.example.fragmenttest2;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentControlTextBox3 extends Fragment {
//Inflate fragment_textbox1.
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
//Create a View object from fragment_main
View oFragmentMainView =
inflater.inflate(R.layout.fragment_textbox3,container,false);
return oFragmentMainView;
}
}
//p.501
//Create a View object from fragment_main
View oFragmentMainView =
inflater.inflate(R.layout.fragment_textbox3,container,false);
//p.502
//Add our new fragment
oFT.add(R.id.mainframe,oFC_TB1);
oFT.add(R.id.mainframe,oFC_TB2);
oFT.add(R.id.mainframe,oFC_TB3);
//p.502-503
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//When user clicks the button, add the three fragments to the LinearLayout.
public void AddFragments(View view) {
//Create a new FragmentControlTextBox# classes
FragmentControlTextBox1 oFC_TB1 = new FragmentControlTextBox1();
FragmentControlTextBox2 oFC_TB2 = new FragmentControlTextBox2();
FragmentControlTextBox3 oFC_TB3 = new FragmentControlTextBox3();
//Get access to the FragmentManager.
FragmentManager oFM = (FragmentManager) getSupportFragmentManager();
//Begin a fragment transaction
FragmentTransaction oFT = oFM.beginTransaction();
//Add our new fragment
oFT.add(R.id.mainframe,oFC_TB1);
oFT.add(R.id.mainframe,oFC_TB2);
oFT.add(R.id.mainframe,oFC_TB3);
//Store in back stack
oFT.addToBackStack(null);
//Commit the change.
oFT.commit();
//Execute Pending Transactions
oFM.executePendingTransactions();
}
}
//p.504
oFT.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
//p.505
//p.510
//p.510
//p.510-512
//p.512
//p.512
//p.512-513
//p.513
- All Sectors
- Basic Materials
- Conglomerates
- Consumer Goods
- Financial
- Healthcare
- Industrial Goods
- Services
- Technology
- Utilities
- A
- AA
- ANDA
- ACAT
- AACC
- ABAX
- AAON
- AAN
- A
- ADGE
- 0
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
//p.513-514
EquityYoStocks
Settings
User&s Guide
Portfolio
equityYO! User\'s Guide
Stock Symbols
//p.514
//p.514-520
package com.example.equityyostocks;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.support.v4.widget.DrawerLayout;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements
Fragment1SpinnerControl.OnFragment1SpinnerChangedListener {
ListView oSectorListView;
Fragment1SpinnerControl oF1C_SP;
Fragment2DetailsControl oF2C_DE;
Fragment3PriceChartControl oF3C_PC;
Fragment4DividendChartControl oF4C_DC;
Fragment5AlsoViewedImageControl oF5C_AC;
FragmentManager oFM;
FragmentTransaction oFT;
DrawerLayout oSectorDrawerLayout;
View viewSectorOLD;
Boolean bFirstTimeThrough = true;
ScrollView oScrollView;
int iDeviceWidth,iDeviceHeight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Access the DrawerLayout object.
oSectorDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//Access the ScrollView object.
oScrollView = (ScrollView) findViewById(R.id.svFragments);
//Access the sector ListView object.
oSectorListView = (ListView) findViewById(R.id.sector_drawer);
//Place the sector names in an array.
String[] aSectorNames = getResources().getStringArray(R.array.sectors);
//Rig up a custom ArrayAdapter to the list of sector names in the array.
CustomArrayAdapter adapter = new CustomArrayAdapter(this,
android.R.layout.simple_list_item_1,
aSectorNames);
//Associate the adapter with the sector ListView.
oSectorListView.setAdapter(adapter);
//Access the FragmentManager.
oFM = (FragmentManager) getSupportFragmentManager();
//Get the width and height of the device
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
iDeviceWidth = display.getWidth();
iDeviceHeight = display.getHeight();
//Load the five fragments into the mainframe.
initialLoadFragments();
//Open the drawer containing the sectors.
oSectorDrawerLayout.openDrawer(oSectorListView);
//Set up a listener for the click of the NavigationDrawer.
SectorDrawerItemClickListener sectorDrawerListener =
new SectorDrawerItemClickListener();
oSectorListView.setOnItemClickListener(sectorDrawerListener);
}
//Override the onRestart method.
@Override
protected void onRestart() {
super.onRestart();
//Re-init the boolean variable bFirstTimeThrough to true.
bFirstTimeThrough=true;
//Remove the fragments.
oFT = oFM.beginTransaction();
oFT.remove(oF5C_AC);
oFT.remove(oF4C_DC);
oFT.remove(oF3C_PC);
oFT.remove(oF2C_DE);
oFT.remove(oF1C_SP);
oFT.commitAllowingStateLoss();
oFM.executePendingTransactions();
//Re-initialize the sector ListView
oSectorListView = (ListView) findViewById(R.id.sector_drawer);
String[] aSectorNames = getResources().getStringArray(R.array.sectors);
CustomArrayAdapter adapter = new CustomArrayAdapter(this,
android.R.layout.simple_list_item_1,
aSectorNames);
oSectorListView.setAdapter(adapter);
//Re-initialize the fragments
initialLoadFragments();
//Move the ScrollView up to the top.
oScrollView.scrollTo(0, 0);
}
//Populate the menu on the ActionBar (will show three vertical dots)
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
//Handle the menu item clicks.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.mUsersGuide:
Intent intent = new Intent(MainActivity.this,UsersGuideActivity.class);
startActivity(intent);
return true;
case R.id.mManagePorfolio:
Toast.makeText(getApplicationContext(),
"This feature is not implemented.",
Toast.LENGTH_SHORT).show();
return true;
case R.id.mSettings:
Toast.makeText(getApplicationContext(),
"This feature is not implemented.",
Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//Method to load the fragments initially.
private void initialLoadFragments() {
//Instantiate the five fragments.
oF1C_SP = new Fragment1SpinnerControl(); //Fragment #1: Spinner
oF2C_DE = new Fragment2DetailsControl(); //Fragment #2: Details
oF3C_PC = new Fragment3PriceChartControl(); //Fragment #3: Price Chart
oF4C_DC = new Fragment4DividendChartControl(); //Fragment #4: Dividend Chart
oF5C_AC = new Fragment5AlsoViewedImageControl(); //Fragment #5: AV Image
//Set up a Bundle for use with the five fragment objects.
Bundle oBundleArgs = new Bundle();
//Populate oBundleArgs for use with the fragments.
oBundleArgs.putString("SECTORKEY", "0");
oBundleArgs.putString("SYMBOL", "A");
oBundleArgs.putInt("WIDTH", iDeviceWidth);
oBundleArgs.putInt("HEIGHT", iDeviceHeight);
//Fragment #1: Spinner
oF1C_SP.setArguments(oBundleArgs);
//Fragment #2: Details
oF2C_DE.setArguments(oBundleArgs);
//Fragment #3: Price Chart
oF3C_PC.setArguments(oBundleArgs);
//Fragment #4: Dividend Chart
oF4C_DC.setArguments(oBundleArgs);
//Fragment #5: Also Viewed Image
oF5C_AC.setArguments(oBundleArgs);
//Begin a fragment transaction
oFT = oFM.beginTransaction();
//Add in the fragments
oFT.add(R.id.mainframe,oF1C_SP);
oFT.add(R.id.mainframe,oF2C_DE);
oFT.add(R.id.mainframe,oF3C_PC);
oFT.add(R.id.mainframe,oF4C_DC);
oFT.add(R.id.mainframe,oF5C_AC);
//Commit the change.
oFT.commitAllowingStateLoss();
//Execute Pending Transactions
oFM.executePendingTransactions();
}
//Create a class to handle clicks for the Sector Drawer.
private class SectorDrawerItemClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView> adapter,
View view,
int position,
long id) {
//Highlight the clicked sector
highlightSector(view,position);
//Update the Spinner with the new sector key.
updateSpinner(position);
//Update fragment #2 (Details)
updateDetails(position);
//Update fragment #3 (Price Chart)
updatePriceChart(position);
//Update fragment #4 (Dividend Chart)
updateDividendChart(position);
//Update fragment #5 (Also Viewed Image)
updateAlsoViewedImage(position);
//Move ScrollView to top
oScrollView.scrollTo(0, 0);
//Close the drawer
oSectorDrawerLayout.closeDrawer(oSectorListView);
}
//Highlight the appropriate sector when it is clicked
private void highlightSector(View view,int iPosition) {
//Change the background color from green to white for the old position
if (viewSectorOLD != null) {
viewSectorOLD.setBackgroundColor(Color.rgb(255, 255, 255));
}
//Change the background color from white to green.
view.setBackgroundColor(Color.rgb(163, 186, 66));
//Swap views
viewSectorOLD = view;
}
//Update the spinner with the set of stocks for the newly selected sector.
private void updateSpinner(int iPosition) {
//Create an array from the sectorkeys array
String[] sArray = getResources().getStringArray(R.array.sectorkeys);
//String to hold this sectorkey
String sThisSectorKey = sArray[iPosition];
//Update the spinner in Fragement #1.
oF1C_SP.populateSpinner(sThisSectorKey);
}
//Update the details fragment with the default stock for this sector.
private void updateDetails(int iPosition) {
//Create an array from the sectordefaultsymbol array
String[] sArray =
getResources().getStringArray(R.array.sectordefaultsymbol);
//String to hold this sectorkey's default stock
String sThisSectorKeyDefaultStock = sArray[iPosition];
//Update the spinner in Fragment #1.
oF2C_DE.populateDetails(sThisSectorKeyDefaultStock);
}
//Update the Price Chart fragment with the default stock for this sector.
private void updatePriceChart(int iPosition) {
//Create an array from the sectordefaultsymbol array
String[] sArray =
getResources().getStringArray(R.array.sectordefaultsymbol);
//String to hold this sectorkey's default stock
String sThisSectorKeyDefaultStock = sArray[iPosition];
//Update the price chart in Fragment #3.
oF3C_PC.populatePriceChart(sThisSectorKeyDefaultStock);
}
//Update the Price Chart fragment with the default stock for this sector.
private void updateDividendChart(int iPosition) {
//Create an array from the sectordefaultsymbol array
String[] sArray =
getResources().getStringArray(R.array.sectordefaultsymbol);
//String to hold this sectorkey's default stock
String sThisSectorKeyDefaultStock = sArray[iPosition];
//Update the price chart in Fragment #3.
oF4C_DC.populateDividendChart(sThisSectorKeyDefaultStock);
}
//Update the Price Chart fragment with the default stock for this sector.
private void updateAlsoViewedImage(int iPosition) {
//Create an array from the sectordefaultsymbol array
String[] sArray =
getResources().getStringArray(R.array.sectordefaultsymbol);
//String to hold this sectorkey's default stock
String sThisSectorKeyDefaultStock = sArray[iPosition];
//Update the price chart in Fragment #3.
oF5C_AC.generateAlsoViewedImage(sThisSectorKeyDefaultStock,
iDeviceWidth,iDeviceWidth);
}
}
//Create a CustomArrayAdapter in order to highlight the first ListView entry.
private class CustomArrayAdapter extends ArrayAdapter {
private String[] sArray;
private Context context;
public CustomArrayAdapter(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(android.R.layout.simple_list_item_1, 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(android.R.id.text1);
//Set the text to whatever you want in mytextview
oTVSS.setText(sItem);
//Set the background
if (bFirstTimeThrough && position==0) {
view.setBackgroundColor(Color.rgb(163, 186, 66));
viewSectorOLD = view;
}
else {
view.setBackgroundColor(Color.rgb(255, 255, 255));
}
if (bFirstTimeThrough) {
bFirstTimeThrough=false;
}
return view;
}
}
//Called when the user changes the Fragment #1 spinner.
@Override
public void OnFragment1SpinnerChanged(String sSymbol) {
oF2C_DE.populateDetails(sSymbol);
oF3C_PC.populatePriceChart(sSymbol);
oF4C_DC.populateDividendChart(sSymbol);
oF5C_AC.generateAlsoViewedImage(sSymbol,iDeviceWidth,iDeviceWidth);
}
}
//p.520-521
package com.example.equityyostocks;
import android.content.Context;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
public class EquityYoDatabaseAccess extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "EQUITY_DATABASE";
private static final int DATABASE_VERSION = 1;
public EquityYoDatabaseAccess(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//Force any new database to overwrite an existing database.
setForcedUpgradeVersion(DATABASE_VERSION);
//Close the database once it has been installed.
//I will open the database again later.
close();
}
}
//p.521-523
package com.example.equityyostocks;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SimpleCursorAdapter;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TextView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment1SpinnerControl extends Fragment {
String sSectorKey = "0"; //By default, the sector key is zero.
View oFragment1Spinner;
OnFragment1SpinnerChangedListener mCallback;
//Interface to alert the parent of a change in the Fragment 1 spinner.
public interface OnFragment1SpinnerChangedListener {
public void OnFragment1SpinnerChanged(String sSymbol);
}
//Pull the arguments from Bundle.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sSectorKey = getArguments() != null ?
getArguments().getString("SECTORKEY")
: "0";
}
//Display Fragment #1.
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
//Create a View object from fragment1_spinner
oFragment1Spinner =
inflater.inflate(R.layout.fragment1_spinner,container,false);
//Add the list of stocks to the spinner in this fragment
populateSpinner(sSectorKey);
return oFragment1Spinner;
}
//Hook up mCallback to the activity
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mCallback = (OnFragment1SpinnerChangedListener) activity;
}
//Populate Fragment #1 Spinner with appropriate data based on sector.
public void populateSpinner(String sSectorKey) {
EquityYoDatabaseAccess equityYoDB = new
EquityYoDatabaseAccess(getActivity().getApplicationContext());
SQLiteDatabase dbEquityYoDB = equityYoDB.getReadableDatabase();
String sSQLClause;
//Set up the SQL clause based on the iSectorKey
if (sSectorKey.equals("0")) {
sSQLClause="SELECT DISTINCT _id,Symbol || '/' || sName AS SYMBOL_SNAME FROM EquityYoSymbolMaster WHERE Type='S' AND SectorKey IS NOT NULL AND IndustryKey IS NOT NULL ORDER BY 2";
}
else {
sSQLClause="SELECT DISTINCT _id,Symbol || '/' || sName AS SYMBOL_SNAME FROM EquityYoSymbolMaster WHERE Type='S' AND SectorKey IS NOT NULL AND IndustryKey IS NOT NULL AND SectorKey=" + sSectorKey + " ORDER BY 2";
}
//Obtain a cursor for the query.
Cursor oCSR = dbEquityYoDB.rawQuery(sSQLClause, null);
//Attach the cursor to the Fragment #1 Spinner.
//Instantiate the Spinner as an object
Spinner oSP = (Spinner)
oFragment1Spinner.findViewById(R.id.idfragment1_spinner);
//Create a new instance of GenericSpinnerListener for the Spinner.
oSP.setOnItemSelectedListener(new cGenericSpinnerListener());
//Set up a cursor adapter for the ListView using oCSR
SimpleCursorAdapter adapter =
new SimpleCursorAdapter(oFragment1Spinner.getContext(),
android.R.layout.simple_spinner_item,
oCSR,
new String[] {"SYMBOL_SNAME"},
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);
return;
}
//*-----------------------------------------------------------------------*
//* Name: cGenericSpinnerListener *
//* Type: Class *
//* Purpose: This class implements the OnItemSelectedListener in order to *
//* to create a generic listener for the spinners that appear in *
//* the SlidingDrawer. *
//*-----------------------------------------------------------------------*
private class cGenericSpinnerListener implements OnItemSelectedListener {
private boolean isFirstTimeThru = true;
// The onItemSelected method is triggered when a user changes the
// selected item in a spinner.
@Override
public void onItemSelected(AdapterView> parent,
View view,
int position,
long id) {
if (isFirstTimeThru) {
isFirstTimeThru = false;
} else {
//Based on the new symbol, tell the parent Activity to update
// fragments 2, 3, 4, and 5.
String sSpinnerText = (String) ((TextView) view).getText();
String sSymbol = sSpinnerText.substring(0, sSpinnerText.indexOf("/"));
mCallback.OnFragment1SpinnerChanged(sSymbol);
}
}
@Override
public void onNothingSelected(AdapterView> parent) {
// NOP
}
} //end of private class GenericSpinnerListener
}
//p.523-528
package com.example.equityyostocks;
import java.text.DecimalFormat;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Fragment2DetailsControl extends Fragment {
String sSymbol = "A"; //By default, the symbol for sector zero is A.
View oFragment2Details;
int[] aiTextViewIDs = new int[] {
R.id.tvSTOCK_Symbol,
R.id.tvSTOCK_MaxMonthPriceNAV,
R.id.tvSTOCK_sName,
R.id.tvSTOCK_sInfo,
R.id.tvSTOCK_Sector,
R.id.tvSTOCK_Industry,
R.id.tvSTOCK_sMktCapNetAssets,
R.id.tvSTOCK_sAverage3MonthVolume,
R.id.tvSTOCK_sBeta,
R.id.tvSTOCK_sEPS,
R.id.tvSTOCK_sPERatio,
R.id.tvSTOCK_sTargetEstimate,
R.id.tvSTOCK_PriceGain,
R.id.tvSTOCK_ComputedYield,
R.id.tvSTOCK_ComputedDividend,
R.id.tvSTOCK_sDisplayedYield,
R.id.tvSTOCK_sDisplayedDividend,
R.id.tvSTOCK_DividendFrequency,
R.id.tvSTOCK_DividendConsistency,
R.id.tvSTOCK_DivGain
};
String[] asDetailColumnNames = new String[] {
"Symbol",
"MaxMonthPriceNAV",
"sName",
"sInfo",
"Sector",
"Industry",
"sMktCapNetAssets",
"sAverage3MonthVolume",
"sBeta",
"sEPS",
"sPERatio",
"sTargetEstimate",
"YearlyGrowth",
"ComputedYield",
"ComputedDividend",
"sDisplayedYield",
"sDisplayedDividend",
"DividendFrequency",
"DividendConsistency",
"YearlyDivCapGain"
};
String[] asDetailColumnLabels = new String[] {
"Symbol: ",
"Last Price: $",
"Company Name: ",
"Description: ",
"Sector: ",
"Industry: ",
"Market Capitalization: ",
"Average 3-Month Volume: ",
"Beta: ",
"Earnings Per Share(EPS): ",
"Price/Earnings (PE) Ratio: ",
"12-Month Target Estimate: ",
"$10,000 Growth (due to Price): $ ",
"Computed Yield: ",
"Computed Dividend: ",
"Displayed Yield: ",
"Displayed Dividend: ",
"Dividend Frequency: ",
"Dividend Consistency: ",
"$10,000 Growth (due to Div/CapGain): $"
};
//Pull the arguments from the Bundle.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sSymbol = getArguments() != null ? getArguments().getString("SYMBOL") : "A";
}
//Display the fragment.
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
//Create a View object from fragment2_details
oFragment2Details =
inflater.inflate(R.layout.fragment2_details,container,false);
//Add the list of stocks to the spinner in this fragment
populateDetails(sSymbol);
return oFragment2Details;
}
//Populate Fragment #2.
public void populateDetails(String sSymbol) {
EquityYoDatabaseAccess equityYoDB = new
EquityYoDatabaseAccess(getActivity().getApplicationContext());
SQLiteDatabase dbEquityYoDB = equityYoDB.getReadableDatabase();
String sSQLClause;
int iColumnIndex;
String sColumnValue="";
TextView aTextView;
String sColumnLabel="";
//Set up the SQL clause based on the iSectorKey
sSQLClause="SELECT * FROM vwEquityYoSymbolMasterSTOCKS WHERE Symbol=" +
'"' + sSymbol + '"';
//Obtain a cursor for the query.
Cursor oCSR = dbEquityYoDB.rawQuery(sSQLClause, null);
oCSR.moveToFirst();
//Only one line will come in from the database.
//Match up each textview with its corresponding data from the cursor.
//Loop around filling in the TextViews.
for(int i=0;i categories;
private List column1;
private ValueCategorySeries series;
private CategoryXAxis categoryAxis;
private NumericYAxis valueAxis;
EquityYoDatabaseAccess equityYoDB = new
EquityYoDatabaseAccess(getActivity().getApplicationContext());
SQLiteDatabase dbEquityYoDB = equityYoDB.getReadableDatabase();
String sSQLClause;
//Constructor
public cEquityYoIguanaPriceCharts(String pWhichData,DataChart igChart) {
categoryAxis = new CategoryXAxis();
valueAxis = new NumericYAxis();
categoryAxis.setLabelBrush(new SolidColorBrush(Color.BLACK));
valueAxis.setLabelBrush(new SolidColorBrush(Color.BLACK));
categories = new ArrayList();
categories.add("1");
categories.add("2");
categories.add("3");
categories.add("4");
categories.add("5");
categories.add("6");
categories.add("7");
categories.add("8");
categories.add("9");
categories.add("10");
categories.add("11");
categories.add("12");
column1 = new ArrayList();
column1.add(0.0f);
column1.add(0.0f);
column1.add(0.0f);
column1.add(0.0f);
column1.add(0.0f);
column1.add(0.0f);
column1.add(0.0f);
column1.add(0.0f);
column1.add(0.0f);
column1.add(0.0f);
column1.add(0.0f);
column1.add(0.0f);
//Create the X-Axis categories
categoryAxis.setDataSource(categories);
categoryAxis.setLabelFormatter(new CategoryAxis.LabelFormatter() {
@Override
public String format(CategoryAxis axis, Object item) {
String sItem = item.toString();
String sResult = "W";
if (sItem.contentEquals("1")) sResult="J";
if (sItem.contentEquals("2")) sResult="F";
if (sItem.contentEquals("3")) sResult="M";
if (sItem.contentEquals("4")) sResult="A";
if (sItem.contentEquals("5")) sResult="M";
if (sItem.contentEquals("6")) sResult="J";
if (sItem.contentEquals("7")) sResult="J";
if (sItem.contentEquals("8")) sResult="A";
if (sItem.contentEquals("9")) sResult="S";
if (sItem.contentEquals("10")) sResult="O";
if (sItem.contentEquals("11")) sResult="N";
if (sItem.contentEquals("12")) sResult="D";
return sResult;
}
});
igChart.scales().add(categoryAxis);
//Create the Y-Axis
valueAxis.setMinimumValue(valueAxis.getMinimumValue());
valueAxis.setMaximumValue(valueAxis.getMaximumValue());
valueAxis.setLabelFormatter(new NumericAxis.LabelFormatter() {
@Override
public String format(NumericAxis axis, float item, int precision) {
if (precision != numberFormat.getMinimumFractionDigits()) {
numberFormat.setMinimumFractionDigits(precision);
numberFormat.setMaximumFractionDigits(precision);
}
return numberFormat.format(item);
}
});
igChart.scales().add(valueAxis);
if (pWhichData == "P") {
series = new AreaSeries();
}
else if (pWhichData == "D") {
series = new ColumnSeries();
}
series.setCategoryAxis(categoryAxis);
series.setValueAxis(valueAxis);
series.setValueMember("");
series.setDataSource(column1);
igChart.series().add(series);
}
//Update the chart
public void UpdatePriceChart(String sSymbol,DataChart igChart) {
int iMonth;
float fDiv,fPrice;
EquityYoDatabaseAccess equityYoDB = new
EquityYoDatabaseAccess(getActivity().getApplicationContext());
SQLiteDatabase dbEquityYoDB = equityYoDB.getReadableDatabase();
String sSQLClause;
String sWhichData = "P";
String sType="S";
if (sWhichData=="P") {
//Query the database table EquityYoPriceData.
sSQLClause = "SELECT Month,CAST(TOTAL(Price) AS REAL) AS Price FROM (SELECT Month,Price FROM EquityYoPriceData WHERE Type=? AND Symbol=? UNION ALL SELECT Month,0 AS Price FROM EquityYoDateData) GROUP BY Month ORDER BY Month";
//Execute the query
Cursor oCsr = dbEquityYoDB.rawQuery(sSQLClause,
new String[] {sType,sSymbol});
oCsr.moveToFirst();
//Pull in the indices for the month and price to be used below.
int iMonthIndex = oCsr.getColumnIndex("Month");
int iPriceIndex = oCsr.getColumnIndex("Price");
//Fill in categories and column1 based on the Month and Price data.
if (oCsr.getCount()>0) {
while (oCsr.moveToNext()) {
//Pull the month and format it to a character string.
iMonth = oCsr.getInt(iMonthIndex);
//Pull the price.
fPrice = oCsr.getFloat(iPriceIndex);
//Fill in the arrays
categories.set(iMonth-1,Integer.toString(iMonth));
column1.set(iMonth-1,fPrice);
}
}
//Close the cursor.
oCsr.close();
valueAxis.setMinimumValue(0.90f * valueAxis.getMinimumValue());
valueAxis.setMaximumValue(1.10f * valueAxis.getMaximumValue());
series.setDataSource(null);
series.setDataSource(column1);
for (Series s: igChart.series()) {
s.notifyDataReset();
}
series.notifyDataUpdate(0, 12);
}
}
}
}
//p.531-535
package com.example.equityyostocks;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import com.iguanaui.controls.DataChart;
import com.iguanaui.controls.Series;
import com.iguanaui.controls.axes.CategoryAxis;
import com.iguanaui.controls.axes.CategoryXAxis;
import com.iguanaui.controls.axes.NumericAxis;
import com.iguanaui.controls.axes.NumericYAxis;
import com.iguanaui.controls.valuecategory.AreaSeries;
import com.iguanaui.controls.valuecategory.ColumnSeries;
import com.iguanaui.controls.valuecategory.ValueCategorySeries;
import com.iguanaui.graphics.SolidColorBrush;
public class Fragment4DividendChartControl extends Fragment {
String sSymbol = "A"; //By default, the symbol for sector zero is A.
View oFragment4DividendChart;
DataChart igDivChart;
cEquityYoIguanaDividendCharts DivChart;
//Pull the arguments from the Bundle.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sSymbol = getArguments() != null ? getArguments().getString("SYMBOL") : "A";
}
//Display the fragment.
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
//Create a View object from fragment4_dividend
oFragment4DividendChart =
inflater.inflate(R.layout.fragment4_dividend,container,false);
//Set up the price chart.
igDivChart = (DataChart)
oFragment4DividendChart.findViewById(R.id.igDivChart);
DivChart = new cEquityYoIguanaDividendCharts("D",igDivChart);
//Add the list of stocks to the spinner in this fragment
populateDividendChart(sSymbol);
return oFragment4DividendChart;
}
//Populate the chart with the data for the requested symbol.
public void populateDividendChart(String sSymbol) {
DivChart.UpdateDivChart(sSymbol, igDivChart);
}
//Class to handle the price charts.
public class cEquityYoIguanaDividendCharts {
//Set up a number format
final NumberFormat numberFormat = NumberFormat.getInstance();
private List categories;
private List column1;
private ValueCategorySeries series;
private CategoryXAxis categoryAxis;
private NumericYAxis valueAxis;
EquityYoDatabaseAccess equityYoDB = new
EquityYoDatabaseAccess(getActivity().getApplicationContext());
SQLiteDatabase dbEquityYoDB = equityYoDB.getReadableDatabase();
String sSQLClause;
//Constructor
public cEquityYoIguanaDividendCharts(String pWhichData,DataChart igChart) {
categoryAxis = new CategoryXAxis();
valueAxis = new NumericYAxis();
categoryAxis.setLabelBrush(new SolidColorBrush(Color.BLACK));
valueAxis.setLabelBrush(new SolidColorBrush(Color.BLACK));
categories = new ArrayList();
categories.add("1");
categories.add("2");
categories.add("3");
categories.add("4");
categories.add("5");
categories.add("6");
categories.add("7");
categories.add("8");
categories.add("9");
categories.add("10");
categories.add("11");
categories.add("12");
column1 = new ArrayList();
column1.add(0.0f);
column1.add(0.0f);
column1.add(0.0f);
column1.add(0.0f);
column1.add(0.0f);
column1.add(0.0f);
column1.add(0.0f);
column1.add(0.0f);
column1.add(0.0f);
column1.add(0.0f);
column1.add(0.0f);
column1.add(0.0f);
//Create the X-Axis categories
categoryAxis.setDataSource(categories);
categoryAxis.setLabelFormatter(new CategoryAxis.LabelFormatter() {
@Override
public String format(CategoryAxis axis, Object item) {
String sItem = item.toString();
String sResult = "W";
if (sItem.contentEquals("1")) sResult="J";
if (sItem.contentEquals("2")) sResult="F";
if (sItem.contentEquals("3")) sResult="M";
if (sItem.contentEquals("4")) sResult="A";
if (sItem.contentEquals("5")) sResult="M";
if (sItem.contentEquals("6")) sResult="J";
if (sItem.contentEquals("7")) sResult="J";
if (sItem.contentEquals("8")) sResult="A";
if (sItem.contentEquals("9")) sResult="S";
if (sItem.contentEquals("10")) sResult="O";
if (sItem.contentEquals("11")) sResult="N";
if (sItem.contentEquals("12")) sResult="D";
return sResult;
}
});
igChart.scales().add(categoryAxis);
//Create the Y-Axis
valueAxis.setMinimumValue(valueAxis.getMinimumValue());
valueAxis.setMaximumValue(valueAxis.getMaximumValue());
valueAxis.setLabelFormatter(new NumericAxis.LabelFormatter() {
@Override
public String format(NumericAxis axis, float item, int precision) {
if (precision != numberFormat.getMinimumFractionDigits()) {
numberFormat.setMinimumFractionDigits(precision);
numberFormat.setMaximumFractionDigits(precision);
}
return numberFormat.format(item);
}
});
igChart.scales().add(valueAxis);
if (pWhichData == "P") {
series = new AreaSeries();
}
else if (pWhichData == "D") {
series = new ColumnSeries();
}
series.setCategoryAxis(categoryAxis);
series.setValueAxis(valueAxis);
series.setValueMember("");
series.setDataSource(column1);
igChart.series().add(series);
}
//Update the chart
public void UpdateDivChart(String sSymbol,DataChart igChart) {
int iMonth;
float fDiv,fPrice;
EquityYoDatabaseAccess equityYoDB = new
EquityYoDatabaseAccess(getActivity().getApplicationContext());
SQLiteDatabase dbEquityYoDB = equityYoDB.getReadableDatabase();
String sSQLClause;
String sWhichData = "D";
String sType="S";
if (sWhichData=="D") {
//Query the database table EquityYoPriceData.
sSQLClause = "SELECT Month,CAST(TOTAL(Dividend) AS REAL) AS Dividend FROM (SELECT Month,Dividend FROM EquityYoDividendData WHERE Type=? AND Symbol=? UNION ALL SELECT Month,0 AS Dividend FROM EquityYoDateData) GROUP BY Month ORDER BY Month";
//Execute the query
Cursor oCsr = dbEquityYoDB.rawQuery(sSQLClause,
new String[] {sType,sSymbol});
oCsr.moveToFirst();
//Pull in the indices for the month and price to be used below.
int iMonthIndex = oCsr.getColumnIndex("Month");
int iDivIndex = oCsr.getColumnIndex("Dividend");
//Fill in categories and column1 based on the Month and Price data.
if (oCsr.getCount()>0) {
while (oCsr.moveToNext()) {
//Pull the month and format it to a character string.
iMonth = oCsr.getInt(iMonthIndex);
//Pull the price.
fDiv = oCsr.getFloat(iDivIndex);
//Fill in the arrays
categories.set(iMonth-1,Integer.toString(iMonth));
column1.set(iMonth-1,fDiv);
}
}
else {
for(int i=0;i<12;i++) {
categories.set(i,Integer.toString(i+1));
column1.set(i,0.0f);
}
}
//Close the cursor.
oCsr.close();
valueAxis.setMinimumValue(0.00f);
valueAxis.setMaximumValue(1.10f * valueAxis.getMaximumValue());
series.setDataSource(null);
series.setDataSource(column1);
for (Series s: igChart.series()) {
s.notifyDataReset();
}
series.notifyDataUpdate(0, 12);
}
}
}
}
//p.535-539
package com.example.equityyostocks;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.FloatMath;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class Fragment5AlsoViewedImageControl extends Fragment {
String sSymbol = "A"; //By default, the symbol for sector zero is A.
View oFragment5AlsoViewedImage;
private cAlsoViewed AlsoViewed;
private ImageView igAVImageView;
int iAlsoViewedMeasuredHeight=0;
int iAlsoViewedMeasuredWidth=0;
String sPV;
//Pull the arguments from the Bundle.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sSymbol = getArguments() != null ? getArguments().getString("SYMBOL") : "A";
iAlsoViewedMeasuredHeight = getArguments() != null ?
getArguments().getInt("HEIGHT") : 0;
iAlsoViewedMeasuredWidth = getArguments() != null ?
getArguments().getInt("WIDTH") : 0;
}
//Display the fragment.
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
//Create a View object from fragment5_alsoviewed
oFragment5AlsoViewedImage =
inflater.inflate(R.layout.fragment5_alsoviewed,container,false);
igAVImageView = (ImageView)
oFragment5AlsoViewedImage.findViewById(R.id.igAVImageView);
AlsoViewed = new cAlsoViewed(igAVImageView);
//Generate the image first time round.
generateAlsoViewedImage(sSymbol,
iAlsoViewedMeasuredWidth,
iAlsoViewedMeasuredWidth);
return oFragment5AlsoViewedImage;
}
//Generate the Also Viewed image.
public void generateAlsoViewedImage(String sSymbol,int piHeight,int piWidth) {
AlsoViewed.UpdateAlsoViewedImage(sSymbol, piHeight, piWidth);
}
//Class to handle generating the AlsoViewed bitmap image.
public class cAlsoViewed {
//String sSymbol = "";
String sPV = "-";
ImageView oAVIV = null;
EquityYoDatabaseAccess equityYoDB = new
EquityYoDatabaseAccess(getActivity().getApplicationContext());
SQLiteDatabase dbEquityYoDB = equityYoDB.getReadableDatabase();
String sSQLClause;
public cAlsoViewed(ImageView poAVImageView) {
oAVIV = poAVImageView;
}
public void UpdateAlsoViewedImage(String psSymbol,int piHeight,int piWidth) {
sSymbol = psSymbol;
iAlsoViewedMeasuredHeight = piHeight;
iAlsoViewedMeasuredWidth = piWidth;
//Pull the PV column from the database.
sSQLClause = "SELECT sPV FROM vwEquityYoSymbolMasterSTOCKS WHERE sPV IS NOT NULL AND SYMBOL='" + sSymbol + "'";
//Execute the query
Cursor oCSR = dbEquityYoDB.rawQuery(sSQLClause, null);
oCSR.moveToFirst();
int iColumnIndex = oCSR.getColumnIndex("sPV");
if (oCSR.getCount() > 0) {
sPV = (oCSR.isNull(iColumnIndex) ? "-" : oCSR.getString(iColumnIndex));
}
else {
sPV="-";
}
Rect oSymbolRect = new Rect();
Rect oTextRect = new Rect();
//Update the imageview's height.
oAVIV.setMinimumHeight(iAlsoViewedMeasuredHeight);
//Create a blank bitmap.
Bitmap oBM = Bitmap.createBitmap(iAlsoViewedMeasuredHeight,
iAlsoViewedMeasuredWidth,
Bitmap.Config.ARGB_8888);
//Create a Canvas associating the bitmap oBM with it,
Canvas oCanvas = new Canvas(oBM);
//Paint to canvas oCanvas.
oCanvas.drawARGB(255, 255, 255, 255);
//Create a Paint object for the line
Paint oPT_LINE = new Paint(Paint.DITHER_FLAG | Paint.ANTI_ALIAS_FLAG);
oPT_LINE.setARGB(255, 255, 255, 255);
oPT_LINE.setStrokeWidth(3);
oPT_LINE.setColor(Color.BLACK);
oPT_LINE.setStyle(Style.STROKE);
//Create a Paint object for the dot
Paint oPT_DOT = new Paint(Paint.DITHER_FLAG | Paint.ANTI_ALIAS_FLAG);
oPT_DOT.setARGB(255, 255, 255, 255);
oPT_DOT.setStrokeWidth(3);
oPT_DOT.setColor(Color.BLACK);
oPT_DOT.setStyle(Style.FILL_AND_STROKE);
//Create a Paint object for the text (black and bold)
Paint oPT_TEXT = new Paint(Paint.DITHER_FLAG | Paint.ANTI_ALIAS_FLAG);
oPT_TEXT.setARGB(255, 255, 255, 255);
oPT_TEXT.setTypeface(Typeface.DEFAULT_BOLD);
oPT_TEXT.setTextSize(24);
oPT_TEXT.setColor(Color.BLACK);
oPT_TEXT.setTextAlign(Paint.Align.CENTER);
//Determine the center of the canvas
int iCanvasHeight = oCanvas.getHeight();
int iCanvasWidth = oCanvas.getWidth();
float fCanvasHeight_CENTER = ( ((float) iCanvasHeight) / 2.0f);
float fCanvasWidth_CENTER = ( ((float) iCanvasWidth) / 2.0f);
if (sPV.contentEquals("-")) {
//Determine the bounding box for the text sSymbol.
oPT_TEXT.getTextBounds("NO DATA AVAILABLE",
0,
"NO DATA AVAILABLE".length(),
oSymbolRect);
//Place the sSymbol on the canvas.
oCanvas.drawText("NO DATA AVAILABLE",
fCanvasWidth_CENTER,
fCanvasHeight_CENTER + (oSymbolRect.height())/2,
oPT_TEXT);
//Place a line around the perimeter of the bitmap
oCanvas.drawRoundRect(new RectF(0f,0f,(float) piWidth,(float) piHeight),
20.0f, 20.0f, oPT_LINE);
} else {
//Place a line around the perimeter of the bitmap
oCanvas.drawRoundRect(new RectF(0f,0f,(float) piWidth,(float) piHeight),
20.0f, 20.0f, oPT_LINE);
//Determine the bounding box for the text sSymbol.
oPT_TEXT.getTextBounds(sSymbol, 0, sSymbol.length(), oSymbolRect);
//Place the sSymbol on the canvas.
oCanvas.drawText(sSymbol,
fCanvasWidth_CENTER,
fCanvasHeight_CENTER + (oSymbolRect.height())/2,
oPT_TEXT);
//Parse sPV in to an array.
String[] aPV = sPV.split((";"));
//Determine the number of entries in aPV
int iNbrPV = aPV.length;
//Determine the number of degrees we will place each entry
// in aPV on the SurfaceView.
float fDegrees = 360f / (float)iNbrPV;
//Determine the width of the text WWWWW.
Rect oWWWWWRect = new Rect();
oPT_TEXT.getTextBounds("WWWWW", 0, "WWWWW".length(), oWWWWWRect);
float fWWWWWWidth = (float) (Math.abs(oWWWWWRect.width()));
//Compute the x-coordinate from the right side based on WWWWW
// (assumes the translate() has occurred!)
float fXCoord = fCanvasWidth_CENTER - fWWWWWWidth;
//Draw each entry in sPV in turn on the surface starting at
// zero degrees and working clockwise fDegrees.
oCanvas.save();
oCanvas.translate(fCanvasWidth_CENTER, fCanvasHeight_CENTER);
//Place a circle around the sSymbol
oCanvas.drawCircle(0, 0, fWWWWWWidth/2f, oPT_LINE);
float fThisX;
float fThisY;
for(int i=0;i 0f && fThisDegrees < 180f ) {
oPT_TEXT.setTextAlign(Paint.Align.CENTER);
oCanvas.drawText(sThisSymbol,
fThisX,
fThisY + (oTextRect.height()/2),
oPT_TEXT);
} else if (fThisDegrees > 180f && fThisDegrees < 360f ) {
oPT_TEXT.setTextAlign(Paint.Align.CENTER);
oCanvas.drawText(sThisSymbol,
fThisX,
fThisY + (oTextRect.height()/2),
oPT_TEXT);
} else {
oPT_TEXT.setTextAlign(Paint.Align.CENTER);
oCanvas.drawText(sThisSymbol, fThisX, fThisY, oPT_TEXT);
}
}
oCanvas.restore();
}
//Set the bitmap, oBM, as the image of imageView1.
oAVIV.setImageBitmap(oBM);
}
}
}
//p.540
//Instantiate the five fragments.
oF1C_SP = new Fragment1SpinnerControl(); //Fragment #1: Spinner
oF2C_DE = new Fragment2DetailsControl(); //Fragment #2: Details
oF3C_PC = new Fragment3PriceChartControl(); //Fragment #3: Price Chart
oF4C_DC = new Fragment4DividendChartControl(); //Fragment #4: Dividend Chart
oF5C_AC = new Fragment5AlsoViewedImageControl(); //Fragment #5: Also Viewed Image
//p.540
//Set up a Bundle for use with the five fragment objects.
Bundle oBundleArgs = new Bundle();
//Populate oBundleArgs for use with the fragments.
oBundleArgs.putString("SECTORKEY", "0");
oBundleArgs.putString("SYMBOL", "A");
oBundleArgs.putInt("WIDTH", iDeviceWidth);
oBundleArgs.putInt("HEIGHT", iDeviceHeight);
//Fragment #1: Spinner
oF1C_SP.setArguments(oBundleArgs);
...and so on...
//p.540
//Begin a fragment transaction
oFT = oFM.beginTransaction();
//Add in the fragments
oFT.add(R.id.mainframe,oF1C_SP);
oFT.add(R.id.mainframe,oF2C_DE);
oFT.add(R.id.mainframe,oF3C_PC);
oFT.add(R.id.mainframe,oF4C_DC);
oFT.add(R.id.mainframe,oF5C_AC);
//Commit the change.
oFT.commitAllowingStateLoss();
//Execute Pending Transactions
oFM.executePendingTransactions();
//p.541
//Pull the arguments from the Bundle.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sSectorKey = getArguments() != null ? getArguments().getString("SECTORKEY")
: "0";
}
//p.541
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
//Create a View object from fragment1_spinner
oFragment1Spinner =
inflater.inflate(R.layout.fragment1_spinner,container,false);
//Add the list of stocks to the spinner in this fragment
populateSpinner(sSectorKey);
return oFragment1Spinner;
}
//p.542
OnFragment1SpinnerChangedListener mCallback;
//Interface used to alert the parent Activity of change in Fragment #1 Spinner.
public interface OnFragment1SpinnerChangedListener {
public void OnFragment1SpinnerChanged(String sSymbol);
}
//p.542
//Hook up mCallback to the activity
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mCallback = (OnFragment1SpinnerChangedListener) activity;
}
//p.542
//Create a new instance of GenericSpinnerListener for the Spinner.
oSP.setOnItemSelectedListener(new cGenericSpinnerListener());
//p.542-543
private class cGenericSpinnerListener implements OnItemSelectedListener {
private boolean isFirstTimeThru = true;
// The onItemSelected method is triggered when a user changes the
// selected item in a spinner.
@Override
public void onItemSelected(AdapterView> parent,
View view,
int position,
long id) {
if (isFirstTimeThru) {
isFirstTimeThru = false;
} else {
//Based on the new stock symbol, tell the parent Activity to
// update fragments 2, 3, 4, and 5.
String sSpinnerText = (String) ((TextView) view).getText();
String sSymbol = sSpinnerText.substring(0, sSpinnerText.indexOf("/"));
mCallback.OnFragment1SpinnerChanged(sSymbol);
}
}
@Override
public void onNothingSelected(AdapterView> parent) {
// NOP
}
} //end of private class GenericSpinnerListener
//p.543
public class MainActivity extends ActionBarActivity
implements Fragment1SpinnerControl.OnFragment1SpinnerChangedListener {
//p.543
//Called when the user changes the Fragment #1 spinner.
@Override
public void OnFragment1SpinnerChanged(String sSymbol) {
oF2C_DE.populateDetails(sSymbol);
oF3C_PC.populatePriceChart(sSymbol);
oF4C_DC.populateDividendChart(sSymbol);
oF5C_AC.generateAlsoViewedImage(sSymbol,iDeviceWidth,iDeviceWidth);
}
//p.543-544
//Override the onRestart method.
@Override
protected void onRestart() {
super.onRestart();
//Re-init the boolean variable bFirstTimeThrough to true.
bFirstTimeThrough=true;
//Remove the fragments.
oFT = oFM.beginTransaction();
oFT.remove(oF5C_AC);
oFT.remove(oF4C_DC);
oFT.remove(oF3C_PC);
oFT.remove(oF2C_DE);
oFT.remove(oF1C_SP);
oFT.commitAllowingStateLoss();
oFM.executePendingTransactions();
//Re-initialize the sector ListView
oSectorListView = (ListView) findViewById(R.id.sector_drawer);
String[] aSectorNames = getResources().getStringArray(R.array.sectors);
CustomArrayAdapter adapter = new CustomArrayAdapter(this,
android.R.layout.simple_list_item_1,
aSectorNames);
oSectorListView.setAdapter(adapter);
//Re-initialize the fragments
initialLoadFragments();
//Move the ScrollView up to the top.
oScrollView.scrollTo(0, 0);
}
//p.547
//p.547-548
//p.548
case R.id.mSearch:
Intent intentSearch = new Intent(MainActivity.this,SearchActivity.class);
startActivity(intentSearch);
return true;
//p.548-549
package com.example.equityyostocks;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class SearchActivity extends ActionBarActivity {
FragmentManager oFM;
FragmentTransaction oFT;
FragmentSearch oFC_SE;
FragmentSearch oFC_SE_OLD=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
//Access the FragmentManager.
oFM = (FragmentManager) getSupportFragmentManager();
}
//Handle the onClick event for the Go! button!
public void SearchDatabase(View view) {
//Set up a Bundle for use with the search fragment.
Bundle oBundleArgs = new Bundle();
//Pull the text in the TextView tvSearchText
EditText oET = (EditText) findViewById(R.id.etSearchText);
String sSearchText = oET.getText().toString().toUpperCase();
//Add the text to the Bundle
oBundleArgs.putString("SEARCHTEXT", sSearchText);
//Begin a fragment transaction
oFT = oFM.beginTransaction();
//Add a custom animation
oFT.setCustomAnimations(R.anim.my_slide_in_from_right,
R.anim.my_slide_out_to_right);
//Instantiate the search fragment.
oFC_SE = new FragmentSearch();
//Add the Bundle to oFC_SE
oFC_SE.setArguments(oBundleArgs);
//Remove previous fragment, if it exists.
if (oFC_SE_OLD != null) {
oFT.remove(oFC_SE_OLD);
oFC_SE_OLD=oFC_SE;
oFT.addToBackStack(null);
}
else if (oFC_SE_OLD == null) {
oFC_SE_OLD=oFC_SE;
}
//Add in the fragments
oFT.add(R.id.searchframe,oFC_SE);
//Commit the change.
oFT.commit();
//Execute Pending Transactions
oFM.executePendingTransactions();
}
//Close the SearchActivity.
public void CloseSearchActivity() {
this.finish();
}
}
//p.549-551
package com.example.equityyostocks;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.ListFragment;
import android.support.v4.widget.SimpleCursorAdapter;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class FragmentSearch extends ListFragment {
View oFragmentSearch;
String sSearchText="-";
//Pull the arguments from the setArguments Bundle.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sSearchText = getArguments() != null ?
getArguments().getString("SEARCHTEXT") : "-";
if (sSearchText.length() == 0) {
sSearchText="-";
}
}
//Display the fragment_search fragment and populate it.
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
//Create a View object from fragment_main
oFragmentSearch = inflater.inflate(R.layout.fragment_search,
container,
false);
//Populate the ListView based on the search criteria.
SimpleCursorAdapter adapter=populateListView(sSearchText);
//Set the list adapter here.
setListAdapter(adapter);
return oFragmentSearch;
}
//Populate the ListFragment by providing the appropriate adapter.
public SimpleCursorAdapter populateListView(String sSearchText) {
EquityYoDatabaseAccess equityYoDB = new
EquityYoDatabaseAccess(getActivity().getApplicationContext());
SQLiteDatabase dbEquityYoDB = equityYoDB.getReadableDatabase();
String sSQLClause="";
SimpleCursorAdapter adapter;
//Set up the SQL clause based on the iSectorKey
if (sSearchText.equals("-") || sSearchText.trim().length() == 0) {
//Display a alert indicating that no usable search criteria was entered.
DialogFragment oAlertNoDataFragment =
FragmentAlertSearchCriteriaControl.newInstance();
oAlertNoDataFragment.show(getFragmentManager(), "dialog");
//Set the adapter to null.
adapter=null;
}
else {
sSQLClause="SELECT _id,Symbol || '/' || sName AS SYMBOL_SNAME FROM vwEquityYoSymbolMasterSTOCKS WHERE sName LIKE '%" + sSearchText + "%' ORDER BY 1";
//Obtain a cursor for the query.
Cursor oCSR = dbEquityYoDB.rawQuery(sSQLClause, null);
oCSR.moveToFirst();
//Set up a cursor adapter for the ListView using oCSR
adapter = new SimpleCursorAdapter(oFragmentSearch.getContext(),
android.R.layout.simple_list_item_1,
oCSR,
new String[] {"SYMBOL_SNAME"},
new int[] {android.R.id.text1},0);
}
return adapter;
}
//Class to handle the no search results alert.
public static class FragmentAlertSearchCriteriaControl extends DialogFragment {
public static FragmentAlertSearchCriteriaControl newInstance() {
FragmentAlertSearchCriteriaControl oAlert = new
FragmentAlertSearchCriteriaControl();
return oAlert;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//Set up several string variables.
String sTitle = "Enter in your search criteria!";
String sSearchAgain = "Search Again";
String sGoHome = "Go Home";
//Create an Alert Dialog object via the Builder.
AlertDialog.Builder oADB = new AlertDialog.Builder(getActivity());
//Set the title of the AlertDialog
oADB.setTitle(sTitle);
//Set the icon to the app icon.
oADB.setIcon(R.drawable.ic_launcher);
//Create a listener associated with the Search Again click.
DialogInterface.OnClickListener onClickSearchAgainListener = new
DialogInterface.OnClickListener() {
//Close the dialog box itself when user clicks Search Again.
@Override
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel(); //Close this dialog box
}
};
//Associate the setNegativeButton with the listener above.
oADB.setNegativeButton(sSearchAgain, onClickSearchAgainListener);
//Create a listener associated with the Go Home click.
DialogInterface.OnClickListener onClickGoHomeListener = new
DialogInterface.OnClickListener() {
//Close the SearcActivity when user clicks Go Home.
@Override
public void onClick(DialogInterface dialog, int whichButton) {
((SearchActivity)getActivity()).CloseSearchActivity();
}
};
//Associate the setNegativeButton with the listener above.
oADB.setPositiveButton(sGoHome, onClickGoHomeListener);
//Create the AlertDialog and return it.
return oADB.create();
}
}
}
//p.552
//Set up a Bundle for use with the search fragment.
Bundle oBundleArgs = new Bundle();
//Pull the text in the TextView tvSearchText
EditText oET = (EditText) findViewById(R.id.etSearchText);
String sSearchText = oET.getText().toString().toUpperCase();
//Add the text to the Bundle
oBundleArgs.putString("SEARCHTEXT", sSearchText);
//Begin a fragment transaction
oFT = oFM.beginTransaction();
//Add a custom animation
oFT.setCustomAnimations(R.anim.my_slide_in_from_right,
R.anim.my_slide_out_to_right);
//Instantiate the search fragment.
oFC_SE = new FragmentSearch();
//Add the Bundle to oFC_SE
oFC_SE.setArguments(oBundleArgs);
//Remove previous fragment, if it exists.
if (oFC_SE_OLD != null) {
oFT.remove(oFC_SE_OLD);
oFC_SE_OLD=oFC_SE;
oFT.addToBackStack(null);
}
else if (oFC_SE_OLD == null) {
oFC_SE_OLD=oFC_SE;
}
//Add in the fragments
oFT.add(R.id.searchframe,oFC_SE);
//Commit the change.
oFT.commit();
//Execute Pending Transactions
oFM.executePendingTransactions();
//p.553
//Display a DialogFragment indicating that no usable search criteria was entered.
DialogFragment oAlertNoDataFragment =
FragmentAlertSearchCriteriaControl.newInstance();
oAlertNoDataFragment.show(getFragmentManager(), "dialog");
//p.553
//Create an Alert Dialog object via the Builder.
AlertDialog.Builder oADB = new AlertDialog.Builder(getActivity());
//p.553
String sTitle = "Enter in your search criteria!";
String sSearchAgain = "Search Again";
String sGoHome = "Go Home";
//p.553
//Set the title of the AlertDialog
oADB.setTitle(sTitle);
//Set the icon to the app icon.
oADB.setIcon(R.drawable.ic_launcher);
//p.554
//Create a listener associated with the Search Again click.
DialogInterface.OnClickListener onClickSearchAgainListener = new
DialogInterface.OnClickListener() {
//Close the dialog box itself when user clicks Search Again.
@Override
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel(); //Close this dialog box
}
};
//Associate the setNegativeButton with the listener above.
oADB.setNegativeButton(sSearchAgain, onClickSearchAgainListener);
//Create a listener associated with the Go Home click.
DialogInterface.OnClickListener onClickGoHomeListener = new
DialogInterface.OnClickListener() {
//Close the SearcActivity when user clicks Go Home.
@Override
public void onClick(DialogInterface dialog, int whichButton) {
((SearchActivity)getActivity()).CloseSearchActivity();
}
};
//Associate the setNegativeButton with the listener above.
ADB.setPositiveButton(sGoHome, onClickGoHomeListener);
//p.554
//Close the SearchActivity.
public void CloseSearchActivity() {
this.finish();
}
//*------------------------------------------------------------------------------------*
//* Chapter 31: Working with WebView and WebViewClient - pg 555 *
//*------------------------------------------------------------------------------------*
//p.555-556
//p.556
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");
}
}
//*------------------------------------------------------------------------------------*
//* Chapter 32: Styles and Themes - pg 558 *
//*------------------------------------------------------------------------------------*
//p.558
//p.558
//p.559
//p.559
//p.559-560
//p.560
//p.560
//p.561
...
//p.561
...
//p.561
...
//p.561
//p.562
//p.562
//p.563
//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.564
#FF0000
//p.564
//p.564-565
//*------------------------------------------------------------------------------------*
//* Chapter 33: Distributing Your Android Application - pg 566 *
//*------------------------------------------------------------------------------------*
//p.566
keytool -genkeypair -v -keystore com_example_andapp1.keystore -alias com_example_andapp1 -keyalg RSA -keysize 2048 -validity 10000
//p.567
keytool -list -keystore com_example_andapp1.keystore