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

Android libraries I wish I knew when I started

Android libraries I wish I knew when I started

There’s no sense in re-inventing the wheel when you’re working on Android apps, especially if you’re just starting out. This talk will cover a range of libraries you can include in your Android apps that will help you tackle the problems other people have already solved. Whether you’re loading data from a web api, showing & caching images, or storing & syncing data there’s a library you can pull in to help you out!

Chris Guzman

July 28, 2016
Tweet

More Decks by Chris Guzman

Other Decks in Programming

Transcript

  1. A lot of apps do similar things → Manage multiple

    views → Load and display images → Fetch data from an API → Parse JSON → Start new activities with extras → Persist data to storage
  2. These libraries prevent you reinventing the wheel with every project.

    → Butter Knife v8.5.1 → Picasso v2.5.2 → Gson v2.8.0 → Retrofit v2.3.0 → Realm v3.3.1 → Dart & Henson v2.0.2
  3. <LinearLayout ... android:orientation="vertical"> <ImageView android:id="@+id/taco_img" .../> <TextView android:id="@+id/description" .../> <LinearLayout

    android:orientation="horizontal" .../> <Button android:id="@+id/reject" .../> <Button android:id="@+id/save" .../> </LinearLayout> </LinearLayout>
  4. → How many times have you wrote findViewById? → No

    additional cost at run-time - does not slow down your app at all! → Improved View lookups → Improved Listener attachments → Improved Resource lookups
  5. Bind views in an activity <TextView android:id="@+id/name" ... /> public

    class MainActivity extends Activity { @BindView(R.id.name) TextView name; @Override protected void onCreate(Bundle bundle) { ... ButterKnife.bind(this); name.setText("Tofu with Cheese on a tortilla"); } }
  6. ButterKnife.bind(this) Generates code that looks up views/resources and saves them

    as a property on the Activity. public void bind(MainActivity activity) { activity.description = (android.widget.TextView) activity.findViewById(2130968577); }
  7. Bind and unbind views in a fragment public class TacoFragment

    extends Fragment { @BindView(R.id.tags) EditText tags; @Override public View onCreateView(args...) { ... ButterKnife.bind(this, parentView); //Important! unbinder = ButterKnife.bind(this, parentView); tags.setHint("Add tags. Eg: Tasty!, Want to try") return view; } }
  8. Event listeners @OnClick(R.id.save) public void saveTaco(Button button) { button.setText("Saved!"); }

    Arguments to the listener method are optional @OnClick(R.id.reject) public void reject() { Log.d("RejectBtn", "onClick") }
  9. Butter Knife also supports: - OnLongClick - OnEditorAction - OnFocusChange

    - OnItemClick - OnItemLongClick - OnItemSelected - OnPageChange - OnTextChanged - OnTouch - OnCheckedChanged
  10. Inject resources once, no need to save them as member

    variables! class MainActivity extends Activity { @BindString(R.string.title) String title; @BindDrawable(R.drawable.star) Drawable star; // int or ColorStateList @BindColor(R.color.guac_green) int guacGreen; // int (in pixels) or float (for exact value) @BindDimen(R.dimen.spacer) Float spacer; }
  11. Group views together: @OnClick({ R.id.save, R.id.reject}) public void saveOrReject(View view)

    { if (view.getId() == R.reject) { Toast.makeText(this, "Ew Gross!", LENGTH_SHORT).show(); } else { Toast.makeText(this, "Yummy :)", LENGTH_SHORT).show(); } //TODO: implement ButterKnife.apply(actionButtons, DISABLE); getNewTaco(); }
  12. Act on list of views at once with ButterKnife.apply. @BindViews({R.id.save,

    R.id.reject}) List<Button> actionButtons; ButterKnife.apply(actionButtons, View.ALPHA, 0.0f);
  13. Action and Setter interfaces allow specifying simple behavior. ButterKnife.apply(actionButtons, DISABLE);

    ButterKnife.apply(actionButtons, ENABLED, false); static final ButterKnife.Action<View> DISABLE = new ButterKnife.Action<View>() { @Override public void apply(View view, int index) { view.setEnabled(false); } }; static final ButterKnife.Setter<View, Boolean> ENABLED = new ButterKnife.Setter<View, Boolean>() { @Override public void set(View view, Boolean value, int index) { view.setEnabled(value); } };
  14. → makes HTTP Requests → caches the images → easy

    resizing/cropping/centering/scaling → takes care of downloading off the main thread → properly recycles views in RecyclerView
  15. private Bitmap DownloadImage(String url) { Bitmap bitmap = null; InputStream

    in = null; try { in = OpenHttpGETConnection(url); bitmap = BitmapFactory.decodeStream(in); in.close(); } catch (Exception e) { Log.d("DownloadImage", e.getLocalizedMessage()); } return bitmap; }
  16. But wait there's more! .placeholder(R.mipmap.loading) //can be a resource or

    a drawable .error(R.drawable.sad_taco) //fallback image if error .fit() //reduce the image size to the dimensions of imageView .resize(imgWidth, imgHeight) //resizes the image in pixels .centerCrop() //or .centerInside() .rotate(90f) //or rotate(degrees, pivotX, pivotY) .noFade() //don't fade all fancy-like
  17. //Butter Knife! @BindView(R.id.taco_img) ImageView tacoImg; private void setTacoImage() { Picasso.with(context)

    .load("http://tacoimages.com/random.jpg") .into(tacoImg); } private void getNewTaco() { setTacoImage(); //TODO: implement loadTacoDescription(); }
  18. Step 4 Set up models Get ready for models by

    setting up what JSON will look like
  19. Example time! class Taco { private String name; private String

    url; //not included in JSON serialization or deserialization private transient String imageUrl; Taco(args...) { ... } }
  20. // Serialize to JSON Taco breakfastTaco = new Taco( "Eggs

    with syrup on pancake", "tacofancy.com/breakfast", "imgur.com/123"); Gson gson = new Gson(); String json = gson.toJson(breakfastTaco); json = { "name":"Eggs with syrup on pancake", "url": "tacofancy.com/breakfast" } // Deserialize to POJO Taco yummyTaco = gson.fromJson(json, Taco.class); // ==> yummyTaco is just like breakfastTaco without imagUrl
  21. Benefits → All fields in the current class (and from

    all super classes) are included by default → Supports multi-dimensional arrays
  22. Gotchas → While serializing, a null field is skipped from

    the output → While deserializing, a missing entry in JSON results in setting the corresponding field in the object to null
  23. Cool customization //Set properties to null instead of ignoring them

    Gson gson = new GsonBuilder().serializeNulls().create(); //Keep whitespace Gson gson = new GsonBuilder().setPrettyPrinting().create();
  24. Need to rename a variable from an API? public class

    Taco { @SerializedName("serialized_labels") private String tags; }
  25. Or use a custom date format? public String DATE_FORMAT =

    "yyyy-MM-dd"; GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setDateFormat(DATE_FORMAT); Gson gson = gsonBuilder.create();
  26. The better way → Typesafe → Built in support for:

    → Authentication → parse JSON to POJOs → Supports RxJava → Can be executed synchronously or asynchronously
  27. API Endpoints public interface TacoApi { // Request method and

    URL specified in the annotation // Callback for the parsed response is the last parameter @GET("random") Call<Taco> randomTaco(@Query("full-taco") boolean full); @GET("contributions/{name}") Call<Contributor> getContributors(@Path("name") String username); @POST("recipe/new") Call<Recipe> createRecipe(@Body Recipe recipe); @GET("contributions") Call<List<Contributor>> getContributors(); }
  28. Getting JSON synchronously Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://taco-randomizer.herokuapp.com/") .addConverterFactory(GsonConverterFactory.create())

    .build(); // Create an instance of our TacoApi interface. TacoApi tacoApi = retrofit.create(TacoApi.class); // Create a call instance for a random taco Call<Taco> call = tacoApi.randomTaco(false); // Fetch a random taco // Do this off the main thread Taco taco = call.execute().body();
  29. POSTing JSON Async Recipe recipe = new Recipe(); Call<Recipe> call

    = tacoApi.createRecipe(recipe); call.enqueue(new Callback<Recipe>() { @Override public void onResponse(Call<Recipe> call, Response<Recipe> response) { } @Override public void onFailure(Call<Recipe> call, Throwable t) { }
  30. Annotations → @Path: variable substitution for the API endpoint. →

    @Query: Add a query parameter. → @Body: Payload for the POST call (serialized from a Java object to a JSON string) → @Headers: Add a header to the HTTP call → @Url: Pass in a dynamic url
  31. Cool tricks //Change the base url @POST("http://taco-randomizer.herokuapp.com/v2/taco") private Call<Taco> getFromNewAPI();

    //Add headers @Headers({"User-Agent: tacobot"}) @GET("contributions") private Call<List<Contributor>> getContributors();
  32. private void getNextTaco() { ... loadTacoDescription(); } private void loadTacoDescription()

    { Call<Taco> call = tacoApi.randomTaco(true); call.enqueue(new Callback<Taco>() { @Override public void onResponse(Call<Taco> call, Response<Taco> response) { //Set description from response Taco taco = response.body; //TODO: implement saveTaco(taco); } @Override public void onFailure(Call<Taco> call, Throwable t) { //Show error } }
  33. → Works by extending your models → Made for mobile

    → Most queries in Realm are fast enough to be run synchronously → Can have multiple realm database in an app
  34. public class Taco extends RealmObject { private String name; private

    String imageUrl; private String url; //getters and setters }
  35. Set-up Realm Realm.init(this); // Get a Realm instance for this

    thread Realm realm = Realm.getDefaultInstance();
  36. Persist to db // Persist your data in a transaction

    realm.beginTransaction(); // Persist unmanaged objects final Taco managedTaco = realm.copyToRealm(unmanagedTaco); // Create managed objects directly Taco taco = realm.createObject(Taco.class); realm.commitTransaction();
  37. Accessing Data //find all favorite tacos final RealmResults<Taco> likedTacos =

    realm.where(Taco.class).equalTo("favorite", true).findAll();
  38. Typical SQL relationships → One to One → One to

    Many → Many to One → Many to Many
  39. Conditions → between() → greaterThan(), lessThan() → greaterThanOrEqualTo() & lessThanOrEqualTo()

    → equalTo() & notEqualTo() → contains() → beginsWith() & endsWith()
  40. //Transaction block realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm)

    { Taco taco = realm.createObject(Taco.class); taco.setName("Spaghetti Squash on Fresh Corn Tortillas"); taco.setUrl("http://tacofancy.com/squash"); } });
  41. //Async realm.executeTransactionAsync(new Realm.Transaction() { public void execute(Realm bgRealm) { Taco

    taco = bgRealm.createObject(Taco.class); taco.name("Spaghetti Squash on Fresh Corn Tortillas"); taco.setUrl("http://tacofancy.com/squash"); } }, new Realm.Transaction.OnSuccess() { public void onSuccess() { // Transaction was a success. } }, new Realm.Transaction.OnError() { public void onError(Throwable error) { // Transaction failed and was automatically canceled. } });
  42. public class Taco extends RealmObject { ... private List<Ingredient> ...

    } public class Ingredient extends RealmObject { private String name; private URL url; }
  43. Delete results // All changes to data must happen in

    a transaction realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { // remove single match limeTacos.deleteFirstFromRealm(); //or limeTacos.deleteLastFromRealm(); // remove a single object Taco fishTaco = limeTacos.get(1); fishTaco.deleteFromRealm(); // Delete all matches limeTacos.deleteAllFromRealm(); } });
  44. Data change listeners Can be attached to RealmObject or RealmResults

    limeTacos.addChangeListener( new RealmChangeListener<RealmResults<Taco>>() { @Override public void onChange(RealmResults<Taco> tacosConLimon) { //tacosConLimon.size() == limeTacos.size() // Query results are updated in real time Log.d("LimeTacos", "Now we have" + limeTacos.size() + " tacos"); } } );
  45. Prevent memory leaks @Override protected void onDestroy() { // Remove

    the listener. realm.removeChangeListener(realmListener); //or realm.removeAllChangeListeners(); // Close the Realm instance. realm.close(); ... }
  46. Gotchas → No support for list of String or primitives

    → In the meantime add this Gson adapter → Need to save data to realm after getting response from Retrofit → Large datasets or complex queries should be run on background thread
  47. Benefits → readable DSL for passing extras to intent →

    stop wasting time and write less of this: intent.putExtra("TACO_NAME", "Salsa Verde"); tacoName = getIntent().getExtras().getString("TACO_NAME");
  48. public class TacoDetailActivity extends Activity { @InjectExtra String name; @Nullable

    @InjectExtra String imageUrl; //default value if left null @Nullable @InjectExtra String tag = "taco"; //Ingredient implements Parcelable @Nullable @InjectExtra Ingredient ingredient; @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); Dart.inject(this); //TODO use member variables ... } }
  49. Generate intent builders //Start intent for TacoDetailActivity Intent intent =

    Henson.with(this) .gotoTacoDetailActivity() .name(taco.getName()) .url(taco.getUrl()) .imageUrl(taco.getImageUrl()) .build(); // tag is null startActivity(intent);
  50. Want to use Henson for an activity without injectable extras?

    Annotate the activity with @HensonNavigable
  51. → Butter Knife - Manage multiple views → Picasso -

    Load and display images → Gson - Parse JSON → Retrofit - Fetch data from an API → Realm - Persist data to storage → Dart & Henson - Start new activities with extras