Android Bootcamp Santa Fe GTUG

  • 2,726 views
Uploaded on

Presentacion de Android Bootcamp utilizada por Santa Fe GTUG. Actualizada por Horacio Alvarez.

Presentacion de Android Bootcamp utilizada por Santa Fe GTUG. Actualizada por Horacio Alvarez.

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
2,726
On Slideshare
0
From Embeds
0
Number of Embeds
1

Actions

Shares
Downloads
93
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide
  • Install (Unzip) SDK Configure Ecipse with SDK location Download Android platforms
  • Install (Unzip) SDK Configure Ecipse with SDK location Download Android platforms
  • Install (Unzip) SDK Configure Ecipse with SDK location Download Android platforms
  • 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'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's view hierarchy. It can itself be a complex view hierarchy. link to http://developer.android.com/images/activity_lifecycle.png?
  • 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
  • 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 "dip" and "dp", though "dp" is more consistent with "sp". sp:  Scale-independent Pixels - this is like the dp unit, but it is also scaled by the user'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's preference.
  • @+id/  means that we are creating this id in the namespace of our application 
  • 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.
  • Note that the width of EditText is defined in sp
  • ?
  • 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.
  • Second argument in  sp.getString("countries", "Brazil;Argentina;Mexico");  is the default value
  • 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 .

Transcript

  • 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.
    • ¿Qué es una aplicación Android?
    • Android Application
      • Java Language
      • Android SDK: compilar, empaquetar (.apk)
    • Múltiples actividades relacionadas entre sí
      • Alta cohesión
      • Bajo acoplamiento
    • Android Activity: A single screen with a user interface.
    • Ej: aplicación de email
        • Mostrar nuevos emails
        • Escribir nuevo email
        • Leer email
  • 3. Ciclo de vida Android Application
  • 4.
    • Bootcamp Pen Drive
    • Por favor, copie desde el pen drive la carpeta BOOTCAMP en alguna carpeta de su notebook
    • Contenido
    • android-sdk: entorno de desarrollo Android
    • eclipse: Eclipse Galileo 3.5.0
    • txt: código del tutorial
    • ADT-10.0.0.zip: plugin de Android para Eclipse
  • 5.
    • Prerrequisitos
    • Java SDK 1.6
    • Android SKD (eliminar carpeta c:Documents and Settings....android)
  • 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..." 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
  • 9. Crear un Virtual Device
  • 10. Iniciar Virtual Device Start… Launch
  • 11.
    • Proyecto Hello World
    • En Eclipse:
    • File -> New -> Other -> Android Project
    • Project Name:  HelloWorld
    • Build Target: Android 2.1
    • Properties:
    •   Application Name:  Hello World
    •   Package Name:  com.example.helloworld
    •   Create Activity:  HelloActivity
    • Finish
  • 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
  • 14. res/layout/main.xml LinearLayout
  • 15. res/layout/main.xml android:orientation="vertical" android:layout_width / android:layout_height "fill_parent" "wrap_content" "@string/hello"
  • 16. res/values/strings.xml Cadenas de caracteres de la aplicación
  • 17. Prueba Project -> Run (Ctrl + Shift + F11)
  • 18. Esto es una Activity
  • 19. Pero es aburrido.
  • 20. Upgrade: Una lista
  • 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.
    • Documentación de Referencia
    • http://developer.android.com/index.html
      • Framework Topics
      • Android Market Topics
      • Developing
      • Publishing
      • Best Practices
      • Web Applications
      • Appendix
  • 48. ¿Preguntas?