Skip to content

Instantly share code, notes, and snippets.

@OrenBochman
Last active September 13, 2018 03:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OrenBochman/64f867768f5db2d23b0fc9ca010e19ed to your computer and use it in GitHub Desktop.
Save OrenBochman/64f867768f5db2d23b0fc9ca010e19ed to your computer and use it in GitHub Desktop.
android libraries and tools

Libraries Android - A quick reference guide

I generally try to avoid libraries and code I did not write/test but here is a quick refrence for:

Library Library Library
Android Annotations Buterknife Dagger2
EventBus FirbaseJobDispatcher Glide
Icepick JodaTime LeakCanary
ObjectBox OkHttpClient Moshi
Parceler Picasso Retrofit
Room RXAndroid ThreeTenABP
Timber
@EActivity(R.layout.activty)
public class MyActivity extends Activity {
@ViewById
EditText textInput;
@AnimationRes
Animation fadeIn;
@Click
void doTranslate(...) { ... }
@Background
void runOnBackground(...) { ... }
@UiThread
void runOnUI(...) { ... }
}
@BindView(R.id.view) TextView view;
@BindString(R.string.title) String title;
@OnClick(R.id.submit)
public void submit() {
// Handle click
}
@Override
public void onCreate(...) {
...
ButterKnife.bind(this);
}
class CoffeeMaker {
@Inject Heater heater;
}
@Module
class DripCoffeeModule {
@Provides Heater
provideHeater() {
return new ElectricHeater(); }
}
ObjectGraph.create(
new DripCoffeeModule());
public class Event {
public final String message;
... }
EventBus.getDefault()
.register(this);
@Subscribe
public void onEvent(Event event) {
// Handle event
}
EventBus.getDefault()
.post(new Event(...));
Job myJob = dispatcher
.newJobBuilder()
.setService(MyJobService.class)
.setTag("my-unique-tag")
.setRecurring(false)
.setLifetime(UNTIL_NEXT_BOOT)
.setReplaceCurrent(false)
.setConstraints(
ON_UNMETERED_NETWORK,
DEVICE_CHARGING
)
.setExtras(extrasBundle) .build();
dispatcher.mustSchedule(myJob);
GlideApp.with(cx)
.load(url)
.into(imageView);
GlideApp.with(cx)
.load(url)
.centerCrop()
.placeholder(R.drawable.ph)
.into(imageView);
// This will be automatically saved and restored
@State String username;
@Override public void onCreate(Bundle state) {
//...
Icepick.restoreInstanceState(this, state);
}
@Override public void onSaveInstanceState(Bundle outState) {
//...
Icepick.saveInstanceState(this, outState);
}
DateTime datetime = ... ; datetime.getMonthOfYear(); datetime.getDayOfMonth();
LocalDate fromDate = ... ; LocalDate newYear =
fromDate.plusYears(1) .withDayOfYear(1);
Days.daysBetween(fromDate, newYear);
dateOfBirth.monthOfYear()
.getAsText(Locale.ENGLISH);
/** LeakCanary - A memory leak detection library for Android and Java - @link https://github.com/square/leakcanary .
* dependencies:
* debugImplementation . 'com.squareup.leakcanary:leakcanary-android:1.6.1'
* releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.6.1'
* debugImplementation 'com.squareup.leakcanary:leakcanary-support-fragment:1.6.1' . //Optional, if you use support library fragments:
*/
public class ExampleApplication extends Application {
@Override public void onCreate() {
super.onCreate();
if (LeakCanary.isInAnalyzerProcess(this)) {
// This process is dedicated to LeakCanary for heap analysis.
// You should not init your app in this process.
return;
}
LeakCanary.install(this);
// Normal app init code...
}
}
Moshi moshi = new Moshi.Builder().build();
JsonAdapter<MyObj> adapter = moshi.adapter(MyObj.class);
adapter.toJson(item); adapter.fromJson(jsonStr);
@Entity public class Person {
@Id long id;
String firstName;
...
}
// MyObjectBox is generated by ObjectBox
BoxStore boxStore = MyObjectBox.builder()
.androidContext(YourApp.this).build();
Box<Person> box = boxStore.boxFor(Person.class);
// CRUD
Person person = new Person("Joe", "Green");
long id = box.put(person); // Create
Person person = box.get(id); // Read
person.setLastName("Black");
box.put(person); // Update
box.remove(person); // Delete
// Query
Query query = box.query()
.equal(Person_.firstName, "Joe")
.startsWith(Person_.lastName, "B").build();
List persons = query.find();
// Relations
Playlist playlist = new Playlist("Black Album");
playlist.songs.add(new Song("Enter Sandman");
playlist.songs.add(new Song("Sad but True");
box.put(playlist);
OkHttpClient client = new OkHttpClient();
Request request =
new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request)
.execute();
return response.body().string();
Parcel
public class Example {
String name;
int age;
/* Constructors, getters, etc. */
}
Bundle bundle = new Bundle();
bundle.putParcelable(
"key",
Parcels.wrap(example));
Example example = Parcels.unwrap( this.getIntent()
.getParcelableExtra("key"));
Picasso.with(context)
.load(url)
.resize(50, 50)
.centerCrop()
.into(imageView);
Picasso.with(context)
.load(url)
.placeholder(R.drawable.ph) .error(R.drawable.error) .into(imageView);
class Dog extends RealmObject {
private String name;
}
Realm realm =
Realm.getDefaultInstance(); Dog dog = new Dog();
dog.setName("Rex");
realm.beginTransaction(); realm.copyToRealm(dog); realm.commitTransaction();
Dog dog = realm.where(Dog.class) .equalTo("name", "Rex") .findFirst();
public interface GitHub {
@GET("users/{user}/repos")
Call<List<Repo>> repos(
@Path("user") String user);
}
Retrofit retrofit =new Retrofit.Builder()
.baseUrl("https://api.github.com") .build();
GitHub service = retrofit.create(GitHub.class);
Call<List<Repo>> repos = service.repos("octocat");
public class User {
@PrimaryKey
private int uid; @ColumnInfo(name = "first_name") private String firstName;
}
@Dao
public interface UserDao {
@Insert
Void insertAll(User... users);
@Query("SELECT * FROM user
WHERE uid IN (:userIds)")
List<User> loadAllByIds(
int[] userIds);
}
Observable.just(items)
.subscribeOn(
Schedulers.newThread())
.observeOn(
AndroidSchedulers
.mainThread())
.subscribe(/* an Observer */);
LocalDateTime ldt =
LocalDateTime.now();
int ld = ldt.getDayOfMonth();
int lm = ldt.getMonthValue();
int ly = ldt.getYear();
ldt.withYear(2000);
ldt.plusHours(2);
ldt = LocalDateTime
.of(2005, 3, 26, 12, 0, 0, 0);
ldt.plusDays(1); ldt.plus(24,ChronoUnit.HOURS);
@Override
public void onCreate() {
super.onCreate();
if (BuildConfig.DEBUG)
Timber.plant(
new DebugTree());
else
Timber.plant(
new NotLoggingTree());
}
Timber.v("some verbose logs here");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment