Skip to content

Instantly share code, notes, and snippets.

@jmsalcido
Last active October 9, 2016 17:26
Show Gist options
  • Save jmsalcido/e599d6186597d84a3a5ad05d504b3971 to your computer and use it in GitHub Desktop.
Save jmsalcido/e599d6186597d84a3a5ad05d504b3971 to your computer and use it in GitHub Desktop.
Android Architecture in UI 1 - very ugly code in Android.
// ----------------------------------------------------------
// VIEW & CONTROLLER
// ----------------------------------------------------------
// This class represents View layer and also Controller layer
// ----------------------------------------------------------
public interface ActivityListener {
void showMessage(boolean buttonState, String message);
}
public class MainActivity extends AppCompatActivity implements ActivityListener {
private Button loadButton;
private TextView console;
private CloudApi cloudApi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// start model
cloudApi = new CloudApi();
// show views
setContentView(R.layout.some_layout_activity);
loadButton = (Button) findViewById(R.id.load_button);
console = (TextView) findViewById(R.id.console_view);
showMessage(true, "Click on the Button");
// acting as a Controller too
loadButton.setOnClickListener(() -> {
runOnBackgroundThread(() -> cloudApi.downloadSomething(MainActivity.this));
});
}
@Override
public void showMessage(boolean buttonState, String message) {
runOnUiThread(() -> {
loadButton.setEnabled(buttonState);
console.setText(message);
});
}
}
// ----------------------------------------------------------
// MODEL
// ----------------------------------------------------------
// Classes that represents the Model layer
// ----------------------------------------------------------
public class CloudApi {
public void downloadSomething(ActivityListener listener) {
listener.showMessage(false, "DOWNLOADING");
try {
Thread.sleep(5 * 1000); // simulate downloading something
} catch (InterruptedException e) {
listener.showMessage(true, e.getMessage());
}
listener.showMessage(true, "DOWNLOADED, CLICK AGAIN!"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment