SlideShare une entreprise Scribd logo
1  sur  48
Android Bootcamp Elaborado (con adaptaciones) a partir de los tutoriales: http://developer.android.com/resources/tutorials/hello-world.html http://developer.android.com/resources/tutorials/views/index.html
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Ciclo de vida Android Application
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object]
Instalación del Plugin ADT en Eclipse En Eclipse: Help --> Install New Software.... --> Add --> Archive… Archive:   ADT-10.0.0.zip (en la carpeta BOOTCAMP) Name:  Android Plugin [x] Developer Tools [ ] DESMARQUE “Contact all update sites..." Next, Next, Finish..... Restart
Configurar Android SDK en Eclipse  En Eclipse: Window -> Preferences -> Android
Crear un Virtual Device Desde Eclipse ingresar al AVD Manager: AVD Manager -> Virtual Devices-> New Name:  MyAVD Target:  Android 2.1 SD Card:  - Skin:  built-in (HVGA) Create AVD
Crear un Virtual Device
Iniciar Virtual Device Start… Launch
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
src/com/example/HelloActivity.java - onCreate() - Bundle savedInstanceState - setContentView(R.layout.main);
res/layout/main.xml Define el layout de la Activity: LinearLayout   TableLayout RelativeLayout
res/layout/main.xml LinearLayout
res/layout/main.xml android:orientation="vertical" android:layout_width / android:layout_height "fill_parent" "wrap_content" "@string/hello"
res/values/strings.xml Cadenas de caracteres de la aplicación
Prueba Project -> Run (Ctrl + Shift + F11)
Esto es una Activity
Pero es aburrido.
Upgrade: Una lista
Crear res/layout/list_item.xml [código 1.txt] <? xml   version = &quot;1.0&quot;   encoding = &quot;utf-8&quot; ?> < TextView   xmlns:android = &quot;http://schemas.android.com/apk/res/android&quot; android:layout_width = &quot;fill_parent&quot; android:layout_height = &quot;fill_parent&quot; android:padding = &quot;10dp&quot; android:textSize = &quot;16sp&quot;   > </ TextView > Define el layout de cada item en la lista
Modificar res/layout/main.xml [código: 2.txt] <? xml   version = &quot;1.0&quot;   encoding = &quot;utf-8&quot; ?> < LinearLayout   xmlns:android = &quot;http://schemas.android.com/apk/res/android&quot; android:orientation = &quot;vertical&quot; android:layout_width = &quot;fill_parent&quot; android:layout_height = &quot;fill_parent&quot; > < ListView android:id = &quot;@+id/mylistview&quot;   android:layout_width = &quot;fill_parent&quot;   android:layout_height = &quot;fill_parent&quot;   /> </ LinearLayout >
HelloActivity.java [código: 3.txt] public class  HelloActivity  extends  Activity  implements  OnItemClickListener  {      static final  String[]  COUNTRIES  = {  &quot;Brazil&quot; ,               &quot;Argentina&quot; , &quot;Mexico&quot;  }; @Override public   void  onCreate(Bundle savedInstanceState) {      super .onCreate(savedInstanceState);      setContentView(R.layout. main );      ListView lv = (ListView) findViewById(R.id. mylistview );      lv.setAdapter( new  ArrayAdapter<String>( this ,           R.layout. list_item ,          COUNTRIES ));      lv.setOnItemClickListener( this ); } public void  onItemClick(AdapterView<?> parent, View view,       int  pos,  long  id) {      Toast.makeText(getApplicationContext(),           ((TextView) view).getText(),          Toast. LENGTH_SHORT ).show(); }
Prueba Project -> Run (Ctrl + Shift + F11)
Upgrade: Cuadro de Texto y Botón para Añadir
Modificar main.xml [Código 4.txt] <? xml   version = &quot;1.0&quot;   encoding = &quot;utf-8&quot; ?> < LinearLayout   xmlns:android = &quot;http://schemas.android.com/apk/res/android&quot; android:orientation = &quot;vertical&quot; android:layout_width = &quot;fill_parent&quot; android:layout_height = &quot;fill_parent&quot; >      < LinearLayout            android:layout_width = &quot;fill_parent&quot;          android:layout_height = &quot;wrap_content&quot;          android:orientation = &quot;horizontal&quot; >          < EditText               android:id = &quot;@+id/mytextview&quot;              android:layout_width = &quot;200sp&quot;              android:layout_height = &quot;wrap_content&quot;              android:text = &quot;&quot; />          < Button                android:id = &quot;@+id/mybutton&quot;                android:layout_width = &quot;wrap_content&quot;                android:layout_height = &quot;wrap_content&quot;              android:text = &quot;Añadir&quot; />      </ LinearLayout >      < ListView          android:id = &quot;@+id/mylistview&quot;            android:layout_width = &quot;fill_parent&quot;            android:layout_height = &quot;fill_parent&quot; /> </ LinearLayout >
Prueba Project -> Run (Ctrl + Shift + F11)
Ahora vamos a implementar...
HelloActivity.java [Código: 5.txt] package  com.example.helloworld;  import  ... public   class  HelloActivity  extends  Activity       implements  OnItemClickListener,  OnClickListener  {      private  List<String>  countries  =           new  ArrayList<String>();      private  ArrayAdapter<String>  adapter ;      @Override      public   void  onCreate(Bundle savedInstanceState) {          super .onCreate(savedInstanceState);          setContentView(R.layout. main );          countries .add( &quot;Mexico&quot; );          ListView lv = (ListView)               findViewById(R.id. mylistview );          adapter  =  new  ArrayAdapter<String>(              this , R.layout. list_item ,  countries );          lv.setAdapter( adapter );            lv.setOnItemClickListener( this );          Button btn = (Button) findViewById(R.id. mybutton );          btn.setOnClickListener( this ); } ...
... HelloActivity.java [Código: 5.txt] public   void  onItemClick(AdapterView<?> parent,       View view,  int  pos,  long  id) {      Toast. makeText (getApplicationContext(),                      ((TextView)view).getText(),      Toast. LENGTH_SHORT ).show(); } public   void  onClick(View view) {      EditText et = (EditText) findViewById(R.id. mytextview );      countries .add(et.getText().toString());      adapter .notifyDataSetChanged(); }
Prueba Project -> Run (Ctrl + Shift + F11)
Experimento Cerrar la aplicación (oprimiendo &quot;Home&quot;) Arrancarla nuevamente desde el menú de aplicaciones. ¿ Cuál  es el resultado?
Experimento El contenido se queda en la lista! ¿Por qué pasa eso?
Experimento 1 Porque Android hace &quot;Activity Lifecycle Management&quot; y puede mantener activas o cerrar Activities conforme la necesidad
Experimento 2 Cerrar la aplicación (oprimiendo &quot;Home&quot;) Hacer  Force Close  a traves del menú Menu -> Settings  -> Applications  ->  Manage Apps ->  Hello World -> Force Close  Arrancarla nuevamente desde el menú de aplicaciones. ¿Cuál es el resultado?
Experimento 2 Resultado: El contenido se fué.
¿Cómo grabar el contenido de una manera que sea persistente entre sesiones de mi aplicación?
Fácil ->  SharedPreferences Completo ->  Base de datos SQLite
SharedPreferences SharedPreferences sp = getPreferences(MODE_PRIVATE); Leer: String x = sp.getString(&quot;key&quot;, &quot;defaultvalue&quot;); Grabar: SharedPreferences.Editor spe = sp.edit(); spe.putString(&quot;key&quot;, &quot;value&quot;); spe.commit();
HelloActivity.java [Código: 6.txt] void  saveData() {      SharedPreferences.Editor spe =          getPreferences( MODE_PRIVATE ).edit();      StringBuilder sb =  new  StringBuilder();      for  ( int  i = 0; i <  countries .size(); i++)          sb.append( ((i == 0) ?  &quot;&quot;  :  &quot;;&quot; )               +  countries .get(i));      spe.putString( &quot;countries&quot; , sb.toString());      spe.commit(); } void  loadData() {      SharedPreferences sp =                   getPreferences( MODE_PRIVATE );      String countryList =       sp.getString( &quot;countries&quot; ,          &quot;Argentina;Brazil;Chile;Mexico&quot; );      for  (String country : countryList.split( &quot;;&quot; ))          countries .add(country); }
HelloActivity.java [Código: 6.txt] public   void  onCreate(Bundle savedInstanceState) {      super .onCreate(savedInstanceState);      setContentView(R.layout. main );      loadData();      ListView lv = (ListView)      findViewById(R.id. mylistview );      adapter  =  new  ArrayAdapter<String>( this ,      R.layout. list_item ,  countries );      lv.setAdapter( adapter );      lv.setOnItemClickListener( this );      Button btn = (Button) findViewById(R.id. mybutton );      btn.setOnClickListener( this ); }
HelloActivity.java [Código: 6.txt] public   void  onClick(View view) {      EditText et = (EditText)      findViewById(R.id. mytextview );      countries .add(et.getText().toString());      adapter .notifyDataSetChanged();      saveData(); }
Prueba Project -> Run (Ctrl + Shift + F11)
El &quot;Toast&quot; que aparece cuando se hace click en la lista es aburrido... ¿C ó mo se puede implementar una búsqueda en  la Web  en lugar del Toast?
... HelloActivity.java [Código: 7.txt] public   void  onItemClick(AdapterView<?> parent,       View view,  int  pos,  long  id) {      Uri uri =          Uri. parse ( &quot;http://en.wikipedia.org/&quot; +          &quot;wiki/&quot;  +      Uri. encode ( countries .get(pos),  null ));      Intent intent =  new  Intent(      Intent. ACTION_VIEW , uri);       startActivity(intent); }
Prueba Project -> Run (Ctrl + Shift + F11)
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
¿Preguntas?

Contenu connexe

Tendances

Membuat perhitungan luas persegi panjang pada adt
Membuat perhitungan luas persegi panjang pada adtMembuat perhitungan luas persegi panjang pada adt
Membuat perhitungan luas persegi panjang pada adtiswan_di
 
Membuat text to speech pada android
Membuat text to speech pada androidMembuat text to speech pada android
Membuat text to speech pada androidiswan_di
 
Construcción de Extensiones y Jetpacks
Construcción de Extensiones y Jetpacks Construcción de Extensiones y Jetpacks
Construcción de Extensiones y Jetpacks ccarruitero
 
Modul praktikum 9 - Android Sudaryatno
Modul praktikum 9 - Android SudaryatnoModul praktikum 9 - Android Sudaryatno
Modul praktikum 9 - Android SudaryatnoYatno Sudar
 
HTTP Interceptors com AngularJS
HTTP Interceptors com AngularJSHTTP Interceptors com AngularJS
HTTP Interceptors com AngularJSRodrigo Branas
 
함수형 프로그래밍과 안드로이드 테스팅
함수형 프로그래밍과 안드로이드 테스팅 함수형 프로그래밍과 안드로이드 테스팅
함수형 프로그래밍과 안드로이드 테스팅 MireukPark
 
Parent communication register android application Coding
Parent communication register android application CodingParent communication register android application Coding
Parent communication register android application CodingBhadra Gowdra
 
Practical JavaScript Programming - Session 2/8
Practical JavaScript Programming - Session 2/8Practical JavaScript Programming - Session 2/8
Practical JavaScript Programming - Session 2/8Wilson Su
 
Estandarizacion de macros
Estandarizacion de macrosEstandarizacion de macros
Estandarizacion de macrosgerariel
 
Utilizando diretivas com AngularJS
Utilizando diretivas com AngularJSUtilizando diretivas com AngularJS
Utilizando diretivas com AngularJSRodrigo Branas
 

Tendances (13)

Membuat perhitungan luas persegi panjang pada adt
Membuat perhitungan luas persegi panjang pada adtMembuat perhitungan luas persegi panjang pada adt
Membuat perhitungan luas persegi panjang pada adt
 
Membuat text to speech pada android
Membuat text to speech pada androidMembuat text to speech pada android
Membuat text to speech pada android
 
Construcción de Extensiones y Jetpacks
Construcción de Extensiones y Jetpacks Construcción de Extensiones y Jetpacks
Construcción de Extensiones y Jetpacks
 
ANT
ANTANT
ANT
 
Modul praktikum 9 - Android Sudaryatno
Modul praktikum 9 - Android SudaryatnoModul praktikum 9 - Android Sudaryatno
Modul praktikum 9 - Android Sudaryatno
 
HTTP Interceptors com AngularJS
HTTP Interceptors com AngularJSHTTP Interceptors com AngularJS
HTTP Interceptors com AngularJS
 
함수형 프로그래밍과 안드로이드 테스팅
함수형 프로그래밍과 안드로이드 테스팅 함수형 프로그래밍과 안드로이드 테스팅
함수형 프로그래밍과 안드로이드 테스팅
 
Spring Batch
Spring BatchSpring Batch
Spring Batch
 
Parent communication register android application Coding
Parent communication register android application CodingParent communication register android application Coding
Parent communication register android application Coding
 
Practical JavaScript Programming - Session 2/8
Practical JavaScript Programming - Session 2/8Practical JavaScript Programming - Session 2/8
Practical JavaScript Programming - Session 2/8
 
Estandarizacion de macros
Estandarizacion de macrosEstandarizacion de macros
Estandarizacion de macros
 
Examen final
Examen finalExamen final
Examen final
 
Utilizando diretivas com AngularJS
Utilizando diretivas com AngularJSUtilizando diretivas com AngularJS
Utilizando diretivas com AngularJS
 

En vedette

Katere so vaše prioritete?
Katere so vaše prioritete?Katere so vaše prioritete?
Katere so vaše prioritete?Damjana Kocjanc
 
Wm Credentials
Wm CredentialsWm Credentials
Wm Credentialspikwik
 
Johnstown Pa Defense Hub
Johnstown   Pa Defense HubJohnstown   Pa Defense Hub
Johnstown Pa Defense HubBob Shark
 
We’re all SMILES! Building Chemical Semantic Web Services with SADI, ChEBI, a...
We’re all SMILES! Building Chemical Semantic Web Services with SADI, ChEBI, a...We’re all SMILES! Building Chemical Semantic Web Services with SADI, ChEBI, a...
We’re all SMILES! Building Chemical Semantic Web Services with SADI, ChEBI, a...Michel Dumontier
 
FOTOS DE NUESTRAS FIESTAS
FOTOS DE NUESTRAS FIESTASFOTOS DE NUESTRAS FIESTAS
FOTOS DE NUESTRAS FIESTASlamasantigua
 
Konsep Presentasi Portal Berita
Konsep Presentasi Portal BeritaKonsep Presentasi Portal Berita
Konsep Presentasi Portal BeritaGameloft
 
Connect Globally For An Innovation Economy, Nastas Article In Moscow Times
Connect Globally For An Innovation Economy, Nastas Article In Moscow TimesConnect Globally For An Innovation Economy, Nastas Article In Moscow Times
Connect Globally For An Innovation Economy, Nastas Article In Moscow TimesThomas Nastas
 
F Business Presentatie 180609 Final
F Business Presentatie 180609 FinalF Business Presentatie 180609 Final
F Business Presentatie 180609 FinalPatrick Terranea
 
Plenaire Presentatie Jan Bommerez
Plenaire Presentatie Jan BommerezPlenaire Presentatie Jan Bommerez
Plenaire Presentatie Jan BommerezPatrick Terranea
 
Conducting Remote Task-Based Usability Testing on Your Mobile Website
Conducting Remote Task-Based Usability Testing on Your Mobile WebsiteConducting Remote Task-Based Usability Testing on Your Mobile Website
Conducting Remote Task-Based Usability Testing on Your Mobile WebsiteUserZoom
 
U of L and The Social Web
U of L and The Social WebU of L and The Social Web
U of L and The Social Webjackbr4
 
The Economics of Grid-Connected Hybrid Distributed Generation
The Economics of Grid-Connected Hybrid Distributed GenerationThe Economics of Grid-Connected Hybrid Distributed Generation
The Economics of Grid-Connected Hybrid Distributed GenerationIain Sanders
 
SP3 찬송가 옵션 작업후기 (Logic Audio)
SP3 찬송가 옵션 작업후기 (Logic Audio)SP3 찬송가 옵션 작업후기 (Logic Audio)
SP3 찬송가 옵션 작업후기 (Logic Audio)Yoon Lee
 

En vedette (20)

Katere so vaše prioritete?
Katere so vaše prioritete?Katere so vaše prioritete?
Katere so vaše prioritete?
 
Para ver y bajar los ppt
Para ver y bajar los pptPara ver y bajar los ppt
Para ver y bajar los ppt
 
Wm Credentials
Wm CredentialsWm Credentials
Wm Credentials
 
Johnstown Pa Defense Hub
Johnstown   Pa Defense HubJohnstown   Pa Defense Hub
Johnstown Pa Defense Hub
 
Burlata
BurlataBurlata
Burlata
 
We’re all SMILES! Building Chemical Semantic Web Services with SADI, ChEBI, a...
We’re all SMILES! Building Chemical Semantic Web Services with SADI, ChEBI, a...We’re all SMILES! Building Chemical Semantic Web Services with SADI, ChEBI, a...
We’re all SMILES! Building Chemical Semantic Web Services with SADI, ChEBI, a...
 
FOTOS DE NUESTRAS FIESTAS
FOTOS DE NUESTRAS FIESTASFOTOS DE NUESTRAS FIESTAS
FOTOS DE NUESTRAS FIESTAS
 
Yoshida thesis
Yoshida thesisYoshida thesis
Yoshida thesis
 
Konsep Presentasi Portal Berita
Konsep Presentasi Portal BeritaKonsep Presentasi Portal Berita
Konsep Presentasi Portal Berita
 
Connect Globally For An Innovation Economy, Nastas Article In Moscow Times
Connect Globally For An Innovation Economy, Nastas Article In Moscow TimesConnect Globally For An Innovation Economy, Nastas Article In Moscow Times
Connect Globally For An Innovation Economy, Nastas Article In Moscow Times
 
F Business Presentatie 180609 Final
F Business Presentatie 180609 FinalF Business Presentatie 180609 Final
F Business Presentatie 180609 Final
 
Plenaire Presentatie Jan Bommerez
Plenaire Presentatie Jan BommerezPlenaire Presentatie Jan Bommerez
Plenaire Presentatie Jan Bommerez
 
Conducting Remote Task-Based Usability Testing on Your Mobile Website
Conducting Remote Task-Based Usability Testing on Your Mobile WebsiteConducting Remote Task-Based Usability Testing on Your Mobile Website
Conducting Remote Task-Based Usability Testing on Your Mobile Website
 
U of L and The Social Web
U of L and The Social WebU of L and The Social Web
U of L and The Social Web
 
The Economics of Grid-Connected Hybrid Distributed Generation
The Economics of Grid-Connected Hybrid Distributed GenerationThe Economics of Grid-Connected Hybrid Distributed Generation
The Economics of Grid-Connected Hybrid Distributed Generation
 
Connexions Roy 2013
Connexions Roy 2013Connexions Roy 2013
Connexions Roy 2013
 
SP3 찬송가 옵션 작업후기 (Logic Audio)
SP3 찬송가 옵션 작업후기 (Logic Audio)SP3 찬송가 옵션 작업후기 (Logic Audio)
SP3 찬송가 옵션 작업후기 (Logic Audio)
 
Email etiquette
Email etiquetteEmail etiquette
Email etiquette
 
Arrs
ArrsArrs
Arrs
 
asdfghjkl;\'
asdfghjkl;\'asdfghjkl;\'
asdfghjkl;\'
 

Android Bootcamp Santa Fe GTUG

  • 1. Android Bootcamp Elaborado (con adaptaciones) a partir de los tutoriales: http://developer.android.com/resources/tutorials/hello-world.html http://developer.android.com/resources/tutorials/views/index.html
  • 2.
  • 3. Ciclo de vida Android Application
  • 4.
  • 5.
  • 6. Instalación del Plugin ADT en Eclipse En Eclipse: Help --> Install New Software.... --> Add --> Archive… Archive: ADT-10.0.0.zip (en la carpeta BOOTCAMP) Name: Android Plugin [x] Developer Tools [ ] DESMARQUE “Contact all update sites...&quot; Next, Next, Finish..... Restart
  • 7. Configurar Android SDK en Eclipse En Eclipse: Window -> Preferences -> Android
  • 8. Crear un Virtual Device Desde Eclipse ingresar al AVD Manager: AVD Manager -> Virtual Devices-> New Name: MyAVD Target: Android 2.1 SD Card: - Skin: built-in (HVGA) Create AVD
  • 10. Iniciar Virtual Device Start… Launch
  • 11.
  • 12. src/com/example/HelloActivity.java - onCreate() - Bundle savedInstanceState - setContentView(R.layout.main);
  • 13. res/layout/main.xml Define el layout de la Activity: LinearLayout TableLayout RelativeLayout
  • 15. res/layout/main.xml android:orientation=&quot;vertical&quot; android:layout_width / android:layout_height &quot;fill_parent&quot; &quot;wrap_content&quot; &quot;@string/hello&quot;
  • 16. res/values/strings.xml Cadenas de caracteres de la aplicación
  • 17. Prueba Project -> Run (Ctrl + Shift + F11)
  • 18. Esto es una Activity
  • 21. Crear res/layout/list_item.xml [código 1.txt] <? xml version = &quot;1.0&quot; encoding = &quot;utf-8&quot; ?> < TextView xmlns:android = &quot;http://schemas.android.com/apk/res/android&quot; android:layout_width = &quot;fill_parent&quot; android:layout_height = &quot;fill_parent&quot; android:padding = &quot;10dp&quot; android:textSize = &quot;16sp&quot; > </ TextView > Define el layout de cada item en la lista
  • 22. Modificar res/layout/main.xml [código: 2.txt] <? xml version = &quot;1.0&quot; encoding = &quot;utf-8&quot; ?> < LinearLayout xmlns:android = &quot;http://schemas.android.com/apk/res/android&quot; android:orientation = &quot;vertical&quot; android:layout_width = &quot;fill_parent&quot; android:layout_height = &quot;fill_parent&quot; > < ListView android:id = &quot;@+id/mylistview&quot;   android:layout_width = &quot;fill_parent&quot; android:layout_height = &quot;fill_parent&quot; /> </ LinearLayout >
  • 23. HelloActivity.java [código: 3.txt] public class HelloActivity extends Activity implements OnItemClickListener {      static final String[] COUNTRIES = { &quot;Brazil&quot; ,               &quot;Argentina&quot; , &quot;Mexico&quot; }; @Override public void onCreate(Bundle savedInstanceState) {      super .onCreate(savedInstanceState);      setContentView(R.layout. main );      ListView lv = (ListView) findViewById(R.id. mylistview );      lv.setAdapter( new ArrayAdapter<String>( this ,           R.layout. list_item ,          COUNTRIES ));      lv.setOnItemClickListener( this ); } public void onItemClick(AdapterView<?> parent, View view,       int pos, long id) {      Toast.makeText(getApplicationContext(),           ((TextView) view).getText(),          Toast. LENGTH_SHORT ).show(); }
  • 24. Prueba Project -> Run (Ctrl + Shift + F11)
  • 25. Upgrade: Cuadro de Texto y Botón para Añadir
  • 26. Modificar main.xml [Código 4.txt] <? xml version = &quot;1.0&quot; encoding = &quot;utf-8&quot; ?> < LinearLayout xmlns:android = &quot;http://schemas.android.com/apk/res/android&quot; android:orientation = &quot;vertical&quot; android:layout_width = &quot;fill_parent&quot; android:layout_height = &quot;fill_parent&quot; >      < LinearLayout          android:layout_width = &quot;fill_parent&quot;          android:layout_height = &quot;wrap_content&quot;          android:orientation = &quot;horizontal&quot; >          < EditText               android:id = &quot;@+id/mytextview&quot;              android:layout_width = &quot;200sp&quot;              android:layout_height = &quot;wrap_content&quot;              android:text = &quot;&quot; />          < Button                android:id = &quot;@+id/mybutton&quot;              android:layout_width = &quot;wrap_content&quot;              android:layout_height = &quot;wrap_content&quot;              android:text = &quot;Añadir&quot; />      </ LinearLayout >      < ListView          android:id = &quot;@+id/mylistview&quot;          android:layout_width = &quot;fill_parent&quot;          android:layout_height = &quot;fill_parent&quot; /> </ LinearLayout >
  • 27. Prueba Project -> Run (Ctrl + Shift + F11)
  • 28. Ahora vamos a implementar...
  • 29. HelloActivity.java [Código: 5.txt] package com.example.helloworld;  import ... public class HelloActivity extends Activity      implements OnItemClickListener, OnClickListener {      private List<String> countries =           new ArrayList<String>();      private ArrayAdapter<String> adapter ;      @Override      public void onCreate(Bundle savedInstanceState) {          super .onCreate(savedInstanceState);          setContentView(R.layout. main );          countries .add( &quot;Mexico&quot; );          ListView lv = (ListView)               findViewById(R.id. mylistview );          adapter = new ArrayAdapter<String>(              this , R.layout. list_item , countries );          lv.setAdapter( adapter );          lv.setOnItemClickListener( this );          Button btn = (Button) findViewById(R.id. mybutton );          btn.setOnClickListener( this ); } ...
  • 30. ... HelloActivity.java [Código: 5.txt] public void onItemClick(AdapterView<?> parent,      View view, int pos, long id) {      Toast. makeText (getApplicationContext(),                      ((TextView)view).getText(),      Toast. LENGTH_SHORT ).show(); } public void onClick(View view) {      EditText et = (EditText) findViewById(R.id. mytextview );      countries .add(et.getText().toString());      adapter .notifyDataSetChanged(); }
  • 31. Prueba Project -> Run (Ctrl + Shift + F11)
  • 32. Experimento Cerrar la aplicación (oprimiendo &quot;Home&quot;) Arrancarla nuevamente desde el menú de aplicaciones. ¿ Cuál es el resultado?
  • 33. Experimento El contenido se queda en la lista! ¿Por qué pasa eso?
  • 34. Experimento 1 Porque Android hace &quot;Activity Lifecycle Management&quot; y puede mantener activas o cerrar Activities conforme la necesidad
  • 35. Experimento 2 Cerrar la aplicación (oprimiendo &quot;Home&quot;) Hacer Force Close a traves del menú Menu -> Settings -> Applications -> Manage Apps -> Hello World -> Force Close Arrancarla nuevamente desde el menú de aplicaciones. ¿Cuál es el resultado?
  • 36. Experimento 2 Resultado: El contenido se fué.
  • 37. ¿Cómo grabar el contenido de una manera que sea persistente entre sesiones de mi aplicación?
  • 38. Fácil -> SharedPreferences Completo -> Base de datos SQLite
  • 39. SharedPreferences SharedPreferences sp = getPreferences(MODE_PRIVATE); Leer: String x = sp.getString(&quot;key&quot;, &quot;defaultvalue&quot;); Grabar: SharedPreferences.Editor spe = sp.edit(); spe.putString(&quot;key&quot;, &quot;value&quot;); spe.commit();
  • 40. HelloActivity.java [Código: 6.txt] void saveData() {      SharedPreferences.Editor spe =          getPreferences( MODE_PRIVATE ).edit();      StringBuilder sb = new StringBuilder();      for ( int  i = 0; i < countries .size(); i++)          sb.append( ((i == 0) ? &quot;&quot; : &quot;;&quot; )              + countries .get(i));      spe.putString( &quot;countries&quot; , sb.toString());      spe.commit(); } void loadData() {      SharedPreferences sp =                   getPreferences( MODE_PRIVATE );      String countryList =      sp.getString( &quot;countries&quot; ,          &quot;Argentina;Brazil;Chile;Mexico&quot; );      for (String country : countryList.split( &quot;;&quot; ))          countries .add(country); }
  • 41. HelloActivity.java [Código: 6.txt] public void onCreate(Bundle savedInstanceState) {      super .onCreate(savedInstanceState);      setContentView(R.layout. main );      loadData();      ListView lv = (ListView)      findViewById(R.id. mylistview );      adapter = new ArrayAdapter<String>( this ,      R.layout. list_item , countries );      lv.setAdapter( adapter );      lv.setOnItemClickListener( this );      Button btn = (Button) findViewById(R.id. mybutton );      btn.setOnClickListener( this ); }
  • 42. HelloActivity.java [Código: 6.txt] public void onClick(View view) {      EditText et = (EditText)      findViewById(R.id. mytextview );      countries .add(et.getText().toString());      adapter .notifyDataSetChanged();      saveData(); }
  • 43. Prueba Project -> Run (Ctrl + Shift + F11)
  • 44. El &quot;Toast&quot; que aparece cuando se hace click en la lista es aburrido... ¿C ó mo se puede implementar una búsqueda en la Web en lugar del Toast?
  • 45. ... HelloActivity.java [Código: 7.txt] public void onItemClick(AdapterView<?> parent,       View view, int pos, long id) {      Uri uri =          Uri. parse ( &quot;http://en.wikipedia.org/&quot; +          &quot;wiki/&quot; +      Uri. encode ( countries .get(pos), null ));      Intent intent = new Intent(      Intent. ACTION_VIEW , uri);      startActivity(intent); }
  • 46. Prueba Project -> Run (Ctrl + Shift + F11)
  • 47.

Notes de l'éditeur

  1. Install (Unzip) SDK Configure Ecipse with SDK location Download Android platforms
  2. Install (Unzip) SDK Configure Ecipse with SDK location Download Android platforms
  3. Install (Unzip) SDK Configure Ecipse with SDK location Download Android platforms
  4. onCreate()   Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity&apos;s previously frozen state, if there was one. Always followed by onStart(). setContentView():  Set the activity content to an explicit view. This view is placed directly into the activity&apos;s view hierarchy. It can itself be a complex view hierarchy. link to http://developer.android.com/images/activity_lifecycle.png?
  5. fill_parent :  means that the view wants to be as big as its parent (minus padding) wrap_content : means that the view wants to be just big enough to enclose its content (plus padding) String Resources: In Java: R.string. string_name In XML:@string/ string_name
  6. dp:  Density-independent Pixels - an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Note: The compiler accepts both &amp;quot;dip&amp;quot; and &amp;quot;dp&amp;quot;, though &amp;quot;dp&amp;quot; is more consistent with &amp;quot;sp&amp;quot;. sp:  Scale-independent Pixels - this is like the dp unit, but it is also scaled by the user&apos;s font size preference. It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen density and user&apos;s preference.
  7. @+id/  means that we are creating this id in the namespace of our application 
  8. R.id.mylistview  references entity declared on Resource file Toast:  A toast is a view containing a quick little message for the user. The toast class helps you create and show those. ArrayAdapter:  A concrete BaseAdapter that is backed by an array of arbitrary objects. By default this class expects that the provided resource id references a single TextView. If you want to use a more complex layout, use the constructors that also takes a field id. That field id should reference a TextView in the larger layout resource.
  9. Note that the width of EditText is defined in sp
  10. ?
  11. getPreferences() :  Retrieve a  SharedPreferences  object for accessing preferences that are private to this activity. MODE_PRIVATE : File creation mode: the default mode, where the created file can only be accessed by the calling application (or all applications sharing the same user ID).  MODE_WORLD_READABLE:  File creation mode: allow all other applications to have read access to the created file  MODE_WORLD_WRITABLE:  File creation mode: allow all other applications to have write access to the created file.
  12. Second argument in  sp.getString(&amp;quot;countries&amp;quot;, &amp;quot;Brazil;Argentina;Mexico&amp;quot;);  is the default value
  13. Intent:  An intent is an abstract description of an operation to be performed. An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed. The primary pieces of information in an intent are: action -- The general action to be performed, such as  ACTION_VIEW ,  ACTION_EDIT ,  ACTION_MAIN , etc. data -- The data to operate on, such as a person record in the contacts database, expressed as a  Uri .