Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Google Android - Aula 5 - Turma 2015.1

Google Android - Aula 5 - Turma 2015.1

Slides do curso "Desenvolvimento Google Android", aula 5, ministrado na Linux Fi (turma 2015.1).

Avatar for Eduardo Carneiro

Eduardo Carneiro

July 11, 2015
Tweet

More Decks by Eduardo Carneiro

Other Decks in Programming

Transcript

  1. 95 Webservice O que é Webservice? É uma funcionalidade disponibilizada

    em um endereço na rede através da Web como serviço. SOAP https://code.google.com/p/ksoap2-android/ REST JSON está se tornando um padrão!
  2. 96 JSON { "base" : "cmc stations", "clouds" : {

    "all" : 0 }, "cod" : 200, "coord" : { "lat" : -7.1200000000000001, "lon" : -34.859999999999999 }, "dt" : 1421694903, "id" : 3397277, "main" : { "grnd_level" : 1022.1900000000001, "humidity" : 78, "pressure" : 1022.1900000000001, "sea_level" : 1025.23, "temp" : 302.23399999999998, "temp_max" : 302.23399999999998, "temp_min" : 302.23399999999998 }, "name" : "Joao Pessoa", "sys" : { "country" : "BR", "message" : 0.062100000000000002, "sunrise" : 1421655363, "sunset" : 1421700269 }, "weather" : [ { "description" : "Sky is Clear", "icon" : "01d", "id" : 800, "main" : "Clear" } ], "wind" : { "deg" : 101.502, "speed" : 5.46 } } { "base" : "cmc stations", "clouds" : { "all" : 0 }, "cod" : 200, "coord" : { "lat" : -7.1200000000000001, "lon" : -34.859999999999999 }, "dt" : 1421694903, "id" : 3397277, "main" : { "grnd_level" : 1022.1900000000001, "humidity" : 78, "pressure" : 1022.1900000000001, "sea_level" : 1025.23, "temp" : 302.23399999999998, "temp_max" : 302.23399999999998, "temp_min" : 302.23399999999998 }, "name" : "Joao Pessoa", "sys" : { "country" : "BR", "message" : 0.062100000000000002, "sunrise" : 1421655363, "sunset" : 1421700269 }, "weather" : [ { "description" : "Sky is Clear", "icon" : "01d", "id" : 800, "main" : "Clear" } ], "wind" : { "deg" : 101.502, "speed" : 5.46 } } http://api.openweathermap.org/data/2.5/weather?q=Joao%20Pessoa,br http://api.openweathermap.org/data/2.5/weather?q=Joao%20Pessoa,br Visualizador: http://jsonviewer.stack.hu/ JavaScript Object Notation http://www.json.org/
  3. 97 HTTP try { HttpClient client = new DefaultHttpClient(); HttpGet

    get = new HttpGet("http://ip.jsontest.com/"); HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = entity.getContent(); BufferedReader bReader = new BufferedReader( new InputStreamReader(inputStream, "iso-8859-1"), 8); StringBuilder sBuilder = new StringBuilder(); String line = null; while ((line = bReader.readLine()) != null) { sBuilder.append(line + "\n"); } inputStream.close(); String jsonStr = sBuilder.toString()); } } catch (IOException ex) { ex.printStackTrace(); } try { HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet("http://ip.jsontest.com/"); HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = entity.getContent(); BufferedReader bReader = new BufferedReader( new InputStreamReader(inputStream, "iso-8859-1"), 8); StringBuilder sBuilder = new StringBuilder(); String line = null; while ((line = bReader.readLine()) != null) { sBuilder.append(line + "\n"); } inputStream.close(); String jsonStr = sBuilder.toString()); } } catch (IOException ex) { ex.printStackTrace(); } <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
  4. 98 Jackson try { HttpClient client = new DefaultHttpClient(); HttpGet

    get = new HttpGet("http://ip.jsontest.com/"); HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = entity.getContent(); BufferedReader bReader = new BufferedReader( new InputStreamReader(inputStream, "iso-8859-1"), 8); StringBuilder sBuilder = new StringBuilder(); String line = null; while ((line = bReader.readLine()) != null) { sBuilder.append(line + "\n"); } inputStream.close(); String jsonStr = sBuilder.toString()); ObjectMapper mapper = new ObjectMapper(); IP w = mapper.readValue(jsonStr, IP.class); } } catch (IOException ex) { ex.printStackTrace(); } try { HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet("http://ip.jsontest.com/"); HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = entity.getContent(); BufferedReader bReader = new BufferedReader( new InputStreamReader(inputStream, "iso-8859-1"), 8); StringBuilder sBuilder = new StringBuilder(); String line = null; while ((line = bReader.readLine()) != null) { sBuilder.append(line + "\n"); } inputStream.close(); String jsonStr = sBuilder.toString()); ObjectMapper mapper = new ObjectMapper(); IP w = mapper.readValue(jsonStr, IP.class); } } catch (IOException ex) { ex.printStackTrace(); } compile 'org.codehaus.jackson:jackson-mapper-asl:1.9.13' compile 'org.codehaus.jackson:jackson-mapper-asl:1.9.13'
  5. 100 Persistência O Android disponibiliza diversas opções para que um

    aplicativo persista seus dados, sendo as seguintes: Shared Preferences Armazena dados privados em pares de chave e valor. Internal Storage Armazena dados privados na memória do dispositivo. External Storage Armazena dados públicos na memória do dispositivo. Banco SQLite Armazena dados estruturados em uma base privada. Rede Armazena dados na web em no seu servidor.
  6. 101 Shared Preferences A classe SharedPreferences disponibiliza um framework que

    permite que sejam salvos e recuperados dados em pares chave-valor de tipos primitivos. Podemos salvar booleans, floats, ints, longs e strings. SharedPreferences settings = getSharedPreferences("prefs", 0); boolean silent = settings.getBoolean("silentMode", false); SharedPreferences settings = getSharedPreferences("prefs", 0); boolean silent = settings.getBoolean("silentMode", false); SharedPreferences settings = getSharedPreferences("prefs", 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("silentMode", false); editor.commit(); SharedPreferences settings = getSharedPreferences("prefs", 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("silentMode", false); editor.commit();
  7. 102 PreferenceActivity <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <CheckBoxPreference android:key="pref_sync" android:title="@string/pref_sync" android:summary="@string/pref_sync_summ" android:defaultValue="true" />

    </PreferenceScreen> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <CheckBoxPreference android:key="pref_sync" android:title="@string/pref_sync" android:summary="@string/pref_sync_summ" android:defaultValue="true" /> </PreferenceScreen> public class SettingsActivity extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } } public class SettingsActivity extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } } http://developer.android.com/guide/topics/ui/settings.html
  8. 103 Banco de Dados O Android provê suporte completo ao

    banco de dados SQLite. Qualquer banco criado será acessado apenas pela aplicação. 1º Definir Schema e Contrato 2º Criar o banco com SQL Helper 3º Gravar dados no banco 4º Ler dados do banco http://ormlite.com/sqlite_java_android_orm.shtml https://www.sqlite.org/datatype3.html
  9. 104 Schema e Contrato public final class WeatherContract { public

    WeatherContract() {} public static abstract class City implements BaseColumns { public static final String TABLE_NAME = "city"; public static final String COLUMN_NAME_CITY_ID = "cityid"; public static final String COLUMN_NAME_NAME = "name"; public static final String COLUMN_NAME_LAST_UPDATE = "lastupdate"; public static final String COLUMN_NAME_LATITUDE = "latitude"; public static final String COLUMN_NAME_LONGITUDE = "longitude"; ... } } public final class WeatherContract { public WeatherContract() {} public static abstract class City implements BaseColumns { public static final String TABLE_NAME = "city"; public static final String COLUMN_NAME_CITY_ID = "cityid"; public static final String COLUMN_NAME_NAME = "name"; public static final String COLUMN_NAME_LAST_UPDATE = "lastupdate"; public static final String COLUMN_NAME_LATITUDE = "latitude"; public static final String COLUMN_NAME_LONGITUDE = "longitude"; ... } }
  10. 105 Criar o banco com SQL Helper private static final

    String SQL_CREATE_CITY = "CREATE TABLE " + City.TABLE_NAME + " (" + City._ID + " INTEGER PRIMARY KEY," + City.COLUMN_NAME_CITY_ID + " INTEGER," + City.COLUMN_NAME_NAME + " TEXT," + City.COLUMN_NAME_LAST_NAME + " TEXT" + ")"; private static final String SQL_DELETE_CITY = "DROP TABLE IF EXISTS " + City.TABLE_NAME; public class WeatherDbHelper extends SQLiteOpenHelper { public static final int DATABASE_VERSION = 1; public static final String DATABASE_NAME = "Weather.db"; public WeatherDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } public void onCreate(SQLiteDatabase db) { db.execSQL(SQL_CREATE_CITY); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(SQL_DELETE_CITY); onCreate(db); } public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { onUpgrade(db, oldVersion, newVersion); } } private static final String SQL_CREATE_CITY = "CREATE TABLE " + City.TABLE_NAME + " (" + City._ID + " INTEGER PRIMARY KEY," + City.COLUMN_NAME_CITY_ID + " INTEGER," + City.COLUMN_NAME_NAME + " TEXT," + City.COLUMN_NAME_LAST_NAME + " TEXT" + ")"; private static final String SQL_DELETE_CITY = "DROP TABLE IF EXISTS " + City.TABLE_NAME; public class WeatherDbHelper extends SQLiteOpenHelper { public static final int DATABASE_VERSION = 1; public static final String DATABASE_NAME = "Weather.db"; public WeatherDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } public void onCreate(SQLiteDatabase db) { db.execSQL(SQL_CREATE_CITY); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(SQL_DELETE_CITY); onCreate(db); } public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { onUpgrade(db, oldVersion, newVersion); } }
  11. 106 Gravar dados no banco WeatherDbHelper mDbHelper = new WeatherDbHelper(getContext());

    SQLiteDatabase db = mDbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(City.COLUMN_NAME_CITY_ID, id); values.put(City.COLUMN_NAME_NAME, name); values.put(City.COLUMN_NAME_LAST_UPDATE, lastUpdate); long newRowId = db.insert(City.TABLE_NAME, null, values); WeatherDbHelper mDbHelper = new WeatherDbHelper(getContext()); SQLiteDatabase db = mDbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(City.COLUMN_NAME_CITY_ID, id); values.put(City.COLUMN_NAME_NAME, name); values.put(City.COLUMN_NAME_LAST_UPDATE, lastUpdate); long newRowId = db.insert(City.TABLE_NAME, null, values);
  12. 107 Ler dados do banco WeatherDbHelper mDbHelper = new WeatherDbHelper(getContext());

    SQLiteDatabase db = mDbHelper.getReadableDatabase(); String[] projection = { City._ID, City.COLUMN_NAME_NAME, ... }; String sortOrder = City.COLUMN_NAME_LAST_UPDATË + " DESC"; Cursor c = db.query( City.TABLE_NAME, // Nome da tabela projection, // Colunas a retornar selection, // Vetor de colunas para (where) selectionArgs, // Vetor de valores para (where) null, // Não agrupar (group by) null, // Não filtrar por grupo (having) sortOrder // Ordem (order by) ); cursor.moveToFirst(); long itemId = cursor.getLong(cursor.getColumnIndexOrThrow(City._ID)); WeatherDbHelper mDbHelper = new WeatherDbHelper(getContext()); SQLiteDatabase db = mDbHelper.getReadableDatabase(); String[] projection = { City._ID, City.COLUMN_NAME_NAME, ... }; String sortOrder = City.COLUMN_NAME_LAST_UPDATË + " DESC"; Cursor c = db.query( City.TABLE_NAME, // Nome da tabela projection, // Colunas a retornar selection, // Vetor de colunas para (where) selectionArgs, // Vetor de valores para (where) null, // Não agrupar (group by) null, // Não filtrar por grupo (having) sortOrder // Ordem (order by) ); cursor.moveToFirst(); long itemId = cursor.getLong(cursor.getColumnIndexOrThrow(City._ID));