Saturday, May 25, 2013

zz Make $30 an hour, no bachelor's degree required

No college degree? No problem.

Become a web developer.
The job is growing quickly, offers a median salary around $30 an hour, or $62,500 a year, and does not necessarily require a bachelor's degree.
That's because companies can't meet all the demand for workers. The job is still too new, and the labor pool is not quite large enough yet.
"There aren't enough bodies to fill all the seats," said Judi Wunderlich, co-founder of WunderLand, a Chicago recruiting firm specializing in digital, marketing and creative jobs.
Computer-related jobs are expected to grow by about 22% between 2010 and 2020, according to the Bureau of Labor Statistics.
And for web and mobile developers specifically, traditional college programs can hardly keep up. Even though many schools offer computer science courses, the field is changing so rapidly. The curriculum is rarely the same from year to year.
"If somebody wants to get into this job, it just doesn't make sense to get a college degree," Wunderlich said.
Related: Best jobs in America
As of 2010, about 38% of web developers had less than a four-year college degree, according to Census data. Instead, many workers in this field are self-trained.
Take for instance, Matt Kenefick. Growing up, he devoted himself to learning how to code. He viewed it mostly as a hobby and actually intended to become an architect. After just a few weeks in college though, architecture lost its appeal.
At 18, he dropped out and turned to coding as a full-time job. With little more than a high school diploma in hand, he started making around $65,000 a year.
Since then, he has worked for Percolate, Vimeo and other startups, and now, at age 25, he's earning more than six figures.
"Nobody really cares about your education in this field -- it's can you do it, or can you not?" he said. "Now, when I interview people and they list schooling on their resume, instead I ask, 'show me what you've done.'"
For beginners attracted to this field, some online programs like Codeacademy offer free training. Meanwhile, intensive training programs, which can cost several thousand dollars, are also popping up in major cities.
In Chicago, The Starter League offers a three-month class in web development for $8,000, and Mobile Makers offers an 8-week course in building iPhone and iPad apps for $7,000. General Assembly offers 12-week programs in various locations including New York, San Francisco, Los Angeles and Boston. That program costs $11,500.
You can also learn the old-fashioned way. Chris Lemke was driving trucks for a living, when he picked up two books on building mobile apps, back in December 2011.
"I liked math and decided to give it a whirl," he said. " A month or two later, I had a tipping calculator in the App Store."
About a year after tinkering on his own, the 29-year-old Lemke scored an apprenticeship with VOKAL Interactive, and is learning the rest
on the job.

To say this occupation is attainable for anyone though is a bit of stretch. It still requires some math chops and long hours of practice.
"You have to be a self-starter to go along with this," Kenefick said. "In the beginning, it was literally all day and all night, day after day, I was practicing and building up my portfolio. I'm pretty sure it's more work than going to college."
Web developer is among CareerCast's list of "best jobs that don't require four-year degrees." Other jobs on the list include plumber, electrician, paralegal and industrial machine repairer.

Tuesday, April 9, 2013

Levenberg-Marquardt Method

Levenberg-Marquardt Method

Levenberg-Marquardt is a popular alternative to the Gauss-Newton method of finding the minimum of a function F(x) that is a sum of squares of nonlinear functions,
 F(x)=1/2sum_(i=1)^m[f_i(x)]^2.
Let the Jacobian of f_i(x) be denoted J_i(x), then the Levenberg-Marquardt method searches in the direction given by the solution p to the equations
 (J_k^(T)J_k+lambda_kI)p_k=-J_k^(T)f_k,
where lambda_k are nonnegative scalars and I is the identity matrix. The method has the nice property that, for some scalar Delta related to lambda_k, the vector p_k is the solution of the constrained subproblem of minimizing ||J_kp+f_k||_2^2/2 subject to ||p||_2<=Delta (Gill et al. 1981, p. 136).
The method is used by the command FindMinimum[f, {x, x0}] when given the Method -> LevenbergMarquardt option.

Thursday, April 4, 2013

Numpy.ndarray-hstack function-Python

# |E|^2 Plot
import csv
newarray=np.zeros((114,1))
for ind,wvln in enumerate(plotWavelengths):
 xData = x_pos
 # get index
 nind  = np.where(lambdas==wvln)[0]
 yData = abs(E[:,nind])**2
 label = '%s nm' % wvln
 eplt.plot(xData,yData,label=label)
 newarray=np.hstack((newarray,yData))
np.savetxt("E squre.csv", newarray, delimiter=",")

Wednesday, April 3, 2013

Dump a NumPy array into a csv file-Python

import numpy
a = numpy.asarray([ [1,2,3], [4,5,6], [7,8,9] ])
numpy.savetxt("foo.csv", a, delimiter=",")

Transfermatrix.py------Python

#!/usr/bin/python
# 'Copyright' 2012 Kamil Mielczarek (kamil.m@utdallas.edu), University of Texas at Dallas
# Modifications:
#  10/2012 - Matlab code was ported to python, which is free and readily accessible to all :)
#
# Installation Notes:
#  Requires use of the 2.x Branch of python and
#  Matplotlib  : http://matplotlib.org/
#  Scipy  : http://www.scipy.org/
#  Numpy  : http://numpy.scipy.org/
#
#  A free turn-key solution for windows/mac users is available via Enthought in the 'EPD Free'
#  package which is available via:
#   http://www.enthought.com/products/epd_free.php
#
#  Linux users need to consult their distributions repositories for available packages

# Original MATLAB CODE WAS :
# Copyright 2010 George F. Burkhard, Eric T. Hoke, Stanford University
#     This program is free software: you can redistribute it and/or modify
#     it under the terms of the GNU General Public License as published by
#     the Free Software Foundation, either version 3 of the License, or
#     (at your option) any later version.
#
#     This program is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU General Public License for more details.
#
#     You should have received a copy of the GNU General Public License
#     along with this program.  If not, see <http://www.gnu.org/licenses/>.
# This program calculates the field profile, exciton generation profile
# and generated current from the wavelength dependent complex indicies of
# refraction in devices using the transfer matrix method. It assumes the light source
# light source is in an n=1 environment (air) and that the first layer is
# a thick superstrate, so that incoherent reflection from the air/1st layer
# interface is taken into account before the coherent interference is
# calculated in the remaining layers. If there is no thick superstrate,
# input 'Air' as the first layer so that the incoherent reflection calculates
# to 0.
# The program
# also returns the calculated short circuit current for the device in
# mA/cm^2 if the device had an IQE of 100%.
# The procedure was adapted from J. Appl. Phys Vol 86, No. 1 (1999) p.487
# and JAP 93 No. 7 p. 3693.
# George Burkhard and Eric Hoke February 5, 2010
# When citing this work, please refer to:
#
# G. F. Burkhard, E. T. Hoke, M. D. McGehee, Adv. Mater., 22, 3293.
# Accounting for Interference, Scattering, and Electrode Absorption to Make
# Accurate Internal Quantum Efficiency Measurements in Organic and Other
# Thin Solar Cells
# Modifications:
# 3/3/11 Parastic absorption (parasitic_abs) is calculated and made
# accessable outside of script.
## USER CONFIGURATION
# Build up the device, light enters from left to right, the layer names
# correspond to the csv filenames in the 'matDir' ignoring the material prefix.
# example : you have a material file named 'nk_P3HT.csv' the layer name would be 'P3HT'
# Layer thicknesses are in nm.
layers    = ['SiO2' , 'ITO' , 'PEDOT' , 'P3HTPCBM_BHJ' , 'Ca' , 'Al']
thicknesses  = [0 , 110 , 35  , 220 , 7 , 200]
plotGeneration = True  # Make generation plot , True/False
activeLayer  = 3   # indexing starts from 0
lambda_start = 350 # build a wavelength range to calculate over, starting wavelength (nm)
lambda_stop  = 800 # final wavelength (nm)
lambda_step  = 5  # wavelength step size
plotWavelengths = [400 , 500 , 600]  # Wavelengths to plot |E|^2 for, in nm.
# this is where the n/k optical constants for each material are stored.
# file format is : CSV (comma separated values)
# each materials file is prefixed with 'nk_' and the first 'matHeader' number of lines are skipped.
matDir   = 'matdata' # materials data
matPrefix  = 'nk_'  # materials data prefix
matHeader  = 1    # number of lines in header
##
## START OF CODE. DO NOT EDIT FURTHER.
##
import matplotlib.pyplot as plt
from os.path import join,isfile
from scipy.interpolate import interp1d
import numpy as np
# helper function
lambdas   = np.arange(lambda_start,lambda_stop+lambda_step,lambda_step,float)
t    = thicknesses
def openFile(fname):
 """
 opens files and returns a list split at each new line
 """
 fd = []
 if isfile(fname):
  fn = open(fname, 'r')
  fdtmp = fn.read()
  fdtmp = fdtmp.split('\n')
  # clean up line endings
  for f in fdtmp:
   f = f.strip('\n')
   f = f.strip('\r')
   fd.append(f)
  # make so doesn't return empty line at the end
  if len(fd[-1]) == 0:
   fd.pop(-1)
 else:
  dbug("%s Target is not a readable file" % fname)
 return fd
def get_ntotal(matName,lambdas):
 fname = join(matDir,'%s%s.csv' % (matPrefix,matName))
 fdata = openFile(fname)[matHeader:]
 # get data from the file
 lambList = []
 nList  = []
 kList  = []
 for l in fdata:
  wl , n , k = l.split(',')
  wl , n , k = float(wl) , float(n) , float(k)
  lambList.append(wl)
  nList.append(n)
  kList.append(k)
 # make interpolation functions
 int_n = interp1d(lambList,nList)
 int_k = interp1d(lambList,kList)
 # interpolate data
 kintList = int_k(lambdas)
 nintList = int_n(lambdas)
 # make ntotal
 ntotal = []
 for i,n in enumerate(nintList):
  nt = complex(n,kintList[i])
  ntotal.append(nt)
 return ntotal
def I_mat(n1,n2):
 # transfer matrix at an interface
 r = (n1-n2)/(n1+n2)
 t = (2*n1)/(n1+n2)
 ret = np.array([[1,r],[r,1]],dtype=complex)
 ret = ret / t
 return ret
def L_mat(n,d,l):
 # propagation matrix
 # n = complex dielectric constant
 # d = thickness
 # l = wavelength
 xi = (2*np.pi*d*n)/l
 L = np.array( [ [ np.exp(complex(0,-1.0*xi)),0] , [0,np.exp(complex(0,xi))] ] )
 return L

# Constants
h  =  6.65e-34  # Plank's Constant
c =  3.0e8  # Speed of Light
q = 1.6e-19  # electric charge
# PROGRAM
# initialize an array
n = np.zeros((len(layers),len(lambdas)),dtype=complex)
# load index of refraction for each material in the stack
for i,l in enumerate(layers):
 ni = np.array(get_ntotal(l,lambdas))
 n[i,:] = ni
# calculate incoherent power transmission through substrate
T_glass = abs((4.0*1.0*n[0,:])/((1+n[0,:])**2))
R_glass = abs((1-n[0,:])/(1+n[0,:]))**2
# calculate transfer marices, and field at each wavelength and position
t[0]   = 0
t_cumsum = np.cumsum(t)
x_pos  = np.arange((lambda_step/2.0),sum(t),lambda_step)
# get x_mat
comp1 = np.kron(np.ones( (len(t),1) ),x_pos)
comp2 = np.transpose(np.kron(np.ones( (len(x_pos),1) ),t_cumsum))
x_mat  = sum(comp1>comp2,1)-1  # might need to get changed to better match python indices
R  = lambdas*0.0
T  = lambdas*0.0
E  = np.zeros( (len(x_pos),len(lambdas)),dtype=complex )
# start looping
for ind,l in enumerate(lambdas):
 # calculate the transfer matrices for incoherent reflection/transmission at the first interface
 S = I_mat(n[0,ind],n[1,ind])
 for matind in np.arange(1,len(t)-1):
  mL = L_mat( n[matind,ind] , t[matind] , lambdas[ind] )
  mI = I_mat( n[matind,ind] , n[matind+1,ind])
  S  = np.asarray(np.mat(S)*np.mat(mL)*np.mat(mI))
 R[ind] = abs(S[1,0]/S[0,0])**2
 T[ind] = abs((2/(1+n[0,ind])))/np.sqrt(1-R_glass[ind]*R[ind])
 # good up to here
 # calculate all other transfer matrices
 for material in np.arange(1,len(t)):
  xi = 2*np.pi*n[material,ind]/lambdas[ind]
  dj = t[material]
  x_indices = np.nonzero(x_mat == material)
  x   = x_pos[x_indices]-t_cumsum[material-1]
  # Calculate S_Prime
  S_prime  = I_mat(n[0,ind],n[1,ind])
  for matind in np.arange(2,material+1):
   mL = L_mat( n[matind-1,ind],t[matind-1],lambdas[ind] )
   mI = I_mat( n[matind-1,ind],n[matind,ind] )
   S_prime  = np.asarray( np.mat(S_prime)*np.mat(mL)*np.mat(mI) )
  # Calculate S_dprime (double prime)
  S_dprime = np.eye(2)
  for matind in np.arange(material,len(t)-1):
   mI = I_mat(n[matind,ind],n[matind+1,ind])
   mL = L_mat(n[matind+1,ind],t[matind+1],lambdas[ind])
   S_dprime = np.asarray( np.mat(S_dprime) * np.mat(mI) * np.mat(mL) )
  # Normalized Electric Field Profile
  num = T[ind] * (S_dprime[0,0] * np.exp( complex(0,-1.0)*xi*(dj-x) ) + S_dprime[1,0]*np.exp(complex(0,1)*xi*(dj-x)))
  den = S_prime[0,0]*S_dprime[0,0]*np.exp(complex(0,-1.0)*xi*dj) + S_prime[0,1]*S_dprime[1,0]*np.exp(complex(0,1)*xi*dj)
  E[x_indices,ind] = num / den
# overall Reflection from device with incoherent reflections at first interface
Reflection = R_glass+T_glass**2*R/(1-R_glass*R)
#
# plot |E|^2 vs Position in device for wavelengths specified
#
eplt = plt.axes()
eplt.set_title('E-Field Intensity in Device')
eplt.set_ylabel('Normalized |E|$^2$Intensity')
eplt.set_xlabel('Position in Device , nm')
eplt.set_ylim(ymin=0)
# |E|^2 Plot
for ind,wvln in enumerate(plotWavelengths):
 xData = x_pos
 # get index
 nind  = np.where(lambdas==wvln)[0]
 yData = abs(E[:,nind])**2
 label = '%s nm' % wvln
 eplt.plot(xData,yData,label=label)
# Layer Bars
for matind in np.arange(2,len(t)+1):
 xpos = (t_cumsum[matind-2]+t_cumsum[matind-1])/2.0
 eplt.axvline(np.sum(t[0:matind]),linestyle=':')
 eplt.text(xpos,0.01,layers[matind-1],va='bottom',ha='center')
eplt.legend(loc='upper right')
plt.show()
# Absorption coefficient in 1/cm
a = np.zeros( (len(t),len(lambdas)) )
for matind in np.arange(1,len(t)):
 a[matind,:] = ( 4 * np.pi * np.imag(n[matind,:]) ) / ( lambdas * 1.0e-7 )
#
# Plot normalized intensity absorbed / cm3-nm at each position and wavelength
# as well as the total reflection expected from the device
#
aplt = plt.axes()
aplt.set_title('Fraction of Light Absorbed or Reflected')
aplt.set_xlabel('Wavelength , nm')
aplt.set_ylabel('Light Intensity Fraction')
Absorption = np.zeros( (len(t),len(lambdas)) )
for matind in np.arange(1,len(t)):
 Pos   = np.nonzero(x_mat == matind)
 AbsRate  = np.tile( (a[matind,:] * np.real(n[matind,:])),(len(Pos),1)) * (abs(E[Pos,:])**2)
 Absorption[matind,:] = np.sum(AbsRate,1)*lambda_step*1.0e-7
 aplt.plot(lambdas,Absorption[matind,:],label=layers[matind])
aplt.plot(lambdas,Reflection,label='Reflection')
aplt.legend(loc='upper right',ncol=3)
plt.show()
if plotGeneration:
 # load and interpolate AM1.5G Data
 am15_file = join(matDir,'AM15G.csv')
 am15_data = openFile(am15_file)[1:]
 am15_xData = []
 am15_yData = []
 for l in am15_data:
  x,y = l.split(',')
  x,y = float(x),float(y)
  am15_xData.append(x)
  am15_yData.append(y)
 am15_interp = interp1d(am15_xData,am15_yData,'linear')
 am15_int_y  = am15_interp(lambdas)
 #
 ActivePos = np.nonzero(x_mat == activeLayer)
 tmp1 = (a[activeLayer,:]*np.real(n[activeLayer,:])*am15_int_y)
 Q   = np.tile(tmp1,(np.size(ActivePos),1))*(abs(E[ActivePos,:])**2)
 # Exciton generatoion are
 Gxl  = (Q*1.0e-3)*np.tile( (lambdas*1.0e-9) , (np.size(ActivePos),1))/(h*c)
 if len(lambdas) == 1:
  lambda_step = 1
 else:
  lambda_step = (sorted(lambdas)[-1] - sorted(lambdas)[0])/(len(lambdas) - 1)
 Gx  = np.sum(Gxl,2)*lambda_step
 # plot
 gplt = plt.axes()
 gplt.set_title('Generation Rate in Device')
 gplt.set_xlabel('Position in Device , nm')
 gplt.set_ylabel('Generation Rate/sec-cm$^3$')
 gplt.set_xlim(0,t_cumsum[-1])
 gplt.plot(x_pos[ActivePos[0]] , Gx[0])
 # Layer Bars
 for matind in np.arange(2,len(t)+1):
  xpos = (t_cumsum[matind-2]+t_cumsum[matind-1])/2.0
  gplt.axvline(np.sum(t[0:matind]),linestyle=':')
  gplt.text(xpos,sorted(Gx[0])[0],layers[matind-1],va='bottom',ha='center')
 plt.show()
 # calculate Jsc
 Jsc = np.sum(Gx)*lambda_step*1.0e-7*q*1.0e3
 # calculate parasitic absorption
 parasitic_abs = (1.0 - Reflection - Absorption[activeLayer,:])
 print Jsc

Saturday, March 30, 2013

Android 4.0 tutorial-7

CLASS

MainActivity
*********************************************************************************
package com.nanolaser;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
    private final String TAG="Main Activity";
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
   

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.i(TAG, "onCreate");
      
      
    }
   
    @Override
 public void onStart() {
  // TODO Auto-generated method stub
  super.onStart();
   Log.i(TAG, "onStart");
 }
 
 @Override
 public void onResume() {
  // TODO Auto-generated method stub
  super.onResume();
   Log.i(TAG, "onResume");
 }
  
 @Override
 public void onPause() {
  // TODO Auto-generated method stub
  super.onPause();
  Log.i(TAG, "onPause");
 }


 @Override
 public void onStop() {
  // TODO Auto-generated method stub
  super.onStop();
  Log.i(TAG, "onStop");
 }


 @Override
 public void onDestroy() {
  // TODO Auto-generated method stub
  super.onDestroy();
  Log.i(TAG, "onDestroy");
 }

 public void buttonClick (View v){
  Log.i(TAG, "Button Clicked");
      final TextView textView=(TextView) findViewById(R.id.name);
     String text=textView.getText().toString();
  if (text.contains("world"))
  {
   textView.setText("Hello, Leize");
  }
  else
  {
   textView.setText("Hello, world");
  }
   
   
    }
}
*******************************************************************************
NewActivity
*******************************************************************************
package com.nanolaser;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class NewActivity extends Activity {
 @Override
 public void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.new_activity);
 }
 public void addComment(View v)
 {
  String name, comment, other;
  EditText nameIn=(EditText) findViewById (R.id.nameIn);
  EditText commentIn=(EditText) findViewById (R.id.commentIn);
  EditText otherIn=(EditText) findViewById (R.id.otherIn);
 
  name=nameIn.getText().toString();
  comment=commentIn.getText().toString();
  other=otherIn.getText().toString();
  TextView nameOut=(TextView)findViewById (R.id.name);
  TextView commentOut=(TextView)findViewById (R.id.comment);
  TextView otherOut=(TextView)findViewById (R.id.other);
 
  nameOut.setText(name);
  commentOut.setText(comment);
  otherOut.setText(other);
 
 }

}
********************************************************************************
layout
activity_main
********************************************************************************
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/name"
        android:text="@string/button_string"
        android:onClick="buttonClick"/>
</RelativeLayout>
*********************************************************************************
new_activity
********************************************************************************
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:padding="5dp" >
    <EditText
        android:id="@+id/nameIn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/name"
        android:inputType="text" >
    </EditText>
    <EditText
        android:id="@+id/commentIn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:hint="@string/comment"
        android:inputType="text" />
    <EditText
        android:id="@+id/otherIn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/other"
        android:inputType="text" />
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/addcomment"
        android:onClick="addComment"/>
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="@string/blank"
        android:textAppearance="?android:attr/textAppearanceMedium" />
    <TextView
        android:id="@+id/comment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/blank"
        android:textAppearance="?android:attr/textAppearanceMedium" />
    <TextView
        android:id="@+id/other"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/blank"
        android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>

*******************************************************************************
layout-land
activity_main
*******************************************************************************
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="horizontal"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="buttonClick"
        android:text="@string/button_string" />
</LinearLayout>
********************************************************************************
layout-port
activity_main
*******************************************************************************
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/name"
        android:text="@string/button_string"
        android:onClick="buttonClick"/>
</RelativeLayout>
**********************************************************************************
AndroidManifest
********************************************************************************
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.nanolaser"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.nanolaser.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Friday, March 29, 2013

Android 2.0-Tutorial 26

CLASS

Mainactivity.java
*****************************************************************
package com.nanolaser;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
   
}
*********************************************************************
Menu.java
***********************************************************************
package com.nanolaser;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Menu extends ListActivity{
 String classes[]={"MainActivity","TextPlay","Email","Camera"
   ,"Data","example5","example6"};

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setListAdapter(new ArrayAdapter<String>(Menu.this, android.R.layout.simple_list_item_1, classes));
 }
 @Override
 protected void onListItemClick(ListView l, View v, int position, long id) {
  // TODO Auto-generated method stub
  super.onListItemClick(l, v, position, id);
  String cheese=classes[position];
  try{
  Class ourClass=Class.forName("com.nanolaser."+cheese);
  Intent ourIntent=new Intent(Menu.this, ourClass);
  startActivity(ourIntent);
  }catch(ClassNotFoundException e){
   e.printStackTrace();
   }
 }


}

************************************************************************
Splash.java
************************************************************************
package com.nanolaser;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
public class Splash extends Activity{
     MediaPlayer ourSong;
 @Override
 protected void onCreate(Bundle TravisLoveBacon) {
  // TODO Auto-generated method stub
  super.onCreate(TravisLoveBacon);
  setContentView(R.layout.splash);
  ourSong=MediaPlayer.create(Splash.this, R.raw.music);
  ourSong.start();
  Thread timer=new Thread(){
   public void run(){
    try{
     sleep(5000);

    }catch(InterruptedException e){
     e.printStackTrace();
    }finally{
     Intent openStartingPoint=new Intent("com.nanolaser.MENU");
     startActivity(openStartingPoint);

    }

   }
  };
  timer.start();
 }
 @Override
 protected void onPause() {
  // TODO Auto-generated method stub
  super.onPause();
  ourSong.release();
  finish();
 }
   
}
*************************************************************************
TextPlay.java
*************************************************************************
package com.nanolaser;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;
public class TextPlay extends Activity{
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.text);
  Button chkCmd=(Button)findViewById(R.id.bResults);
  ToggleButton passTog=(ToggleButton)findViewById(R.id.tbPassword);
     EditText input=(EditText)findViewById(R.id.etCommands);
     TextView display=(TextView)findViewById(R.id.tvResults);

 }
}
************************************************************************
Email.java
************************************************************************
package com.nanolaser;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Email extends Activity implements View.OnClickListener {
 EditText personsEmail, intro, personsName, stupidThings, hatefulAction,
   outro;
 String emailAdd, beginning, name, stupidAction, hatefulAct, out;
 Button sendEmail;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.email);
  initializeVars();
  sendEmail.setOnClickListener(this);
 }
 private void initializeVars() {
  // TODO Auto-generated method stub
  personsEmail = (EditText) findViewById(R.id.etEmails);
  intro = (EditText) findViewById(R.id.etIntro);
  personsName = (EditText) findViewById(R.id.etName);
  stupidThings = (EditText) findViewById(R.id.etThings);
  hatefulAction = (EditText) findViewById(R.id.etAction);
  outro = (EditText) findViewById(R.id.etOutro);
  sendEmail = (Button) findViewById(R.id.bSentEmail);
 }
 public void onClick(View v) {
  // TODO Auto-generated method stub
  convertEditTextVarsIntoStringsAndYesThisIsAMethodWeCreated();
  String emailaddress[] = { emailAdd };
  String message = "Well hello "
    + name
    + " I just wanted to say "
    + beginning
    + ".  Not only that but I hate when you "
    + stupidAction
    + ", that just really makes me crazy.  I just want to make you "
    + hatefulAct
    + ".  Welp, thats all I wanted to chit-chatter about, oh and"
    + out
    + ".  Oh also if you get bored you should check out www.mybringback.com"
    + '\n' + "PS. I think I love you...   :( ";
        Intent emailIntent=new Intent(android.content.Intent.ACTION_SEND);
        emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, emailaddress);
        emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "I hate you");
        emailIntent.setType("plain/text");
        emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, message);
     startActivity(emailIntent);
 }
 private void convertEditTextVarsIntoStringsAndYesThisIsAMethodWeCreated() {
  // TODO Auto-generated method stub
  emailAdd = personsEmail.getText().toString();
  beginning = intro.getText().toString();
  name = personsName.getText().toString();
  stupidAction = stupidThings.getText().toString();
  hatefulAct = hatefulAction.getText().toString();
  out = outro.getText().toString();
 }
 @Override
 protected void onPause() {
  // TODO Auto-generated method stub
  super.onPause();
  finish();
 }
}
******************************************************************************
Data.java
******************************************************************************
package com.nanolaser;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Data extends Activity implements OnClickListener{
 Button start,startFor;
 EditText sendET;
 TextView gotAnswer;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.get);
  initialize();
 }
 private void initialize() {
  // TODO Auto-generated method stub
  start=(Button)findViewById(R.id.bSA);
  startFor=(Button)findViewById(R.id.bSAFR);
  sendET=(EditText)findViewById(R.id.etSend);
  gotAnswer=(TextView)findViewById(R.id.tvGot);
  start.setOnClickListener(this);
  startFor.setOnClickListener(this);

 }
 @Override
 public void onClick(View arg0) {
  // TODO Auto-generated method stub
  switch (arg0.getId()){
  case R.id.bSA:
   String bread=sendET.getText().toString();
   Bundle basket=new Bundle();
   basket.putString("key", bread);
   Intent a=new Intent(Data.this,OpenedClass.class);
   a.putExtras(basket);
   startActivity(a);
   break;
  case R.id.bSAFR:

   break;


  }

 }

}
*******************************************************************************
OpenedClass
*******************************************************************************
package com.nanolaser;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
public class OpenedClass extends Activity implements OnClickListener, OnCheckedChangeListener{
 TextView question,test;
 Button returnData;
 RadioGroup selectionList;
 String gotBread;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.send);
  initialize();
  Bundle gotBasket=getIntent().getExtras();
  gotBread=gotBasket.getString("key");
  question.setText(gotBread);

 }
 private void initialize() {
  // TODO Auto-generated method stub
  question=(TextView)findViewById(R.id.tvQuestion);
  test=(TextView)findViewById(R.id.tvText);
  returnData=(Button)findViewById(R.id.bReturn);
  returnData.setOnClickListener(this);
  selectionList=(RadioGroup)findViewById(R.id.rgAnswers);
  selectionList.setOnCheckedChangeListener(this);
 }
 @Override
 public void onClick(View v) {
  // TODO Auto-generated method stub

 }
 @Override
 public void onCheckedChanged(RadioGroup arg0, int arg1) {
  // TODO Auto-generated method stub
  switch(arg1){
  case R.id.rCrazy:
   break;
  case R.id.rSexy:
   break;
  case R.id.rBoth:
   break;
  }
 }



}
******************************************************************************
AboutUs.jave
******************************************************************************
package com.nanolaser;
import android.app.Activity;
import android.os.Bundle;
public class AboutUs extends Activity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.about);
 }



}

******************************************************************************
Camera.java
******************************************************************************
package com.nanolaser;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
public class Camera extends Activity implements View.OnClickListener{
 ImageButton ib;
 Button b;
 ImageView iv;
 Intent i;
 final static int cameraData=0;
 Bitmap bmp;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.photo);
  initialize();
  InputStream is=getResources().openRawResource(R.drawable.ic_launcher);
     bmp=BitmapFactory.decodeStream(is);
 }
 private void initialize(){
  //TODO auto-generated method stub
  iv=(ImageView)findViewById(R.id.ivReturnedPic);
  ib=(ImageButton)findViewById(R.id.ibTakepic);
  b=(Button)findViewById(R.id.bSerWall);
  b.setOnClickListener(this);
  ib.setOnClickListener(this);
 }
 @Override
 public void onClick(View v) {
  // TODO Auto-generated method stub
  switch(v.getId()){
   case R.id.bSerWall:
   try {
    getApplicationContext().setWallpaper(bmp);
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   break;
   case R.id.ibTakepic:
    i=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(i,cameraData);
   break;

  }

 }
 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  // TODO Auto-generated method stub
  super.onActivityResult(requestCode, resultCode, data);
  if (resultCode==RESULT_OK){
   Bundle extras=data.getExtras();
   bmp=(Bitmap)extras.get("data");
   iv.setImageBitmap(bmp);
  }
 }

}
******************************************************************************
Data.java
******************************************************************************
package com.nanolaser;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Data extends Activity implements OnClickListener{
 Button start,startFor;
 EditText sendET;
 TextView gotAnswer;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.get);
  initialize();
 }
 private void initialize() {
  // TODO Auto-generated method stub
  start=(Button)findViewById(R.id.bSA);
  startFor=(Button)findViewById(R.id.bSAFR);
  sendET=(EditText)findViewById(R.id.etSend);
  gotAnswer=(TextView)findViewById(R.id.tvGot);
  start.setOnClickListener(this);
  startFor.setOnClickListener(this);

 }
 @Override
 public void onClick(View arg0) {
  // TODO Auto-generated method stub
  switch (arg0.getId()){
  case R.id.bSA:
   String bread=sendET.getText().toString();
   Bundle basket=new Bundle();
   basket.putString("key", bread);
   Intent a=new Intent(Data.this,OpenedClass.class);
   a.putExtras(basket);
   startActivity(a);
   break;
  case R.id.bSAFR:
   Intent i=new Intent(Data.this,OpenedClass.class);
   startActivityForResult(i,0);
   break;

  }

 }
 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  // TODO Auto-generated method stub
  super.onActivityResult(requestCode, resultCode, data);
  if(resultCode==RESULT_OK){
   Bundle basket=data.getExtras();
   String s=basket.getString("answer");
   gotAnswer.setText(s);
  }
 }


}

******************************************************************************
SharedPrefs.java
******************************************************************************
package com.nanolaser;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class SharedPrefs extends Activity implements OnClickListener{
   EditText sharedData;
   TextView dataResults;
   public static String filename="MySharedString";
   SharedPreferences someData;
@Override
protected void onCreate(Bundle savedInstanceState) {
 // TODO Auto-generated method stub
 super.onCreate(savedInstanceState);
 setContentView(R.layout.sharedpreferences);
 setupVariables();
 someData=getSharedPreferences(filename,0);
}
private void setupVariables() {
 // TODO Auto-generated method stub
 Button save=(Button)findViewById(R.id.bSave);
 Button load=(Button)findViewById(R.id.bLoad);
 sharedData=(EditText)findViewById(R.id.etSharedPrefs);
 dataResults=(TextView)findViewById(R.id.tvLoadSharedPrefs);
 save.setOnClickListener(this);
 load.setOnClickListener(this);

}
@Override
public void onClick(View v) {
 // TODO Auto-generated method stub
 switch (v.getId()){
 case R.id.bSave:
  String stringData=sharedData.getText().toString();
  SharedPreferences.Editor editor=someData.edit();
  editor.putString("sharedString", stringData);
  editor.commit();
  break;
 case R.id.bLoad:
  someData=getSharedPreferences(filename,0);
  String dataReturned=someData.getString("sharedString", "cannot load data");
  dataResults.setText(dataReturned);
  break;

 }
}

}
******************************************************************************
InternalData.java
******************************************************************************
package com.nanolaser;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class InternalData extends Activity implements OnClickListener{
    EditText sharedData;
    TextView dataResults;
    FileOutputStream fos;
    String FILENAME="InteralString";
   
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.sharedpreferences);
  setupVariables();
 }
 private void setupVariables() {
  // TODO Auto-generated method stub
  Button save=(Button)findViewById(R.id.bSave);
  Button load=(Button)findViewById(R.id.bLoad);
  sharedData=(EditText)findViewById(R.id.etSharedPrefs);
  dataResults=(TextView)findViewById(R.id.tvLoadSharedPrefs);
  save.setOnClickListener(this);
  load.setOnClickListener(this);
  try {
   fos=openFileOutput(FILENAME,Context.MODE_PRIVATE);
   fos.close();
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 @Override
 public void onClick(View v) {
  // TODO Auto-generated method stub
  switch (v.getId()){
  case R.id.bSave:
   String data=sharedData.getText().toString();
   //Saving data via File
   /*File f=new File(FILENAME);
   try {
    fos=new FileOutputStream(f);
    fos.close();
   } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }*/
   try {
   fos=openFileOutput(FILENAME, Context.MODE_PRIVATE);
   fos.write(data.getBytes());
   fos.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }

   break;
  case R.id.bLoad:
   String collected=null;
   FileInputStream fis=null;
   try {
     fis=openFileInput(FILENAME);
    byte[] dataArray=new byte[fis.available()];
    while (fis.read(dataArray)!=-1){
     collected=new String(dataArray);
    }
   } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }finally{
    try {
     fis.close();
     dataResults.setText(collected);
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }

   break;

  }
 }

}
******************************************************************************
Flipper.java
******************************************************************************
package com.nanolaser;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ViewFlipper;
public class Flipper extends Activity implements OnClickListener {
 ViewFlipper flippy;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.flipper);
  flippy=(ViewFlipper)findViewById(R.id.viewFlipper1);
  flippy.setOnClickListener(this);
  flippy.setFlipInterval(500);
  flippy.startFlipping();
 }
 @Override
 public void onClick(View arg0) {
  // TODO Auto-generated method stub
  flippy.showNext();
 }


}
******************************************************************************
GFX.java
******************************************************************************
package com.nanolaser;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
public class GFX extends Activity{

 MyBringBack ourView;
 WakeLock wL;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
 
  //wake-lock
  PowerManager pM=(PowerManager)getSystemService(Context.POWER_SERVICE);
  wL=pM.newWakeLock(PowerManager.FULL_WAKE_LOCK, "whatever");
 
  super.onCreate(savedInstanceState);
  wL.acquire();
  ourView=new MyBringBack(this);
  setContentView(ourView);
 }
 @Override
 protected void onPause() {
  // TODO Auto-generated method stub
  super.onPause();
  wL.release();
 }

}
******************************************************************************
GFXSurface.java
******************************************************************************
package com.nanolaser;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
public class GFXSurface extends Activity implements OnTouchListener{
    MyBringBackSurface ourSurfaceView;
 float x,y, sX, sY, fX, fY,dX,dY,aniX,aniY,scaledX,scaledY;
 Bitmap test, plus;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  ourSurfaceView=new MyBringBackSurface(this);
  ourSurfaceView.setOnTouchListener(this);
  x=0;
  y=0;
  sX=0;
  sY=0;
  fX=0;
  fY=0;
  dX=dY=aniX=aniY=scaledX=scaledY=0;
  test=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
  plus=BitmapFactory.decodeResource(getResources(), R.drawable.plus);
  setContentView(ourSurfaceView);
 }

 @Override
 protected void onPause() {
  // TODO Auto-generated method stub
  super.onPause();
  ourSurfaceView.pause();
 }

 @Override
 protected void onResume() {
  // TODO Auto-generated method stub
  super.onResume();
  ourSurfaceView.resume();
 }

 @Override
 public boolean onTouch(View v, MotionEvent event) {
  // TODO Auto-generated method stub
  try {
   Thread.sleep(50);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 
  x=event.getX();
  y=event.getY();
  switch(event.getAction()){
  case MotionEvent.ACTION_DOWN:
   sX=event.getX();
   sY=event.getY();
   dX=dY=aniX=aniY=scaledX=scaledY=fX=fY=0;
   break;
  case MotionEvent.ACTION_UP:
   fX=event.getX();
   fY=event.getY();
   dX=fX-sX;
   dY=fY-sY;
   scaledX=dX/30;
   scaledY=dY/30;
   x=y=0;
   break;
  }
  return true;
 }

 public class MyBringBackSurface extends SurfaceView implements Runnable{
     SurfaceHolder ourHolder;
     Thread ourThread=null;
     boolean isRunning=false;
  public MyBringBackSurface(Context context) {
   // TODO Auto-generated constructor stub
   super(context);
   ourHolder=getHolder();
  
  }
 
     public void pause(){
     isRunning=false;
     while(true){
      try{
      ourThread.join();
      }catch(InterruptedException e){
       e.printStackTrace();
      }
        
      break;
    
     }
     ourThread=null;
     }
     public void resume(){
     isRunning=true;
     ourThread=new Thread(this);
  ourThread.start();
    
     }
  @Override
  public void run() {
   // TODO Auto-generated method stub
   while(isRunning){
    if(!ourHolder.getSurface().isValid())
     continue;
    Canvas canvas=ourHolder.lockCanvas();
    canvas.drawRGB(02, 02, 150);
    if(x!=0 && y!=0){
     canvas.drawBitmap(test, x-(test.getWidth()/2), y-(test.getHeight()/2), null);
    }
    if(sX!=0 && sY!=0){
     canvas.drawBitmap(plus, sX-(plus.getWidth()/2), sY-(plus.getHeight()/2), null);
    }
    if(fX!=0 && fY!=0){
     canvas.drawBitmap(test, fX-(test.getWidth()/2)-aniX, fY-(test.getHeight()/2)-aniY, null);
     canvas.drawBitmap(plus, fX-(plus.getWidth()/2), fY-(plus.getHeight()/2), null);
    }
    aniX=aniX+scaledX;
    aniY=aniY+scaledY;
    ourHolder.unlockCanvasAndPost(canvas);
   
   }
  }
 }

}
******************************************************************************
MyBringBack.java
******************************************************************************
package com.nanolaser;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.view.View;
public class MyBringBack extends View{
    Bitmap gBall;
    float changingY;
    Typeface font;
 public MyBringBack(Context context) {
  super(context);
  // TODO Auto-generated constructor stub
  gBall=BitmapFactory.decodeResource(getResources(), R.drawable.plus);
     changingY=0;
     font=Typeface.createFromAsset(context.getAssets(), "G-Unit.ttf");
 }
 @Override
 protected void onDraw(Canvas canvas) {
  // TODO Auto-generated method stub
  super.onDraw(canvas);
  canvas.drawColor(Color.WHITE);
  Paint textPaint=new Paint();
  textPaint.setARGB(50, 254, 10, 50);
  textPaint.setTextAlign(Align.CENTER);
  textPaint.setTextSize(50);
  textPaint.setTypeface(font);
  canvas.drawText("mybringback", getWidth()/2, 200, textPaint);
  canvas.drawBitmap(gBall, (canvas.getWidth()/2),changingY, null);
     if(changingY<canvas.getHeight()){
      changingY+=10;
         
     }else{
      changingY=0;
     }
     Rect middleRect=new Rect();
     middleRect.set(0, 400, canvas.getWidth(), 550);
     Paint ourBlue=new Paint();
     ourBlue.setColor(Color.BLUE);
     canvas.drawRect(middleRect, ourBlue);
     invalidate();
 }
   
}

******************************************************************************
ourViewClient.java
******************************************************************************
package com.nanolaser;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class ourViewClient extends WebViewClient {
 @Override
 public boolean shouldOverrideUrlLoading(WebView v,String url){
  v.loadUrl(url);
  return true;
 
 }
}
******************************************************************************
Prefs.java
******************************************************************************
package com.nanolaser;
import android.R;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.Fragment;

public class Prefs extends PreferenceActivity{


 @Override
 protected void onCreate(Bundle savedInstanceState) {
 
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
     
  addPreferencesFromResource(com.nanolaser.R.xml.prefs);
 }
}
******************************************************************************
SimpleBrowser.java
******************************************************************************
package com.nanolaser;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
public class SimpleBrowser extends Activity implements OnClickListener{
 EditText url;
 WebView ourBrow;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.simplebrowser);
  ourBrow=(WebView)findViewById(R.id.wvBrowser);
  ourBrow.getSettings().setJavaScriptEnabled(true);
  ourBrow.getSettings().setLoadsImagesAutomatically(true);
  ourBrow.getSettings().setUseWideViewPort(true);
  ourBrow.setWebViewClient(new ourViewClient());
  try{
  ourBrow.loadUrl("http://www.cnn.com");
  }catch(Exception e){
   e.printStackTrace();
  }
 
  Button go=(Button)findViewById(R.id.bGo);
  Button back=(Button)findViewById(R.id.bBack);
  Button refresh=(Button)findViewById(R.id.bRefresh);
  Button forward=(Button)findViewById(R.id.bForward);
  Button clearHistory=(Button)findViewById(R.id.bHistory);
  url=(EditText)findViewById(R.id.etURL);
  go.setOnClickListener(this);
  back.setOnClickListener(this);
  refresh.setOnClickListener(this);
  forward.setOnClickListener(this);
  clearHistory.setOnClickListener(this);
 
 }
 @Override
 public void onClick(View v) {
  // TODO Auto-generated method stub
  switch(v.getId()){
  case R.id.bGo:
  String theWebsite=url.getText().toString();
  ourBrow.loadUrl(theWebsite);
  InputMethodManager imm=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
  imm.hideSoftInputFromWindow(url.getWindowToken(), 0);
  break;
  case R.id.bBack:
  if(ourBrow.canGoBack())
  ourBrow.goBack();
  break;
  case R.id.bForward:
  if(ourBrow.canGoForward())
  ourBrow.goBack();
  break;
  case R.id.bRefresh:
  ourBrow.reload();
  break;
  case R.id.bHistory:
  ourBrow.clearHistory();
  break;
 
  }
 
 }

}
******************************************************************************
Slider.java
******************************************************************************
package com.nanolaser;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.SlidingDrawer;
import android.widget.SlidingDrawer.OnDrawerOpenListener;
public class Slider extends Activity implements OnDrawerOpenListener, OnClickListener, OnCheckedChangeListener{
 SlidingDrawer sd;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.sliding);
  Button handle1=(Button)findViewById(R.id.handle1);
  Button handle2=(Button)findViewById(R.id.handle2);
  Button handle3=(Button)findViewById(R.id.handle3);
  Button handle4=(Button)findViewById(R.id.handle4);
  CheckBox checkbox=(CheckBox)findViewById(R.id.cbSlidable);
  checkbox.setOnCheckedChangeListener(this);
  sd=(SlidingDrawer)findViewById(R.id.slidingD);
  sd.setOnDrawerOpenListener(this);
  handle1.setOnClickListener(this);
  handle2.setOnClickListener(this);
  handle3.setOnClickListener(this);
  handle4.setOnClickListener(this);
 }
 public void onClick(View arg0){
  switch(arg0.getId()){
  case R.id.handle1:
  sd.open();
  break;
  case R.id.handle2:
 
  break;
  case R.id.handle3:
  sd.toggle();
  break;
  case R.id.handle4:
  sd.close();
  break;
 
  }
 
 }
 public void onCheckedChanged(CompoundButton arg0, boolean arg1)
 {
 if(arg0.isChecked()){
  sd.lock();
 }else{
  sd.unlock();
 
 }
 
 }
 @Override
 public void onDrawerOpened() {
  // TODO Auto-generated method stub
  MediaPlayer mp=MediaPlayer.create(this, R.raw.music);
  mp.start();
 }
}
******************************************************************************
SoundStuff.java
******************************************************************************
package com.nanolaser;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
public class SoundStuff extends Activity implements OnClickListener, OnLongClickListener {
 SoundPool sp;
 int explosion=0;
 MediaPlayer mp;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  View v=new View(this);
  v.setOnClickListener(this);
  v.setOnLongClickListener(this);
  setContentView(v);
  sp=new SoundPool(5,AudioManager.STREAM_MUSIC,0);
  explosion=sp.load(this, R.raw.music, 1);
  mp=MediaPlayer.create(this, R.raw.music);
 }
 @Override
 public void onClick(View arg0) {
  // TODO Auto-generated method stub
  if(explosion!=0)
  sp.play(explosion, 1, 1, 0, 0, 1);
 }
 @Override
 public boolean onLongClick(View arg0) {
  // TODO Auto-generated method stub
  mp.start();
  return false;
 }
 }
******************************************************************************
Tabs.java
******************************************************************************
package com.nanolaser;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
public class Tabs extends Activity implements OnClickListener {
 TabHost th;
 TextView showResults;
 long start, stop;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.tabs);
  th=(TabHost)findViewById(R.id.tabhost);
  Button newTab=(Button)findViewById(R.id.bAddTab);
  Button bStart=(Button)findViewById(R.id.bStartWatch);
  Button bStop=(Button)findViewById(R.id.bStopWatch);
  showResults=(TextView)findViewById(R.id.tvShowResults);
  bStart.setOnClickListener(this);
  bStop.setOnClickListener(this);
 
 
  newTab.setOnClickListener(this);
  th.setup();
  TabSpec specs=th.newTabSpec("tag1");
  specs.setContent(R.id.tab1);
  specs.setIndicator("StopWatch");
  th.addTab(specs);
  specs=th.newTabSpec("tag2");
  specs.setContent(R.id.tab2);
  specs.setIndicator("Tab 2");
  th.addTab(specs);
  specs=th.newTabSpec("tag3");
  specs.setContent(R.id.tab3);
  specs.setIndicator("Add a Tab");
  th.addTab(specs);
  start=0;
 
 }
 @Override
 public void onClick(View arg0) {
  // TODO Auto-generated method stub
  switch(arg0.getId()){
  case R.id.bAddTab:
   TabSpec ourSpec=th.newTabSpec("tag1");
   ourSpec.setContent(new TabHost.TabContentFactory() {
   
    @Override
    public View createTabContent(String tag) {
     // TODO Auto-generated method stub
     TextView text=new TextView(Tabs.this);
     text.setText("You've created a new Tab!");
     return null;
    }
   });
   ourSpec.setIndicator("New");
   th.addTab(ourSpec);
   break;
  case R.id.bStartWatch:
   start=System.currentTimeMillis();
   break;
  case R.id.bStopWatch:
   stop=System.currentTimeMillis();
   if(start!=0){
    long result=stop-start;
    int millis=(int) result;
    int seconds=(int) result/1000;
    int minutes=seconds/60;
    millis=millis%100;
    seconds=seconds%60;
    showResults.setText(String.format("%d:%02d:%02d", minutes, seconds, millis));
   
   }
   break;
 
  }
 }
 }
******************************************************************************


LAYOUT

activity_main.xml
************************************************************************
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
</RelativeLayout>
*****************************************************************************
splash.xml
*****************************************************************************
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@drawable/splash_background"
   
    >
   
</LinearLayout>
*****************************************************************************
text.xml
*****************************************************************************
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="25dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <EditText
      android:layout_width="fill_parent" android:layout_height="wrap_content"
      android:id="@+id/etCommands"  android:hint="Type a Command"
      android:password="true"
        />
    <LinearLayout
        android:weightSum="100"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
    <Button
        android:layout_weight="20"
        android:id="@+id/bResults"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Try Command" />
    <ToggleButton
        android:layout_weight="80"
        android:paddingBottom="8dp"
        android:checked="true"
        android:id="@+id/tbPassword"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="ToggleButton" />
    </LinearLayout>
    <TextView
        android:id="@+id/tvResults"
        android:gravity="center"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="invalid" />
</LinearLayout>
**********************************************************************************
email.xml
**********************************************************************************
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_width="match_parent"
 android:weightSum="100" android:layout_height="match_parent">
 <ScrollView android:layout_weight="30" android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <LinearLayout android:orientation="vertical"
   android:layout_width="match_parent" android:layout_height="match_parent">
   <TextView android:text="Email address(es):"
    android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
   <EditText android:layout_height="wrap_content"
    android:layout_width="match_parent" android:id="@+id/etEmails">
   </EditText>
   <TextView android:text="Hateful Intro:"
    android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
   <EditText android:layout_height="wrap_content"
    android:layout_width="match_parent" android:id="@+id/etIntro"></EditText>
   <TextView android:text="Person's name" android:layout_width="wrap_content"
    android:layout_height="wrap_content"></TextView>
   <EditText android:layout_height="wrap_content"
    android:layout_width="match_parent" android:id="@+id/etName"></EditText>
   <TextView android:text="Stupid Things that this Person does"
    android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
   <EditText android:layout_height="wrap_content"
    android:layout_width="match_parent" android:id="@+id/etThings"></EditText>
   <TextView android:text="What you want to do to this person:"
    android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
   <EditText android:layout_height="wrap_content"
    android:layout_width="match_parent" android:id="@+id/etAction"></EditText>
   <TextView android:text="Hateful Outro" android:layout_width="wrap_content"
    android:layout_height="wrap_content"></TextView>
   <EditText android:layout_height="wrap_content"
    android:layout_width="match_parent" android:id="@+id/etOutro"></EditText>
  </LinearLayout>
 </ScrollView>
 <LinearLayout android:orientation="vertical"
  android:layout_width="match_parent" android:layout_weight="40"
  android:layout_height="fill_parent">
  <Button android:text="Send Email" android:id="@+id/bSentEmail"
   android:layout_width="fill_parent" android:layout_height="fill_parent"></Button>
 </LinearLayout>
 <LinearLayout android:orientation="vertical"
  android:layout_width="match_parent" android:layout_weight="30"
  android:layout_height="fill_parent">
  <AnalogClock android:id="@+id/analogClock1"
   android:layout_width="fill_parent" android:layout_height="fill_parent"></AnalogClock>
 </LinearLayout>
</LinearLayout>
*****************************************************************************
get.xml
*****************************************************************************
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
     >
    <EditText
        android:id="@+id/etSend"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >
      
    </EditText>
    <Button
        android:layout_below="@id/etSend"
        android:layout_alignParentRight="true"
        android:id="@+id/bSA"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="StartActivity" />
    <Button
        android:layout_toLeftOf="@id/bSA"
        android:layout_alignTop="@id/bSA"
        android:id="@+id/bSAFR"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="StartActivityForResult" />
    <TextView
        android:layout_below="@id/bSAFR"
        android:id="@+id/tvGot"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />
</RelativeLayout>
*****************************************************************************
photo.xml
*****************************************************************************
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <ImageView
        android:id="@+id/ivReturnedPic"
        android:layout_gravity="center"
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:src="@drawable/ic_launcher" />
    <ImageButton
        android:id="@+id/ibTakepic"
        android:layout_width="125dp"
        android:layout_gravity="center"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />
    <Button
        android:id="@+id/bSerWall"
        android:layout_width="125dp"
        android:layout_gravity="center"
        android:layout_height="wrap_content"
        android:text="Set Wallpaper" />
</LinearLayout>
*******************************************************************************
send.xml
*******************************************************************************
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/tvQuestion"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Leize is..." />
    <RadioGroup
        android:id="@+id/rgAnswers"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
        <RadioButton
            android:id="@+id/rCrazy"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="Crazy" />
        <RadioButton
            android:id="@+id/rSexy"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="SUPER SEXY" />
        <RadioButton
            android:id="@+id/rBoth"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Both" />
    </RadioGroup>
    <Button
        android:id="@+id/bReturn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Return" />
    <TextView
        android:id="@+id/tvText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />
</LinearLayout>
****************************************************************************
AndroidManifest.xml
**********************************************************************************
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.nanolaser"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="8" />
    <uses-permission android:name="android.permission.SET_WALLPAPER"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".Splash"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
                <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="com.nanolaser.MAINACTIVITY" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
                   <activity
            android:name=".Menu"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="com.nanolaser.MENU" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
                    <activity
            android:name=".TextPlay"
            android:label="@string/app_name" >
          
        </activity>
                 <activity
            android:name=".Email"
            android:label="@string/app_name" >
          
        </activity>
    
                 <activity
            android:name=".Camera"
            android:label="Camera Application"
            android:screenOrientation="portrait">
           
        </activity>
        
    
                 <activity
            android:name=".OpenedClass"
            android:label="OpenedClass"
            android:screenOrientation="portrait">
           
        </activity>
                         <activity
            android:name=".Data"
            android:label="Data"
            android:screenOrientation="portrait">
           
        </activity>
    </application>
</manifest>