• Save
Android Bootcamp - GTUG Uruguay
Upcoming SlideShare
Loading in...5
×
 

Android Bootcamp - GTUG Uruguay

on

  • 2,056 views

Android Bootcamp, Setiembre 2011. GTUG Uruguay.

Android Bootcamp, Setiembre 2011. GTUG Uruguay.

Statistics

Views

Total Views
2,056
Views on SlideShare
2,053
Embed Views
3

Actions

Likes
2
Downloads
0
Comments
0

2 Embeds 3

https://si0.twimg.com 2
https://twitter.com 1

Accessibility

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • 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 .

Android Bootcamp - GTUG Uruguay Android Bootcamp - GTUG Uruguay Presentation Transcript

  • Mi primera Aplicación Android ¡¡¡Bienvenidos!!! Setiembre 2011 Gabriel Kouyoumdjian Gabriel Olivera
  • GTUGs: Google Tecnology User Groups Android, AppEngine, APIs de productos, developer tools, proyectos open source  267 #capítulos (activos + incubando) 545 #eventos en los últimos seis meses En Uruguay: uy-gtug.org
  • ¿Por qué un Bootcamp de Android?
  • Cantidad estimada de Dispositivos con Android activados por d ía
  • Evolución de la Aplicaciones móviles disponibles en las principales tiendas
  •  
  •  
  • Lámparas, I’m Watch, TV
  • Vamos al Bootcamp!
    • Bootcamp Pendrive
    • Por favor, copia la carpeta BOOTCAMP a tu laptop.
    • Contenido:
      • android-sdk: developer kit
      • eclipse: IDE desarrollo
      • txt: código del tutorial
      • ADT: plugin para eclipse
  • Instalación del Plugin ADT En Eclipse: Help -> Install New Software.... -> Add Name: Android Plugin Archivo: ADT-12.0.0.zip (en la carpeta BOOTCAMP) [x] Developer Tools [ ] DESMARCAR "Check all update sites..." Next, next, next....., restart.
  • Configurar Ubicación de la SDK En Eclipse: Preferences -> Android SDK Location: BOOTCAMP/android-sdk.../ Click en "Apply" Click en "OK"
  • Crear un nuevo Emulador Window -> AVD Manager -> Virtual Devices->New Name: MyAVD Target: Android 2.1 Resolution/Built-In: HVGA Create AVD Close
  • Proyecto Hello World File -> New -> Android Project Project Name:   Hello World Build Target: Android 2.1 Properties:   Application Name:  Hello World   Package Name:  com.example.helloworld   Create Activity:  HelloActivity
  • src/com/example/HelloActivity.java - onCreate() - Bundle savedInstanceState - setContentView(R.layout.main);
  • El ciclo de vida de una Aplicación Android
  • res/layout/main.xml Definir el layout de la Actividad (Activity)
  • 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 que serán utilizadas por la aplicación
  • Prueba Project -> Run (Ctrl + Shift + F11)
  • Ejemplo de una Actividad
  • Hello World no está mal pero… ¿no es un poco básico?
  • Upgrade: Una lista
  • Crear res/layout/list_item.xml [1] <? 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 > Definir el layout de cada elemento de la lista
  • Modificar res/layout/main.xml [2] <? 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 [3] public class HelloActivity extends Activity implements OnItemClickListener {   static final String[] COUNTRIES = { &quot;Uruguay&quot; ,               &quot;Argentina&quot; , &quot;Brasil&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)
  • Editar Texto y botón para Agregar
  • Modificar main.xml [4] <? 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;Agregar&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)
  • Tiempo de implementar...
  • HelloActivity.java [5] 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;Uruguay&quot; );          countries .add( “Argentina&quot; ); countries .add( “Brasil&quot; ); countries .add( “Chile&quot; ); countries .add( “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 [5] 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 (presionando &quot;Home&quot;) Iniciar nuevamente a partir del menú de aplicaciones. ¿Cuál es el resultado?
  • Resultado El contenido continúa en la lista. ¿Por qué sucede esto?
  • Experimento Porque  Android hace lo que llamamos &quot;Activity Lifecycle Management&quot; ...y puede mantener activas o cerrar las Activities de acuerdo a las necesidades
  • Experimento 2 Cerrar la aplicación (presionando &quot;Home&quot;) Forzar el cierre de la aplicación a través del menú Menu -> Manage Apps -> Hello World -> Force Stop Iniciar nuevamente a partir del menú de aplicaciones. ¿Cuál es el resultado esta vez?
  • Resultado El Contenido de la lista desapareció
  • Persistencia Fácil -> SharedPreferences Completo -> SQLite
  • 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;); Escribir: SharedPreferences.Editor spe = sp.edit(); spe.putString(&quot;key&quot;, &quot;value&quot;); spe.commit();
  • HelloActivity.java [6] 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;Uruguay;Argentina;Brasil;Chile;Mexico&quot; );      for (String country : countryList.split( &quot;;&quot; ))          countries .add(country); }
  • HelloActivity.java [6] 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 [6] 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 al hacer click en la lista tampoco está muy bueno... ¿Cómo se pode implementar una búsqueda en la Web en vez del Toast?
  • ... HelloActivity.java [7] public void onItemClick(AdapterView<?> parent,       View view, int pos, long id) {      Uri uri = Uri.parse(&quot; http :// www.google.com/search?hl=en&q= &quot; + Uri.encode(countries.get(pos), null) + &quot;&btnI= &quot; + Uri.encode(&quot;I'm Feeling Lucky&quot;));      Intent intent = new Intent(      Intent. ACTION_VIEW , uri);      startActivity(intent); }
  • Referencias: 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
  • ¡Gracias! ¡¡¡Hasta la próxima!!! Gabriel Kouyoumdjian (gabriel.kb@gtugs.org) Gabriel Olivera (gabriel.olivera@gtugs.org)