Mehdi TmimiMobile DevelopmentMobile

Mobile Development Lab 1 Part 10 · parts 0–10

Create, edit, delete: the whole API

Add a note, turn the phone: it is gone. The server never heard of it. Now the app tells the server.

Part 9 not finished, or a fresh project? Start here about 5 min
  1. The project: your own, wherever it stopped, or a fresh one: Part 0, steps 0.3 and 0.4 (about 5 minutes).

  2. Your package name, for the code of this page:

    Without JavaScript, the code says com.yourname.notes: replace yourname by the name you chose.

  3. Gradle: in build.gradle.kts (Module :app), check this line; implementation(libs.constraintlayout) works too. Missing? Click Copy 1 line, then in the editor click at the end of line 37, implementation(libs.material). Press Enter, then Ctrl+V, and click Sync Now.

    Gradle Scripts › build.gradle.kts (Module :app)Add the marked lines
    plugins {    alias(libs.plugins.android.application)}
    android { namespace = "com.yourname.notes" compileSdk { version = release(37) }
    defaultConfig { applicationId = "com.yourname.notes" minSdk = 24 targetSdk = 37 versionCode = 1 versionName = "1.0"
    testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" }
    buildTypes { release { optimization { enable = true packageScope = setOf("androidx.**", "kotlin.**", "kotlinx.**") } } } compileOptions { sourceCompatibility = JavaVersion.VERSION_11 targetCompatibility = JavaVersion.VERSION_11 }}
    dependencies { implementation(libs.appcompat) implementation(libs.material) implementation("androidx.constraintlayout:constraintlayout:2.2.2") testImplementation(libs.junit) androidTestImplementation(libs.espresso.core) androidTestImplementation(libs.ext.junit)}
  4. res and manifest: download the pack and open it in Explorer. Drag its app folder onto your project folder (C:\Users\<you>\AndroidStudioProjects\Notes), then choose Replace the files in the destination. Not Extract All: it makes a folder inside and replaces nothing. Then, in res › values › themes, delete themes.xml (night) if it is still there.

    res and manifest: a pack of files replaces them. On a Mac, one line fetches it. Never drag such a folder in Finder: its Replace swaps the whole app folder and deletes your code. In Android Studio, open ViewTool WindowsTerminal: its line must end with Notes %, your project. Copy the line below, paste it there (⌘ Cmd+V) and press Enter: it downloads the pack and replaces the files, and prints nothing.

    curl -fsSL https://mehditmimi.com/courses/mobile/labs/java/files/lab1-part10-res.zip | tar -x

    Then, in res › values › themes, delete themes.xml (night) if it is still there.

    lab1-part10-res.zip zip · 9.5 KB
  5. Java: open MainActivity.java, select all, then paste the first file. Do the same in NoteActivity.java and Note.java with the next two. Missing? First right-click kotlin+java › com.yourname.notes, the one without (test), then NewJava Class: type its name, then press Enter.

    kotlin+java › com.yourname.notes › MainActivity.javaReplace the whole file
    package com.yourname.notes;
    import android.content.Intent;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast;
    import androidx.appcompat.app.AppCompatActivity;
    import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;
    import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import java.util.ArrayList;import java.util.List;
    public class MainActivity extends AppCompatActivity {
    private static final String TAG = "Lifecycle"; private static final String NOTES_URL = "https://bachelor-gl.site/notes"; private static final int[] NOTE_BACKGROUNDS = { R.drawable.bg_note_butter, R.drawable.bg_note_mint, R.drawable.bg_note_lavender, R.drawable.bg_note_peach };
    private TextView textCount; private TextView textEmpty; private LinearLayout notesContainer; private int notesAdded = 0;
    private EditText editTitle; private EditText editBody; private TextView textError; private TextView textCounter;
    private final TextWatcher formWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
    @Override public void onTextChanged(CharSequence s, int start, int before, int count) { }
    @Override public void afterTextChanged(Editable s) { updateForm(); } };
    @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d(TAG, "Main onCreate");
    textCount = findViewById(R.id.textCount); textEmpty = findViewById(R.id.textEmpty); notesContainer = findViewById(R.id.notesContainer);
    textEmpty.setOnClickListener(v -> loadNotes()); loadNotes();
    editTitle = findViewById(R.id.editTitle); editBody = findViewById(R.id.editBody); textError = findViewById(R.id.textError); textCounter = findViewById(R.id.textCounter);
    Button buttonAdd = findViewById(R.id.buttonAdd); buttonAdd.setOnClickListener(v -> addNoteFromComposer());
    editTitle.addTextChangedListener(formWatcher); editBody.addTextChangedListener(formWatcher); }
    private void loadNotes() { textEmpty.setText(R.string.loading); updateCount(); new Thread(() -> { try { String json = download(NOTES_URL); List<Note> notes = parse(json); runOnUiThread(() -> showNotes(notes)); } catch (IOException | JSONException e) { Log.e(TAG, "loadNotes failed", e); runOnUiThread(() -> textEmpty.setText(R.string.error_network)); } }).start(); }
    private String download(String address) throws IOException { URL url = new URL(address); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(10000); connection.setReadTimeout(10000); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder text = new StringBuilder(); String line = reader.readLine(); while (line != null) { text.append(line); line = reader.readLine(); } reader.close(); return text.toString(); }
    private List<Note> parse(String json) throws JSONException { List<Note> notes = new ArrayList<>(); JSONArray array = new JSONArray(json); for (int i = 0; i < array.length(); i++) { JSONObject object = array.getJSONObject(i); Note note = new Note(); note.id = object.getInt("id"); note.title = object.getString("title"); note.description = object.getString("description"); notes.add(note); } return notes; }
    private void showNotes(List<Note> notes) { notesContainer.removeAllViews(); notesAdded = 0; for (Note note : notes) { addNote(note.title, note.description); } textEmpty.setText(R.string.empty); updateCount(); }
    private void updateCount() { int count = notesContainer.getChildCount(); textCount.setText(String.valueOf(count)); textEmpty.setVisibility(count == 0 ? View.VISIBLE : View.GONE); }
    private void addNote(String title, String body) { View card = LayoutInflater.from(this).inflate(R.layout.item_note, notesContainer, false); TextView cardTitle = card.findViewById(R.id.textNoteTitle); TextView cardBody = card.findViewById(R.id.textNoteBody); cardTitle.setText(title); cardBody.setText(body); cardBody.setVisibility(body.isEmpty() ? View.GONE : View.VISIBLE); int background = NOTE_BACKGROUNDS[notesAdded % NOTE_BACKGROUNDS.length]; card.setBackgroundResource(background); notesAdded++;
    card.setOnClickListener(v -> openNote(title, body, background)); card.setOnLongClickListener(v -> { notesContainer.removeView(card); updateCount(); Toast.makeText(this, R.string.note_deleted, Toast.LENGTH_SHORT).show(); return true; });
    notesContainer.addView(card, 0); }
    private void addNoteFromComposer() { String title = editTitle.getText().toString().trim(); String body = editBody.getText().toString().trim(); if (title.isEmpty()) { textError.setVisibility(View.VISIBLE); return; } textError.setVisibility(View.GONE); addNote(title, body); updateCount(); editTitle.setText(""); editBody.setText(""); Toast.makeText(this, R.string.note_added, Toast.LENGTH_SHORT).show(); }
    private void updateForm() { int length = editBody.length(); textCounter.setText(getString(R.string.counter, length)); int colour = length >= 120 ? R.color.error : R.color.muted; textCounter.setTextColor(getColor(colour)); if (editTitle.length() > 0) { textError.setVisibility(View.GONE); } }
    public void onClearClicked(View view) { editTitle.setText(""); editBody.setText(""); }
    private void openNote(String title, String body, int background) { Intent intent = new Intent(this, NoteActivity.class); intent.putExtra(NoteActivity.EXTRA_TITLE, title); intent.putExtra(NoteActivity.EXTRA_BODY, body); intent.putExtra(NoteActivity.EXTRA_BACKGROUND, background); startActivity(intent); }
    @Override protected void onStart() { super.onStart(); Log.d(TAG, "Main onStart"); }
    @Override protected void onResume() { super.onResume(); Log.d(TAG, "Main onResume"); }
    @Override protected void onPause() { super.onPause(); Log.d(TAG, "Main onPause"); }
    @Override protected void onStop() { super.onStop(); Log.d(TAG, "Main onStop"); }
    @Override protected void onRestart() { super.onRestart(); Log.d(TAG, "Main onRestart"); }
    @Override protected void onDestroy() { super.onDestroy(); Log.d(TAG, "Main onDestroy"); }}
    kotlin+java › com.yourname.notes › NoteActivity.javaReplace the whole file
    package com.yourname.notes;
    import android.content.Intent;import android.os.Bundle;import android.util.Log;import android.widget.TextView;
    import androidx.appcompat.app.AppCompatActivity;
    public class NoteActivity extends AppCompatActivity {
    public static final String EXTRA_TITLE = "com.yourname.notes.EXTRA_TITLE"; public static final String EXTRA_BODY = "com.yourname.notes.EXTRA_BODY"; public static final String EXTRA_BACKGROUND = "com.yourname.notes.EXTRA_BACKGROUND"; private static final String TAG = "Lifecycle";
    @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_note); Log.d(TAG, "Note onCreate");
    String title = getIntent().getStringExtra(EXTRA_TITLE); String body = getIntent().getStringExtra(EXTRA_BODY); int background = getIntent().getIntExtra(EXTRA_BACKGROUND, R.drawable.bg_note_butter);
    TextView textTitle = findViewById(R.id.textTitle); TextView textBody = findViewById(R.id.textBody); textTitle.setText(title); textBody.setText(body); findViewById(R.id.noteSheet).setBackgroundResource(background);
    findViewById(R.id.buttonBack).setOnClickListener(v -> finish()); findViewById(R.id.buttonShare).setOnClickListener(v -> share(title, body)); }
    private void share(String title, String body) { Intent send = new Intent(Intent.ACTION_SEND); send.setType("text/plain"); send.putExtra(Intent.EXTRA_TEXT, title + "\n" + body); startActivity(Intent.createChooser(send, null)); }
    @Override protected void onDestroy() { super.onDestroy(); Log.d(TAG, "Note onDestroy"); }}
    kotlin+java › com.yourname.notes › Note.javaReplace the whole file
    package com.yourname.notes;
    public class Note { public int id; public String title; public String description;}
  6. ▶. You are ready when the phone shows the server’s notes.

The emulator at the end of Part 9: the notes screen with three notes read from the server, Exam: the lifecycle, Ideas for the app and Saturday, and the pill 3.
Where you start

Before you start

By the end you can

  • read an API in a Retrofit interface: which request each method sends;
  • send GET, POST, PUT and DELETE, and tell a yes, a refusal and no answer apart;
  • say what Retrofit and Gson do for you.
  • Gradle
  • Java
  • Layout
  • Resources
  • Emulator

Step 1 of 6

Add Retrofit and Gson

6 min

Goal Add two libraries, Retrofit and Gson: they do Part 9’s three chores for you.

  • Gradle build.gradle.kts (Module :app)
Part 9’s three chores, and the library that does each one now
In Part 9, you wroteNow it is the job of
the thread, and the way back to the main threadRetrofit
the HTTP requestRetrofit
the JSON text turned into objectsGson
  1. Paste The two libraries, in the app’s dependencies.

    1. Under Gradle Scripts, open build.gradle.kts (Module :app).
    2. In the panel below, beside After line 38, click Copy 2 lines.
    3. In the editor, click at the end of line 38, the constraintlayout line. Press Enter, then Ctrl+V.
    4. The yellow underline of step 1.3 comes back: a suggestion, not an error. Leave it.
    Gradle Scripts › build.gradle.kts (Module :app)Add the marked lines
    plugins {    alias(libs.plugins.android.application)}
    android { namespace = "com.yourname.notes" compileSdk { version = release(37) }
    defaultConfig { applicationId = "com.yourname.notes" minSdk = 24 targetSdk = 37 versionCode = 1 versionName = "1.0"
    testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" }
    buildTypes { release { optimization { enable = true packageScope = setOf("androidx.**", "kotlin.**", "kotlinx.**") } } } compileOptions { sourceCompatibility = JavaVersion.VERSION_11 targetCompatibility = JavaVersion.VERSION_11 }}
    dependencies { implementation(libs.appcompat) implementation(libs.material) implementation("androidx.constraintlayout:constraintlayout:2.2.2") implementation("com.squareup.retrofit2:retrofit:3.0.0") implementation("com.squareup.retrofit2:converter-gson:3.0.0") testImplementation(libs.junit) androidTestImplementation(libs.espresso.core) androidTestImplementation(libs.ext.junit)}
  2. The Gradle sync.

    1. In the banner at the top, click Sync Now, as in step 1.3: Gradle fetches the two libraries.
    build.gradle.kts (:app) Editor · centreFull size
    The editor on build.gradle.kts (:app): lines 39 and 40 are the two Retrofit lines, their text underlined in yellow like line 38, and above them the banner Gradle files have changed since last project sync, with Sync Now.
    1. Sync Now: Gradle fetches the two libraries, in a few seconds.
    2. Lines 39 and 40, underlined in yellow like line 38: a suggestion, not an error.

Done I see no banner at the top any more, and no red code.

Stuck? 1 symptom · the file
  • The sync ends in red, and the two lines stay red Gradle did not reach the Internet. Check the PC’s connection, then click Sync Now again.

The file at the end of this step, to compare. Do not paste it whole: keep your own version numbers.

Gradle Scripts › build.gradle.kts (Module :app)Read only
plugins {    alias(libs.plugins.android.application)}
android { namespace = "com.yourname.notes" compileSdk { version = release(37) }
defaultConfig { applicationId = "com.yourname.notes" minSdk = 24 targetSdk = 37 versionCode = 1 versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" }
buildTypes { release { optimization { enable = true packageScope = setOf("androidx.**", "kotlin.**", "kotlinx.**") } } } compileOptions { sourceCompatibility = JavaVersion.VERSION_11 targetCompatibility = JavaVersion.VERSION_11 }}
dependencies { implementation(libs.appcompat) implementation(libs.material) implementation("androidx.constraintlayout:constraintlayout:2.2.2") implementation("com.squareup.retrofit2:retrofit:3.0.0") implementation("com.squareup.retrofit2:converter-gson:3.0.0") testImplementation(libs.junit) androidTestImplementation(libs.espresso.core) androidTestImplementation(libs.ext.junit)}

Step 2 of 6

Describe the API in an interface

10 min

Goal Write the API (the four requests the app sends) as four methods with no code: Retrofit writes the code.

  • Java kotlin+java › com.yourname.notes › NoteInput.java · NotesApi.java
The four requests the app sends
The app sendsThe server answers
Read allGET /notescode 200 and the list
CreatePOST /notes + a title and a descriptioncode 201 and the note with its id
EditPUT /notes/4 + a title and a descriptioncode 200 and the note
DeleteDELETE /notes/4code 204, empty
  1. Paste The class NoteInput: what the app sends to the server.

    1. In Project, right-click the plain kotlin+java › com.yourname.notes, as in step 8.1.
    2. Choose NewJava Class, type NoteInput, then press Enter.
    3. Click Copy the file, on the panel below.
    4. Click in the class, press Ctrl+A, then Ctrl+V.
    kotlin+java › com.yourname.notes › NoteInput.javaReplace the whole file
    package com.yourname.notes;
    public class NoteInput { public String title; public String description;
    public NoteInput(String title, String description) { this.title = title; this.description = description; }}

    Only title and description. The server makes the id, and refuses any other key.

  2. Paste The interface NotesApi: one method per request.

    1. Do a’s gestures 1 to 4 again, with the name NotesApi and the panel below.
    kotlin+java › com.yourname.notes › NotesApi.javaReplace the whole file
    package com.yourname.notes;
    import java.util.List;
    import retrofit2.Call;import retrofit2.Retrofit;import retrofit2.converter.gson.GsonConverterFactory;import retrofit2.http.Body;import retrofit2.http.DELETE;import retrofit2.http.GET;import retrofit2.http.POST;import retrofit2.http.PUT;import retrofit2.http.Path;
    public interface NotesApi {
    @GET("notes") Call<List<Note>> getNotes();
    @POST("notes") Call<Note> createNote(@Body NoteInput input);
    @PUT("notes/{id}") Call<Note> updateNote(@Path("id") int id, @Body NoteInput input);
    @DELETE("notes/{id}") Call<Void> deleteNote(@Path("id") int id);
    NotesApi SERVER = new Retrofit.Builder() .baseUrl("https://bachelor-gl.site/") .addConverterFactory(GsonConverterFactory.create()) .build() .create(NotesApi.class);}
    1. "notes": the path. Retrofit adds it to the address of line 30.
    2. Call<List<Note>>: a request whose answer is a list of notes.
    3. @Body: Gson turns the NoteInput into JSON text, and Retrofit sends it.
    4. {id} takes the value of @Path("id"): notes/4 for the note 4.
    5. Call<Void>: an empty answer.
  3. The end of the same file: SERVER, the object you call.

    kotlin+java › com.yourname.notes › NotesApi.javaRead only
    package com.yourname.notes;
    import java.util.List;
    import retrofit2.Call;import retrofit2.Retrofit;import retrofit2.converter.gson.GsonConverterFactory;import retrofit2.http.Body;import retrofit2.http.DELETE;import retrofit2.http.GET;import retrofit2.http.POST;import retrofit2.http.PUT;import retrofit2.http.Path;
    public interface NotesApi {
    @GET("notes") Call<List<Note>> getNotes();
    @POST("notes") Call<Note> createNote(@Body NoteInput input);
    @PUT("notes/{id}") Call<Note> updateNote(@Path("id") int id, @Body NoteInput input);
    @DELETE("notes/{id}") Call<Void> deleteNote(@Path("id") int id);
    NotesApi SERVER = new Retrofit.Builder() .baseUrl("https://bachelor-gl.site/") .addConverterFactory(GsonConverterFactory.create()) .build() .create(NotesApi.class);}
    1. SERVER: the object Retrofit builds from the interface. baseUrl is the server’s address; addConverterFactory hands the JSON to Gson. You call its four methods.

Predict

Which request does NotesApi.SERVER.updateNote(4, new NoteInput("Exam", "Monday")) describe?

See the answer

PUT https://bachelor-gl.site/notes/4, with the text {"title":"Exam","description":"Monday"}: the address, the path with {id} = 4, and the @Body written in JSON by Gson.

Done I see no red code in NotesApi.java. Nothing to run yet.

Stuck? 1 symptom · the files
  • NotesApi has a C icon, not an I The file still holds the class Android Studio wrote. Do action b again: Ctrl+A, then Ctrl+V over it.
Project › kotlin+java Project window · leftFull size
The Project window: under kotlin+java, the plain com.yourname.notes holds MainActivity, Note, NoteActivity, NoteInput and NotesApi; NotesApi has an I icon, the others a C.
  1. Your two new files, beside Note. The icon says what each one is: C for a class, I for an interface.

The panels of actions a and b hold the two files at the end of this step: click Copy the file on each.

By hand, then with Retrofit

Part 9, by hand: this block, plus download() and parse(). 38 lines.

kotlin+java › com.yourname.notes › MainActivity.javaRead only
package com.yourname.notes;
import android.content.Intent;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import java.util.ArrayList;import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Lifecycle"; private static final String NOTES_URL = "https://bachelor-gl.site/notes"; private static final int[] NOTE_BACKGROUNDS = { R.drawable.bg_note_butter, R.drawable.bg_note_mint, R.drawable.bg_note_lavender, R.drawable.bg_note_peach };
private TextView textCount; private TextView textEmpty; private LinearLayout notesContainer; private int notesAdded = 0;
private EditText editTitle; private EditText editBody; private TextView textError; private TextView textCounter;
private final TextWatcher formWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
@Override public void onTextChanged(CharSequence s, int start, int before, int count) { }
@Override public void afterTextChanged(Editable s) { updateForm(); } };
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d(TAG, "Main onCreate");
textCount = findViewById(R.id.textCount); textEmpty = findViewById(R.id.textEmpty); notesContainer = findViewById(R.id.notesContainer);
textEmpty.setOnClickListener(v -> loadNotes()); loadNotes();
editTitle = findViewById(R.id.editTitle); editBody = findViewById(R.id.editBody); textError = findViewById(R.id.textError); textCounter = findViewById(R.id.textCounter);
Button buttonAdd = findViewById(R.id.buttonAdd); buttonAdd.setOnClickListener(v -> addNoteFromComposer());
editTitle.addTextChangedListener(formWatcher); editBody.addTextChangedListener(formWatcher); }
private void loadNotes() { textEmpty.setText(R.string.loading); updateCount(); new Thread(() -> { try { String json = download(NOTES_URL); List<Note> notes = parse(json); runOnUiThread(() -> showNotes(notes)); } catch (IOException | JSONException e) { Log.e(TAG, "loadNotes failed", e); runOnUiThread(() -> textEmpty.setText(R.string.error_network)); } }).start(); }
private String download(String address) throws IOException { URL url = new URL(address); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(10000); connection.setReadTimeout(10000); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder text = new StringBuilder(); String line = reader.readLine(); while (line != null) { text.append(line); line = reader.readLine(); } reader.close(); return text.toString(); }
private List<Note> parse(String json) throws JSONException { List<Note> notes = new ArrayList<>(); JSONArray array = new JSONArray(json); for (int i = 0; i < array.length(); i++) { JSONObject object = array.getJSONObject(i); Note note = new Note(); note.id = object.getInt("id"); note.title = object.getString("title"); note.description = object.getString("description"); notes.add(note); } return notes; }
private void showNotes(List<Note> notes) { notesContainer.removeAllViews(); notesAdded = 0; for (Note note : notes) { addNote(note.title, note.description); } textEmpty.setText(R.string.empty); updateCount(); }
private void updateCount() { int count = notesContainer.getChildCount(); textCount.setText(String.valueOf(count)); textEmpty.setVisibility(count == 0 ? View.VISIBLE : View.GONE); }
private void addNote(String title, String body) { View card = LayoutInflater.from(this).inflate(R.layout.item_note, notesContainer, false); TextView cardTitle = card.findViewById(R.id.textNoteTitle); TextView cardBody = card.findViewById(R.id.textNoteBody); cardTitle.setText(title); cardBody.setText(body); cardBody.setVisibility(body.isEmpty() ? View.GONE : View.VISIBLE); int background = NOTE_BACKGROUNDS[notesAdded % NOTE_BACKGROUNDS.length]; card.setBackgroundResource(background); notesAdded++;
card.setOnClickListener(v -> openNote(title, body, background)); card.setOnLongClickListener(v -> { notesContainer.removeView(card); updateCount(); Toast.makeText(this, R.string.note_deleted, Toast.LENGTH_SHORT).show(); return true; });
notesContainer.addView(card, 0); }
private void addNoteFromComposer() { String title = editTitle.getText().toString().trim(); String body = editBody.getText().toString().trim(); if (title.isEmpty()) { textError.setVisibility(View.VISIBLE); return; } textError.setVisibility(View.GONE); addNote(title, body); updateCount(); editTitle.setText(""); editBody.setText(""); Toast.makeText(this, R.string.note_added, Toast.LENGTH_SHORT).show(); }
private void updateForm() { int length = editBody.length(); textCounter.setText(getString(R.string.counter, length)); int colour = length >= 120 ? R.color.error : R.color.muted; textCounter.setTextColor(getColor(colour)); if (editTitle.length() > 0) { textError.setVisibility(View.GONE); } }
public void onClearClicked(View view) { editTitle.setText(""); editBody.setText(""); }
private void openNote(String title, String body, int background) { Intent intent = new Intent(this, NoteActivity.class); intent.putExtra(NoteActivity.EXTRA_TITLE, title); intent.putExtra(NoteActivity.EXTRA_BODY, body); intent.putExtra(NoteActivity.EXTRA_BACKGROUND, background); startActivity(intent); }
@Override protected void onStart() { super.onStart(); Log.d(TAG, "Main onStart"); }
@Override protected void onResume() { super.onResume(); Log.d(TAG, "Main onResume"); }
@Override protected void onPause() { super.onPause(); Log.d(TAG, "Main onPause"); }
@Override protected void onStop() { super.onStop(); Log.d(TAG, "Main onStop"); }
@Override protected void onRestart() { super.onRestart(); Log.d(TAG, "Main onRestart"); }
@Override protected void onDestroy() { super.onDestroy(); Log.d(TAG, "Main onDestroy"); }}

Part 10, with Retrofit: this block, plus the interface you wrote once for the four requests. 15 lines here.

kotlin+java › com.yourname.notes › MainActivity.javaRead only
package com.yourname.notes;
import android.content.Intent;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.List;
import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Lifecycle"; private static final int[] NOTE_BACKGROUNDS = { R.drawable.bg_note_butter, R.drawable.bg_note_mint, R.drawable.bg_note_lavender, R.drawable.bg_note_peach };
private TextView textCount; private TextView textEmpty; private LinearLayout notesContainer; private int notesAdded = 0;
private EditText editTitle; private EditText editBody; private TextView textError; private TextView textCounter;
private final TextWatcher formWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
@Override public void onTextChanged(CharSequence s, int start, int before, int count) { }
@Override public void afterTextChanged(Editable s) { updateForm(); } };
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d(TAG, "Main onCreate");
textCount = findViewById(R.id.textCount); textEmpty = findViewById(R.id.textEmpty); notesContainer = findViewById(R.id.notesContainer);
textEmpty.setOnClickListener(v -> loadNotes());
editTitle = findViewById(R.id.editTitle); editBody = findViewById(R.id.editBody); textError = findViewById(R.id.textError); textCounter = findViewById(R.id.textCounter);
Button buttonAdd = findViewById(R.id.buttonAdd); buttonAdd.setOnClickListener(v -> addNoteFromComposer());
editTitle.addTextChangedListener(formWatcher); editBody.addTextChangedListener(formWatcher); }
private void loadNotes() { textEmpty.setText(R.string.loading); updateCount(); NotesApi.SERVER.getNotes().enqueue(new Callback<List<Note>>() { @Override public void onResponse(Call<List<Note>> call, Response<List<Note>> response) { if (response.isSuccessful()) { showNotes(response.body()); } else { showRefused(response.code()); } }
@Override public void onFailure(Call<List<Note>> call, Throwable t) { showNoAnswer(t); } }); }
private void showRefused(int code) { Toast.makeText(this, getString(R.string.server_refused, code), Toast.LENGTH_LONG).show(); }
private void showNoAnswer(Throwable t) { Log.e(TAG, "No answer from the server", t); textEmpty.setText(R.string.error_network); Toast.makeText(this, R.string.no_answer, Toast.LENGTH_LONG).show(); }
private void showNotes(List<Note> notes) { notesContainer.removeAllViews(); notesAdded = 0; for (Note note : notes) { addNote(note.title, note.description); } textEmpty.setText(R.string.empty); updateCount(); }
private void updateCount() { int count = notesContainer.getChildCount(); textCount.setText(String.valueOf(count)); textEmpty.setVisibility(count == 0 ? View.VISIBLE : View.GONE); }
private void addNote(String title, String body) { View card = LayoutInflater.from(this).inflate(R.layout.item_note, notesContainer, false); TextView cardTitle = card.findViewById(R.id.textNoteTitle); TextView cardBody = card.findViewById(R.id.textNoteBody); cardTitle.setText(title); cardBody.setText(body); cardBody.setVisibility(body.isEmpty() ? View.GONE : View.VISIBLE); int background = NOTE_BACKGROUNDS[notesAdded % NOTE_BACKGROUNDS.length]; card.setBackgroundResource(background); notesAdded++;
card.setOnClickListener(v -> openNote(title, body, background)); card.setOnLongClickListener(v -> { notesContainer.removeView(card); updateCount(); Toast.makeText(this, R.string.note_deleted, Toast.LENGTH_SHORT).show(); return true; });
notesContainer.addView(card, 0); }
private void addNoteFromComposer() { String title = editTitle.getText().toString().trim(); String body = editBody.getText().toString().trim(); if (title.isEmpty()) { textError.setVisibility(View.VISIBLE); return; } textError.setVisibility(View.GONE); addNote(title, body); updateCount(); editTitle.setText(""); editBody.setText(""); Toast.makeText(this, R.string.note_added, Toast.LENGTH_SHORT).show(); }
private void updateForm() { int length = editBody.length(); textCounter.setText(getString(R.string.counter, length)); int colour = length >= 120 ? R.color.error : R.color.muted; textCounter.setTextColor(getColor(colour)); if (editTitle.length() > 0) { textError.setVisibility(View.GONE); } }
public void onClearClicked(View view) { editTitle.setText(""); editBody.setText(""); }
private void openNote(String title, String body, int background) { Intent intent = new Intent(this, NoteActivity.class); intent.putExtra(NoteActivity.EXTRA_TITLE, title); intent.putExtra(NoteActivity.EXTRA_BODY, body); intent.putExtra(NoteActivity.EXTRA_BACKGROUND, background); startActivity(intent); }
@Override protected void onStart() { super.onStart(); Log.d(TAG, "Main onStart"); }
@Override protected void onResume() { super.onResume(); Log.d(TAG, "Main onResume"); loadNotes(); }
@Override protected void onPause() { super.onPause(); Log.d(TAG, "Main onPause"); }
@Override protected void onStop() { super.onStop(); Log.d(TAG, "Main onStop"); }
@Override protected void onRestart() { super.onRestart(); Log.d(TAG, "Main onRestart"); }
@Override protected void onDestroy() { super.onDestroy(); Log.d(TAG, "Main onDestroy"); }}
  1. enqueue: Retrofit sends the request on another thread, then calls you back on the main thread. The Callback is an anonymous class, like the TextWatcher of step 7.3.
  2. onResponse: the server answered, yes or no. JavaScript’s load.
  3. response.body(): the notes, already objects. Gson did your parse(): it fills each instance variable of Note from the JSON key of the same name.
  4. response.code(): the answer’s code. 200 to 299: yes. Others, such as 404: no.
  5. onFailure: no usable answer, for example no network, or nothing after 10 seconds. JavaScript’s error.

Predict

onResponse calls showNotes() with no runOnUiThread. Why no crash?

See the answer

Retrofit calls onResponse and onFailure on the main thread.

Step 3 of 6

Read: the same list, with less code

12 min

Goal Load the notes with Retrofit: the same screen, with less code.

  • Resources res › values › strings.xml
  • Java MainActivity.java
  • Emulator
  1. Paste Two more strings, in strings.xml.

    1. Open res › values › strings.xml.
    2. Beside After line 20, below, click Copy 2 lines.
    3. Click at the end of line 20, press Enter, then Ctrl+V.
    res › values › strings.xmlAdd the marked lines
    <resources>    <string name="app_name">Notes</string>    <string name="logo_description">Notes logo</string>    <string name="count_start">0</string>    <string name="title_hint">Title</string>    <string name="body_hint">Write something…</string>    <string name="error_no_title">Give your note a title first.</string>    <string name="counter_start">0 / 140</string>    <string name="counter">%1$d / 140</string>    <string name="clear">Clear</string>    <string name="add">Add</string>    <string name="your_notes">YOUR NOTES</string>    <string name="list_hint">Tap to open · hold to delete</string>    <string name="empty">No notes yet.\nWrite your first one above.</string>    <string name="note_added">Note added</string>    <string name="note_deleted">Note deleted</string>    <string name="note_kicker">NOTE</string>    <string name="back_to_notes">Back to notes</string>    <string name="share">Share</string>    <string name="loading">Asking the server…</string>    <string name="server_refused">The server answered %1$d</string>    <string name="no_answer">No answer from the server.</string>    <string name="error_network">No answer from the server.\nTap here to try again.</string></resources>

    server_refused: the server answers no; %1$d is the place of the server’s code. no_answer: it does not answer.

  2. Paste The new MainActivity.java, whole.

    1. Open MainActivity.java.
    2. Click Copy the file, below.
    3. Click in the code, press Ctrl+A, then Ctrl+V.
    kotlin+java › com.yourname.notes › MainActivity.javaReplace the whole file
    package com.yourname.notes;
    import android.content.Intent;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast;
    import androidx.appcompat.app.AppCompatActivity;
    import java.util.List;
    import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;
    public class MainActivity extends AppCompatActivity {
    private static final String TAG = "Lifecycle"; private static final int[] NOTE_BACKGROUNDS = { R.drawable.bg_note_butter, R.drawable.bg_note_mint, R.drawable.bg_note_lavender, R.drawable.bg_note_peach };
    private TextView textCount; private TextView textEmpty; private LinearLayout notesContainer; private int notesAdded = 0;
    private EditText editTitle; private EditText editBody; private TextView textError; private TextView textCounter;
    private final TextWatcher formWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
    @Override public void onTextChanged(CharSequence s, int start, int before, int count) { }
    @Override public void afterTextChanged(Editable s) { updateForm(); } };
    @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d(TAG, "Main onCreate");
    textCount = findViewById(R.id.textCount); textEmpty = findViewById(R.id.textEmpty); notesContainer = findViewById(R.id.notesContainer);
    textEmpty.setOnClickListener(v -> loadNotes());
    editTitle = findViewById(R.id.editTitle); editBody = findViewById(R.id.editBody); textError = findViewById(R.id.textError); textCounter = findViewById(R.id.textCounter);
    Button buttonAdd = findViewById(R.id.buttonAdd); buttonAdd.setOnClickListener(v -> addNoteFromComposer());
    editTitle.addTextChangedListener(formWatcher); editBody.addTextChangedListener(formWatcher); }
    private void loadNotes() { textEmpty.setText(R.string.loading); updateCount(); NotesApi.SERVER.getNotes().enqueue(new Callback<List<Note>>() { @Override public void onResponse(Call<List<Note>> call, Response<List<Note>> response) { if (response.isSuccessful()) { showNotes(response.body()); } else { showRefused(response.code()); } }
    @Override public void onFailure(Call<List<Note>> call, Throwable t) { showNoAnswer(t); } }); }
    private void showRefused(int code) { Toast.makeText(this, getString(R.string.server_refused, code), Toast.LENGTH_LONG).show(); }
    private void showNoAnswer(Throwable t) { Log.e(TAG, "No answer from the server", t); textEmpty.setText(R.string.error_network); Toast.makeText(this, R.string.no_answer, Toast.LENGTH_LONG).show(); }
    private void showNotes(List<Note> notes) { notesContainer.removeAllViews(); notesAdded = 0; for (Note note : notes) { addNote(note.title, note.description); } textEmpty.setText(R.string.empty); updateCount(); }
    private void updateCount() { int count = notesContainer.getChildCount(); textCount.setText(String.valueOf(count)); textEmpty.setVisibility(count == 0 ? View.VISIBLE : View.GONE); }
    private void addNote(String title, String body) { View card = LayoutInflater.from(this).inflate(R.layout.item_note, notesContainer, false); TextView cardTitle = card.findViewById(R.id.textNoteTitle); TextView cardBody = card.findViewById(R.id.textNoteBody); cardTitle.setText(title); cardBody.setText(body); cardBody.setVisibility(body.isEmpty() ? View.GONE : View.VISIBLE); int background = NOTE_BACKGROUNDS[notesAdded % NOTE_BACKGROUNDS.length]; card.setBackgroundResource(background); notesAdded++;
    card.setOnClickListener(v -> openNote(title, body, background)); card.setOnLongClickListener(v -> { notesContainer.removeView(card); updateCount(); Toast.makeText(this, R.string.note_deleted, Toast.LENGTH_SHORT).show(); return true; });
    notesContainer.addView(card, 0); }
    private void addNoteFromComposer() { String title = editTitle.getText().toString().trim(); String body = editBody.getText().toString().trim(); if (title.isEmpty()) { textError.setVisibility(View.VISIBLE); return; } textError.setVisibility(View.GONE); addNote(title, body); updateCount(); editTitle.setText(""); editBody.setText(""); Toast.makeText(this, R.string.note_added, Toast.LENGTH_SHORT).show(); }
    private void updateForm() { int length = editBody.length(); textCounter.setText(getString(R.string.counter, length)); int colour = length >= 120 ? R.color.error : R.color.muted; textCounter.setTextColor(getColor(colour)); if (editTitle.length() > 0) { textError.setVisibility(View.GONE); } }
    public void onClearClicked(View view) { editTitle.setText(""); editBody.setText(""); }
    private void openNote(String title, String body, int background) { Intent intent = new Intent(this, NoteActivity.class); intent.putExtra(NoteActivity.EXTRA_TITLE, title); intent.putExtra(NoteActivity.EXTRA_BODY, body); intent.putExtra(NoteActivity.EXTRA_BACKGROUND, background); startActivity(intent); }
    @Override protected void onStart() { super.onStart(); Log.d(TAG, "Main onStart"); }
    @Override protected void onResume() { super.onResume(); Log.d(TAG, "Main onResume"); loadNotes(); }
    @Override protected void onPause() { super.onPause(); Log.d(TAG, "Main onPause"); }
    @Override protected void onStop() { super.onStop(); Log.d(TAG, "Main onStop"); }
    @Override protected void onRestart() { super.onRestart(); Log.d(TAG, "Main onRestart"); }
    @Override protected void onDestroy() { super.onDestroy(); Log.d(TAG, "Main onDestroy"); }}

    download() and parse() are gone. Line 199: loadNotes() now runs in onResume(), at launch and each time the screen comes back: step 10.6 needs it, when the note page closes.

  3. The same list, on the phone.

    1. Click ▶ Run 'app' (↻ Rerun if the app is running).
The emulator: the same notes screen as at the end of Part 9, with the three notes read from the server and the pill 3.

You should see The server’s notes, as at the end of Part 9. The whole class shares the list: yours may not match the picture.

Done I see the server’s notes again.

Stuck? 2 symptoms · the file
  • The screen says “No answer from the server. Tap here to try again.” The phone reached no server. Check its network (airplane mode off), then tap the message.
  • A Toast says “The server answered 503” (or another code from 500 up), and the screen keeps “Asking the server…” The server is busy. Tap the message to ask again.

Action b’s panel holds the whole file at the end of this step: click Copy the file.

Step 4 of 6

Create: make Add talk to the server

12 min

Goal Make Add send the note to the server with a POST, then draw the card from its answer.

  • Java MainActivity.java
  • Emulator Running Devices
  1. Type addNote() takes a whole Note, with its id.

    1. On line 117, replace note.title, note.description with note.
    2. On line 129, replace String title, String body with Note note.
    3. On lines 133, 134, 135 and 140, replace title with note.title, and body with note.description.
    4. Line 159, addNote(title, body);, turns red: action c replaces it.
    kotlin+java › com.yourname.notes › MainActivity.javaAdd the marked lines
    package com.yourname.notes;
    import android.content.Intent;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast;
    import androidx.appcompat.app.AppCompatActivity;
    import java.util.List;
    import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;
    public class MainActivity extends AppCompatActivity {
    private static final String TAG = "Lifecycle"; private static final int[] NOTE_BACKGROUNDS = { R.drawable.bg_note_butter, R.drawable.bg_note_mint, R.drawable.bg_note_lavender, R.drawable.bg_note_peach };
    private TextView textCount; private TextView textEmpty; private LinearLayout notesContainer; private int notesAdded = 0;
    private EditText editTitle; private EditText editBody; private TextView textError; private TextView textCounter;
    private final TextWatcher formWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
    @Override public void onTextChanged(CharSequence s, int start, int before, int count) { }
    @Override public void afterTextChanged(Editable s) { updateForm(); } };
    @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d(TAG, "Main onCreate");
    textCount = findViewById(R.id.textCount); textEmpty = findViewById(R.id.textEmpty); notesContainer = findViewById(R.id.notesContainer);
    textEmpty.setOnClickListener(v -> loadNotes());
    editTitle = findViewById(R.id.editTitle); editBody = findViewById(R.id.editBody); textError = findViewById(R.id.textError); textCounter = findViewById(R.id.textCounter);
    Button buttonAdd = findViewById(R.id.buttonAdd); buttonAdd.setOnClickListener(v -> addNoteFromComposer());
    editTitle.addTextChangedListener(formWatcher); editBody.addTextChangedListener(formWatcher); }
    private void loadNotes() { textEmpty.setText(R.string.loading); updateCount(); NotesApi.SERVER.getNotes().enqueue(new Callback<List<Note>>() { @Override public void onResponse(Call<List<Note>> call, Response<List<Note>> response) { if (response.isSuccessful()) { showNotes(response.body()); } else { showRefused(response.code()); } }
    @Override public void onFailure(Call<List<Note>> call, Throwable t) { showNoAnswer(t); } }); }
    private void showRefused(int code) { Toast.makeText(this, getString(R.string.server_refused, code), Toast.LENGTH_LONG).show(); }
    private void showNoAnswer(Throwable t) { Log.e(TAG, "No answer from the server", t); textEmpty.setText(R.string.error_network); Toast.makeText(this, R.string.no_answer, Toast.LENGTH_LONG).show(); }
    private void showNotes(List<Note> notes) { notesContainer.removeAllViews(); notesAdded = 0; for (Note note : notes) { addNote(note); } textEmpty.setText(R.string.empty); updateCount(); }
    private void updateCount() { int count = notesContainer.getChildCount(); textCount.setText(String.valueOf(count)); textEmpty.setVisibility(count == 0 ? View.VISIBLE : View.GONE); }
    private void addNote(Note note) { View card = LayoutInflater.from(this).inflate(R.layout.item_note, notesContainer, false); TextView cardTitle = card.findViewById(R.id.textNoteTitle); TextView cardBody = card.findViewById(R.id.textNoteBody); cardTitle.setText(note.title); cardBody.setText(note.description); cardBody.setVisibility(note.description.isEmpty() ? View.GONE : View.VISIBLE); int background = NOTE_BACKGROUNDS[notesAdded % NOTE_BACKGROUNDS.length]; card.setBackgroundResource(background); notesAdded++;
    card.setOnClickListener(v -> openNote(note.title, note.description, background)); card.setOnLongClickListener(v -> { notesContainer.removeView(card); updateCount(); Toast.makeText(this, R.string.note_deleted, Toast.LENGTH_SHORT).show(); return true; });
    notesContainer.addView(card, 0); }
    private void addNoteFromComposer() { String title = editTitle.getText().toString().trim(); String body = editBody.getText().toString().trim(); if (title.isEmpty()) { textError.setVisibility(View.VISIBLE); return; } textError.setVisibility(View.GONE); NoteInput input = new NoteInput(title, body); NotesApi.SERVER.createNote(input).enqueue(new Callback<Note>() { @Override public void onResponse(Call<Note> call, Response<Note> response) { if (response.isSuccessful()) { addNote(response.body()); updateCount(); editTitle.setText(""); editBody.setText(""); Toast.makeText(MainActivity.this, R.string.note_added, Toast.LENGTH_SHORT).show(); } else { showRefused(response.code()); } }
    @Override public void onFailure(Call<Note> call, Throwable t) { showNoAnswer(t); } }); }
    private void updateForm() { int length = editBody.length(); textCounter.setText(getString(R.string.counter, length)); int colour = length >= 120 ? R.color.error : R.color.muted; textCounter.setTextColor(getColor(colour)); if (editTitle.length() > 0) { textError.setVisibility(View.GONE); } }
    public void onClearClicked(View view) { editTitle.setText(""); editBody.setText(""); }
    private void openNote(String title, String body, int background) { Intent intent = new Intent(this, NoteActivity.class); intent.putExtra(NoteActivity.EXTRA_TITLE, title); intent.putExtra(NoteActivity.EXTRA_BODY, body); intent.putExtra(NoteActivity.EXTRA_BACKGROUND, background); startActivity(intent); }
    @Override protected void onStart() { super.onStart(); Log.d(TAG, "Main onStart"); }
    @Override protected void onResume() { super.onResume(); Log.d(TAG, "Main onResume"); loadNotes(); }
    @Override protected void onPause() { super.onPause(); Log.d(TAG, "Main onPause"); }
    @Override protected void onStop() { super.onStop(); Log.d(TAG, "Main onStop"); }
    @Override protected void onRestart() { super.onRestart(); Log.d(TAG, "Main onRestart"); }
    @Override protected void onDestroy() { super.onDestroy(); Log.d(TAG, "Main onDestroy"); }}
  2. Paste Add sends a POST. The server’s answer becomes the card.

    1. Beside After line 158, below, click Copy 20 lines.
    kotlin+java › com.yourname.notes › MainActivity.javaAdd the marked lines
    package com.yourname.notes;
    import android.content.Intent;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast;
    import androidx.appcompat.app.AppCompatActivity;
    import java.util.List;
    import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;
    public class MainActivity extends AppCompatActivity {
    private static final String TAG = "Lifecycle"; private static final int[] NOTE_BACKGROUNDS = { R.drawable.bg_note_butter, R.drawable.bg_note_mint, R.drawable.bg_note_lavender, R.drawable.bg_note_peach };
    private TextView textCount; private TextView textEmpty; private LinearLayout notesContainer; private int notesAdded = 0;
    private EditText editTitle; private EditText editBody; private TextView textError; private TextView textCounter;
    private final TextWatcher formWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
    @Override public void onTextChanged(CharSequence s, int start, int before, int count) { }
    @Override public void afterTextChanged(Editable s) { updateForm(); } };
    @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d(TAG, "Main onCreate");
    textCount = findViewById(R.id.textCount); textEmpty = findViewById(R.id.textEmpty); notesContainer = findViewById(R.id.notesContainer);
    textEmpty.setOnClickListener(v -> loadNotes());
    editTitle = findViewById(R.id.editTitle); editBody = findViewById(R.id.editBody); textError = findViewById(R.id.textError); textCounter = findViewById(R.id.textCounter);
    Button buttonAdd = findViewById(R.id.buttonAdd); buttonAdd.setOnClickListener(v -> addNoteFromComposer());
    editTitle.addTextChangedListener(formWatcher); editBody.addTextChangedListener(formWatcher); }
    private void loadNotes() { textEmpty.setText(R.string.loading); updateCount(); NotesApi.SERVER.getNotes().enqueue(new Callback<List<Note>>() { @Override public void onResponse(Call<List<Note>> call, Response<List<Note>> response) { if (response.isSuccessful()) { showNotes(response.body()); } else { showRefused(response.code()); } }
    @Override public void onFailure(Call<List<Note>> call, Throwable t) { showNoAnswer(t); } }); }
    private void showRefused(int code) { Toast.makeText(this, getString(R.string.server_refused, code), Toast.LENGTH_LONG).show(); }
    private void showNoAnswer(Throwable t) { Log.e(TAG, "No answer from the server", t); textEmpty.setText(R.string.error_network); Toast.makeText(this, R.string.no_answer, Toast.LENGTH_LONG).show(); }
    private void showNotes(List<Note> notes) { notesContainer.removeAllViews(); notesAdded = 0; for (Note note : notes) { addNote(note); } textEmpty.setText(R.string.empty); updateCount(); }
    private void updateCount() { int count = notesContainer.getChildCount(); textCount.setText(String.valueOf(count)); textEmpty.setVisibility(count == 0 ? View.VISIBLE : View.GONE); }
    private void addNote(Note note) { View card = LayoutInflater.from(this).inflate(R.layout.item_note, notesContainer, false); TextView cardTitle = card.findViewById(R.id.textNoteTitle); TextView cardBody = card.findViewById(R.id.textNoteBody); cardTitle.setText(note.title); cardBody.setText(note.description); cardBody.setVisibility(note.description.isEmpty() ? View.GONE : View.VISIBLE); int background = NOTE_BACKGROUNDS[notesAdded % NOTE_BACKGROUNDS.length]; card.setBackgroundResource(background); notesAdded++;
    card.setOnClickListener(v -> openNote(note.title, note.description, background)); card.setOnLongClickListener(v -> { notesContainer.removeView(card); updateCount(); Toast.makeText(this, R.string.note_deleted, Toast.LENGTH_SHORT).show(); return true; });
    notesContainer.addView(card, 0); }
    private void addNoteFromComposer() { String title = editTitle.getText().toString().trim(); String body = editBody.getText().toString().trim(); if (title.isEmpty()) { textError.setVisibility(View.VISIBLE); return; } textError.setVisibility(View.GONE); NoteInput input = new NoteInput(title, body); NotesApi.SERVER.createNote(input).enqueue(new Callback<Note>() { @Override public void onResponse(Call<Note> call, Response<Note> response) { if (response.isSuccessful()) { addNote(response.body()); updateCount(); editTitle.setText(""); editBody.setText(""); Toast.makeText(MainActivity.this, R.string.note_added, Toast.LENGTH_SHORT).show(); } else { showRefused(response.code()); } }
    @Override public void onFailure(Call<Note> call, Throwable t) { showNoAnswer(t); } }); }
    private void updateForm() { int length = editBody.length(); textCounter.setText(getString(R.string.counter, length)); int colour = length >= 120 ? R.color.error : R.color.muted; textCounter.setTextColor(getColor(colour)); if (editTitle.length() > 0) { textError.setVisibility(View.GONE); } }
    public void onClearClicked(View view) { editTitle.setText(""); editBody.setText(""); }
    private void openNote(String title, String body, int background) { Intent intent = new Intent(this, NoteActivity.class); intent.putExtra(NoteActivity.EXTRA_TITLE, title); intent.putExtra(NoteActivity.EXTRA_BODY, body); intent.putExtra(NoteActivity.EXTRA_BACKGROUND, background); startActivity(intent); }
    @Override protected void onStart() { super.onStart(); Log.d(TAG, "Main onStart"); }
    @Override protected void onResume() { super.onResume(); Log.d(TAG, "Main onResume"); loadNotes(); }
    @Override protected void onPause() { super.onPause(); Log.d(TAG, "Main onPause"); }
    @Override protected void onStop() { super.onStop(); Log.d(TAG, "Main onStop"); }
    @Override protected void onRestart() { super.onRestart(); Log.d(TAG, "Main onRestart"); }
    @Override protected void onDestroy() { super.onDestroy(); Log.d(TAG, "Main onDestroy"); }}
  3. The five old lines, replaced by these 20.

    1. In the editor, click at the end of line 158, the textError line.
    2. Hold Shift and click at the end of line 163, the Toast line.
    3. Lines 159 to 163 are selected: press Enter, then Ctrl+V.
  4. A note that stays.

    1. Click ▶ Run 'app' (↻ Rerun if the app is running).
    2. On the phone, type Call Yasmine in Title.
    3. In class, add your first name after it: the list is shared. The pictures show the title alone.
    4. Type Before 6 pm. in Write something…, then tap Add.
    5. Close the keyboard with its down arrow, at the bottom left of the phone.
    6. In Running Devices, click Rotate Left, then Rotate Right: the note is still there.
The emulator after Add: the card Call Yasmine, Before 6 pm., on top of the three other notes, the pill 4, and the Toast Note added.

You should see Call Yasmine on top, and the Toast “Note added”. The list is the class’s: your pill may not say 4.

Done I see my note on top, and it stays when I turn the phone.

Stuck? 1 symptom · the file
  • Two identical cards Add was tapped twice before the server answered. Each tap is one POST. Delete one once step 10.5 is done.

Behind? The files at the end of this step

kotlin+java › com.yourname.notes › MainActivity.javaReplace the whole file
package com.yourname.notes;
import android.content.Intent;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.List;
import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Lifecycle"; private static final int[] NOTE_BACKGROUNDS = { R.drawable.bg_note_butter, R.drawable.bg_note_mint, R.drawable.bg_note_lavender, R.drawable.bg_note_peach };
private TextView textCount; private TextView textEmpty; private LinearLayout notesContainer; private int notesAdded = 0;
private EditText editTitle; private EditText editBody; private TextView textError; private TextView textCounter;
private final TextWatcher formWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
@Override public void onTextChanged(CharSequence s, int start, int before, int count) { }
@Override public void afterTextChanged(Editable s) { updateForm(); } };
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d(TAG, "Main onCreate");
textCount = findViewById(R.id.textCount); textEmpty = findViewById(R.id.textEmpty); notesContainer = findViewById(R.id.notesContainer);
textEmpty.setOnClickListener(v -> loadNotes());
editTitle = findViewById(R.id.editTitle); editBody = findViewById(R.id.editBody); textError = findViewById(R.id.textError); textCounter = findViewById(R.id.textCounter);
Button buttonAdd = findViewById(R.id.buttonAdd); buttonAdd.setOnClickListener(v -> addNoteFromComposer());
editTitle.addTextChangedListener(formWatcher); editBody.addTextChangedListener(formWatcher); }
private void loadNotes() { textEmpty.setText(R.string.loading); updateCount(); NotesApi.SERVER.getNotes().enqueue(new Callback<List<Note>>() { @Override public void onResponse(Call<List<Note>> call, Response<List<Note>> response) { if (response.isSuccessful()) { showNotes(response.body()); } else { showRefused(response.code()); } }
@Override public void onFailure(Call<List<Note>> call, Throwable t) { showNoAnswer(t); } }); }
private void showRefused(int code) { Toast.makeText(this, getString(R.string.server_refused, code), Toast.LENGTH_LONG).show(); }
private void showNoAnswer(Throwable t) { Log.e(TAG, "No answer from the server", t); textEmpty.setText(R.string.error_network); Toast.makeText(this, R.string.no_answer, Toast.LENGTH_LONG).show(); }
private void showNotes(List<Note> notes) { notesContainer.removeAllViews(); notesAdded = 0; for (Note note : notes) { addNote(note); } textEmpty.setText(R.string.empty); updateCount(); }
private void updateCount() { int count = notesContainer.getChildCount(); textCount.setText(String.valueOf(count)); textEmpty.setVisibility(count == 0 ? View.VISIBLE : View.GONE); }
private void addNote(Note note) { View card = LayoutInflater.from(this).inflate(R.layout.item_note, notesContainer, false); TextView cardTitle = card.findViewById(R.id.textNoteTitle); TextView cardBody = card.findViewById(R.id.textNoteBody); cardTitle.setText(note.title); cardBody.setText(note.description); cardBody.setVisibility(note.description.isEmpty() ? View.GONE : View.VISIBLE); int background = NOTE_BACKGROUNDS[notesAdded % NOTE_BACKGROUNDS.length]; card.setBackgroundResource(background); notesAdded++;
card.setOnClickListener(v -> openNote(note.title, note.description, background)); card.setOnLongClickListener(v -> { notesContainer.removeView(card); updateCount(); Toast.makeText(this, R.string.note_deleted, Toast.LENGTH_SHORT).show(); return true; });
notesContainer.addView(card, 0); }
private void addNoteFromComposer() { String title = editTitle.getText().toString().trim(); String body = editBody.getText().toString().trim(); if (title.isEmpty()) { textError.setVisibility(View.VISIBLE); return; } textError.setVisibility(View.GONE); NoteInput input = new NoteInput(title, body); NotesApi.SERVER.createNote(input).enqueue(new Callback<Note>() { @Override public void onResponse(Call<Note> call, Response<Note> response) { if (response.isSuccessful()) { addNote(response.body()); updateCount(); editTitle.setText(""); editBody.setText(""); Toast.makeText(MainActivity.this, R.string.note_added, Toast.LENGTH_SHORT).show(); } else { showRefused(response.code()); } }
@Override public void onFailure(Call<Note> call, Throwable t) { showNoAnswer(t); } }); }
private void updateForm() { int length = editBody.length(); textCounter.setText(getString(R.string.counter, length)); int colour = length >= 120 ? R.color.error : R.color.muted; textCounter.setTextColor(getColor(colour)); if (editTitle.length() > 0) { textError.setVisibility(View.GONE); } }
public void onClearClicked(View view) { editTitle.setText(""); editBody.setText(""); }
private void openNote(String title, String body, int background) { Intent intent = new Intent(this, NoteActivity.class); intent.putExtra(NoteActivity.EXTRA_TITLE, title); intent.putExtra(NoteActivity.EXTRA_BODY, body); intent.putExtra(NoteActivity.EXTRA_BACKGROUND, background); startActivity(intent); }
@Override protected void onStart() { super.onStart(); Log.d(TAG, "Main onStart"); }
@Override protected void onResume() { super.onResume(); Log.d(TAG, "Main onResume"); loadNotes(); }
@Override protected void onPause() { super.onPause(); Log.d(TAG, "Main onPause"); }
@Override protected void onStop() { super.onStop(); Log.d(TAG, "Main onStop"); }
@Override protected void onRestart() { super.onRestart(); Log.d(TAG, "Main onRestart"); }
@Override protected void onDestroy() { super.onDestroy(); Log.d(TAG, "Main onDestroy"); }}

Step 5 of 6

Delete: now you write it

20 min

Goal Make a long press delete the note on the server. This time, you write the code.

  • Java MainActivity.java
  • Emulator
  1. Your method private void deleteNote(Note note, View card), right after addNote().

    1. Your model is addNoteFromComposer(): a request, enqueue, a Callback with its two methods.
    2. The request is NotesApi.SERVER.deleteNote(note.id).
    3. DELETE’s answer is empty: the type is Void, where the POST says Note.
    4. If the server says yes: the long press’s three lines come here (remove the card, update the count, the Toast).
    5. If it refuses, or if there is no answer: as in the POST.
  2. The long press calls your method.

    1. In addNote(), the long press keeps its return true;. Its three other lines become one call to deleteNote.
  3. A note deleted for good.

    1. From now on, a long press deletes the note for everybody: long-press only your own notes.
    2. Click ▶ Run 'app' (↻ Rerun if the app is running).
    3. On the phone, add a note named Delete me, with your first name after it.
    4. Press the mouse button on its card and keep it down: the card goes.
    5. Turn the phone, as in step 10.4: the note does not come back.

You should see The card goes, and a Toast says “Note deleted”.

The Toast Note deleted, with the app’s icon, at real size.
The Toast, at real size

Done I see “Note deleted”, and the note does not come back when I turn the phone.

Stuck? 2 symptoms · the file
  • The Toast line is underlined in red. Hover over it: Cannot resolve method 'makeText(Callback<Void>, int, int)' Inside the Callback, this is the Callback. Write MainActivity.this.
  • A Toast says “The server answered 404” Another phone deleted this note first: the server no longer has it. Turn the phone to load the list again.
MainActivity.java, in deleteNote() Editor · centreFull size
The editor in deleteNote(): the line Toast.makeText(this, R.string.note_deleted, Toast.LENGTH_SHORT).show() has its brackets underlined in red, and a tooltip says Cannot resolve method makeText(Callback<Void>, int, int).
  1. Cannot resolve method 'makeText(Callback<Void>, int, int)': the first word in the brackets, this, is the Callback here, not the screen.

Behind? The files at the end of this step

kotlin+java › com.yourname.notes › MainActivity.javaReplace the whole file
package com.yourname.notes;
import android.content.Intent;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.List;
import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Lifecycle"; private static final int[] NOTE_BACKGROUNDS = { R.drawable.bg_note_butter, R.drawable.bg_note_mint, R.drawable.bg_note_lavender, R.drawable.bg_note_peach };
private TextView textCount; private TextView textEmpty; private LinearLayout notesContainer; private int notesAdded = 0;
private EditText editTitle; private EditText editBody; private TextView textError; private TextView textCounter;
private final TextWatcher formWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
@Override public void onTextChanged(CharSequence s, int start, int before, int count) { }
@Override public void afterTextChanged(Editable s) { updateForm(); } };
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d(TAG, "Main onCreate");
textCount = findViewById(R.id.textCount); textEmpty = findViewById(R.id.textEmpty); notesContainer = findViewById(R.id.notesContainer);
textEmpty.setOnClickListener(v -> loadNotes());
editTitle = findViewById(R.id.editTitle); editBody = findViewById(R.id.editBody); textError = findViewById(R.id.textError); textCounter = findViewById(R.id.textCounter);
Button buttonAdd = findViewById(R.id.buttonAdd); buttonAdd.setOnClickListener(v -> addNoteFromComposer());
editTitle.addTextChangedListener(formWatcher); editBody.addTextChangedListener(formWatcher); }
private void loadNotes() { textEmpty.setText(R.string.loading); updateCount(); NotesApi.SERVER.getNotes().enqueue(new Callback<List<Note>>() { @Override public void onResponse(Call<List<Note>> call, Response<List<Note>> response) { if (response.isSuccessful()) { showNotes(response.body()); } else { showRefused(response.code()); } }
@Override public void onFailure(Call<List<Note>> call, Throwable t) { showNoAnswer(t); } }); }
private void showRefused(int code) { Toast.makeText(this, getString(R.string.server_refused, code), Toast.LENGTH_LONG).show(); }
private void showNoAnswer(Throwable t) { Log.e(TAG, "No answer from the server", t); textEmpty.setText(R.string.error_network); Toast.makeText(this, R.string.no_answer, Toast.LENGTH_LONG).show(); }
private void showNotes(List<Note> notes) { notesContainer.removeAllViews(); notesAdded = 0; for (Note note : notes) { addNote(note); } textEmpty.setText(R.string.empty); updateCount(); }
private void updateCount() { int count = notesContainer.getChildCount(); textCount.setText(String.valueOf(count)); textEmpty.setVisibility(count == 0 ? View.VISIBLE : View.GONE); }
private void addNote(Note note) { View card = LayoutInflater.from(this).inflate(R.layout.item_note, notesContainer, false); TextView cardTitle = card.findViewById(R.id.textNoteTitle); TextView cardBody = card.findViewById(R.id.textNoteBody); cardTitle.setText(note.title); cardBody.setText(note.description); cardBody.setVisibility(note.description.isEmpty() ? View.GONE : View.VISIBLE); int background = NOTE_BACKGROUNDS[notesAdded % NOTE_BACKGROUNDS.length]; card.setBackgroundResource(background); notesAdded++;
card.setOnClickListener(v -> openNote(note.title, note.description, background)); card.setOnLongClickListener(v -> { deleteNote(note, card); return true; });
notesContainer.addView(card, 0); }
private void deleteNote(Note note, View card) { NotesApi.SERVER.deleteNote(note.id).enqueue(new Callback<Void>() { @Override public void onResponse(Call<Void> call, Response<Void> response) { if (response.isSuccessful()) { notesContainer.removeView(card); updateCount(); Toast.makeText(MainActivity.this, R.string.note_deleted, Toast.LENGTH_SHORT).show(); } else { showRefused(response.code()); } }
@Override public void onFailure(Call<Void> call, Throwable t) { showNoAnswer(t); } }); }
private void addNoteFromComposer() { String title = editTitle.getText().toString().trim(); String body = editBody.getText().toString().trim(); if (title.isEmpty()) { textError.setVisibility(View.VISIBLE); return; } textError.setVisibility(View.GONE); NoteInput input = new NoteInput(title, body); NotesApi.SERVER.createNote(input).enqueue(new Callback<Note>() { @Override public void onResponse(Call<Note> call, Response<Note> response) { if (response.isSuccessful()) { addNote(response.body()); updateCount(); editTitle.setText(""); editBody.setText(""); Toast.makeText(MainActivity.this, R.string.note_added, Toast.LENGTH_SHORT).show(); } else { showRefused(response.code()); } }
@Override public void onFailure(Call<Note> call, Throwable t) { showNoAnswer(t); } }); }
private void updateForm() { int length = editBody.length(); textCounter.setText(getString(R.string.counter, length)); int colour = length >= 120 ? R.color.error : R.color.muted; textCounter.setTextColor(getColor(colour)); if (editTitle.length() > 0) { textError.setVisibility(View.GONE); } }
public void onClearClicked(View view) { editTitle.setText(""); editBody.setText(""); }
private void openNote(String title, String body, int background) { Intent intent = new Intent(this, NoteActivity.class); intent.putExtra(NoteActivity.EXTRA_TITLE, title); intent.putExtra(NoteActivity.EXTRA_BODY, body); intent.putExtra(NoteActivity.EXTRA_BACKGROUND, background); startActivity(intent); }
@Override protected void onStart() { super.onStart(); Log.d(TAG, "Main onStart"); }
@Override protected void onResume() { super.onResume(); Log.d(TAG, "Main onResume"); loadNotes(); }
@Override protected void onPause() { super.onPause(); Log.d(TAG, "Main onPause"); }
@Override protected void onStop() { super.onStop(); Log.d(TAG, "Main onStop"); }
@Override protected void onRestart() { super.onRestart(); Log.d(TAG, "Main onRestart"); }
@Override protected void onDestroy() { super.onDestroy(); Log.d(TAG, "Main onDestroy"); }}
See the answer

One way to write it; yours may differ.

kotlin+java › com.yourname.notes › MainActivity.javaRead only
package com.yourname.notes;
import android.content.Intent;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.List;
import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Lifecycle"; private static final int[] NOTE_BACKGROUNDS = { R.drawable.bg_note_butter, R.drawable.bg_note_mint, R.drawable.bg_note_lavender, R.drawable.bg_note_peach };
private TextView textCount; private TextView textEmpty; private LinearLayout notesContainer; private int notesAdded = 0;
private EditText editTitle; private EditText editBody; private TextView textError; private TextView textCounter;
private final TextWatcher formWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
@Override public void onTextChanged(CharSequence s, int start, int before, int count) { }
@Override public void afterTextChanged(Editable s) { updateForm(); } };
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d(TAG, "Main onCreate");
textCount = findViewById(R.id.textCount); textEmpty = findViewById(R.id.textEmpty); notesContainer = findViewById(R.id.notesContainer);
textEmpty.setOnClickListener(v -> loadNotes());
editTitle = findViewById(R.id.editTitle); editBody = findViewById(R.id.editBody); textError = findViewById(R.id.textError); textCounter = findViewById(R.id.textCounter);
Button buttonAdd = findViewById(R.id.buttonAdd); buttonAdd.setOnClickListener(v -> addNoteFromComposer());
editTitle.addTextChangedListener(formWatcher); editBody.addTextChangedListener(formWatcher); }
private void loadNotes() { textEmpty.setText(R.string.loading); updateCount(); NotesApi.SERVER.getNotes().enqueue(new Callback<List<Note>>() { @Override public void onResponse(Call<List<Note>> call, Response<List<Note>> response) { if (response.isSuccessful()) { showNotes(response.body()); } else { showRefused(response.code()); } }
@Override public void onFailure(Call<List<Note>> call, Throwable t) { showNoAnswer(t); } }); }
private void showRefused(int code) { Toast.makeText(this, getString(R.string.server_refused, code), Toast.LENGTH_LONG).show(); }
private void showNoAnswer(Throwable t) { Log.e(TAG, "No answer from the server", t); textEmpty.setText(R.string.error_network); Toast.makeText(this, R.string.no_answer, Toast.LENGTH_LONG).show(); }
private void showNotes(List<Note> notes) { notesContainer.removeAllViews(); notesAdded = 0; for (Note note : notes) { addNote(note); } textEmpty.setText(R.string.empty); updateCount(); }
private void updateCount() { int count = notesContainer.getChildCount(); textCount.setText(String.valueOf(count)); textEmpty.setVisibility(count == 0 ? View.VISIBLE : View.GONE); }
private void addNote(Note note) { View card = LayoutInflater.from(this).inflate(R.layout.item_note, notesContainer, false); TextView cardTitle = card.findViewById(R.id.textNoteTitle); TextView cardBody = card.findViewById(R.id.textNoteBody); cardTitle.setText(note.title); cardBody.setText(note.description); cardBody.setVisibility(note.description.isEmpty() ? View.GONE : View.VISIBLE); int background = NOTE_BACKGROUNDS[notesAdded % NOTE_BACKGROUNDS.length]; card.setBackgroundResource(background); notesAdded++;
card.setOnClickListener(v -> openNote(note.title, note.description, background)); card.setOnLongClickListener(v -> { deleteNote(note, card); return true; });
notesContainer.addView(card, 0); }
private void deleteNote(Note note, View card) { NotesApi.SERVER.deleteNote(note.id).enqueue(new Callback<Void>() { @Override public void onResponse(Call<Void> call, Response<Void> response) { if (response.isSuccessful()) { notesContainer.removeView(card); updateCount(); Toast.makeText(MainActivity.this, R.string.note_deleted, Toast.LENGTH_SHORT).show(); } else { showRefused(response.code()); } }
@Override public void onFailure(Call<Void> call, Throwable t) { showNoAnswer(t); } }); }
private void addNoteFromComposer() { String title = editTitle.getText().toString().trim(); String body = editBody.getText().toString().trim(); if (title.isEmpty()) { textError.setVisibility(View.VISIBLE); return; } textError.setVisibility(View.GONE); NoteInput input = new NoteInput(title, body); NotesApi.SERVER.createNote(input).enqueue(new Callback<Note>() { @Override public void onResponse(Call<Note> call, Response<Note> response) { if (response.isSuccessful()) { addNote(response.body()); updateCount(); editTitle.setText(""); editBody.setText(""); Toast.makeText(MainActivity.this, R.string.note_added, Toast.LENGTH_SHORT).show(); } else { showRefused(response.code()); } }
@Override public void onFailure(Call<Note> call, Throwable t) { showNoAnswer(t); } }); }
private void updateForm() { int length = editBody.length(); textCounter.setText(getString(R.string.counter, length)); int colour = length >= 120 ? R.color.error : R.color.muted; textCounter.setTextColor(getColor(colour)); if (editTitle.length() > 0) { textError.setVisibility(View.GONE); } }
public void onClearClicked(View view) { editTitle.setText(""); editBody.setText(""); }
private void openNote(String title, String body, int background) { Intent intent = new Intent(this, NoteActivity.class); intent.putExtra(NoteActivity.EXTRA_TITLE, title); intent.putExtra(NoteActivity.EXTRA_BODY, body); intent.putExtra(NoteActivity.EXTRA_BACKGROUND, background); startActivity(intent); }
@Override protected void onStart() { super.onStart(); Log.d(TAG, "Main onStart"); }
@Override protected void onResume() { super.onResume(); Log.d(TAG, "Main onResume"); loadNotes(); }
@Override protected void onPause() { super.onPause(); Log.d(TAG, "Main onPause"); }
@Override protected void onStop() { super.onStop(); Log.d(TAG, "Main onStop"); }
@Override protected void onRestart() { super.onRestart(); Log.d(TAG, "Main onRestart"); }
@Override protected void onDestroy() { super.onDestroy(); Log.d(TAG, "Main onDestroy"); }}

Step 6 of 6

Edit: make the note page save

15 min

Goal Make the note page editable, with a Save button that sends a PUT.

  • Resources res › values › strings.xml
  • Layout res › layout › activity_note.xml
  • Java NoteActivity.java · MainActivity.java
  • Emulator
  1. Paste Two strings, in strings.xml.

    1. Beside After line 22, below, click Copy 2 lines.
    2. In strings.xml, click at the end of line 22, press Enter, then Ctrl+V.
    res › values › strings.xmlAdd the marked lines
    <resources>    <string name="app_name">Notes</string>    <string name="logo_description">Notes logo</string>    <string name="count_start">0</string>    <string name="title_hint">Title</string>    <string name="body_hint">Write something…</string>    <string name="error_no_title">Give your note a title first.</string>    <string name="counter_start">0 / 140</string>    <string name="counter">%1$d / 140</string>    <string name="clear">Clear</string>    <string name="add">Add</string>    <string name="your_notes">YOUR NOTES</string>    <string name="list_hint">Tap to open · hold to delete</string>    <string name="empty">No notes yet.\nWrite your first one above.</string>    <string name="note_added">Note added</string>    <string name="note_deleted">Note deleted</string>    <string name="note_kicker">NOTE</string>    <string name="back_to_notes">Back to notes</string>    <string name="share">Share</string>    <string name="loading">Asking the server…</string>    <string name="server_refused">The server answered %1$d</string>    <string name="no_answer">No answer from the server.</string>    <string name="save">Save</string>    <string name="note_saved">Note saved</string>    <string name="error_network">No answer from the server.\nTap here to try again.</string></resources>
  2. Paste The layout: two text fields, and a Save button.

    1. Open res › layout › activity_note.xml, in Code or Split.
    2. Replace the whole file, as in step 10.3.
    res › layout › activity_note.xmlReplace the whole file
    <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:fitsSystemWindows="true"    tools:context=".NoteActivity">
    <LinearLayout android:id="@+id/noteSheet" android:layout_width="0dp" android:layout_height="0dp" android:layout_margin="16dp" android:background="@drawable/bg_note_butter" android:orientation="vertical" android:padding="24dp" app:layout_constraintBottom_toTopOf="@id/buttonSave" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent">
    <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:letterSpacing="0.1" android:text="@string/note_kicker" android:textColor="@color/muted" android:textSize="12sp" android:textStyle="bold" />
    <EditText android:id="@+id/textTitle" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:background="@android:color/transparent" android:fontFamily="sans-serif-black" android:hint="@string/title_hint" android:importantForAutofill="no" android:inputType="textCapSentences" android:textColor="@color/ink" android:textSize="24sp" tools:text="Ideas for the app" />
    <EditText android:id="@+id/textBody" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="12dp" android:background="@android:color/transparent" android:gravity="top" android:hint="@string/body_hint" android:importantForAutofill="no" android:inputType="textMultiLine|textCapSentences" android:maxLength="140" android:lineSpacingMultiplier="1.25" android:textColor="@color/ink" android:textSize="18sp" tools:text="Pastel cards, a Share button, maybe a photo one day." /> </LinearLayout>
    <Button android:id="@+id/buttonSave" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="16dp" android:layout_marginBottom="16dp" android:text="@string/save" app:cornerRadius="12dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" />
    <Button android:id="@+id/buttonShare" style="@style/Widget.Material3.Button.OutlinedButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="8dp" android:text="@string/share" app:cornerRadius="12dp" app:layout_constraintBaseline_toBaselineOf="@id/buttonSave" app:layout_constraintEnd_toStartOf="@id/buttonSave" />
    <Button android:id="@+id/buttonBack" style="@style/Widget.Material3.Button.OutlinedButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="8dp" android:text="@string/back_to_notes" app:cornerRadius="12dp" app:layout_constraintBaseline_toBaselineOf="@id/buttonShare" app:layout_constraintEnd_toStartOf="@id/buttonShare" />
    </androidx.constraintlayout.widget.ConstraintLayout>

    EditText replaces TextView, twice. buttonSave is new.

  3. Paste The class: save() sends a PUT.

    1. Replace NoteActivity.java the same way.
    kotlin+java › com.yourname.notes › NoteActivity.javaReplace the whole file
    package com.yourname.notes;
    import android.content.Intent;import android.os.Bundle;import android.util.Log;import android.widget.EditText;import android.widget.Toast;
    import androidx.appcompat.app.AppCompatActivity;
    import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;
    public class NoteActivity extends AppCompatActivity {
    public static final String EXTRA_ID = "com.yourname.notes.EXTRA_ID"; public static final String EXTRA_TITLE = "com.yourname.notes.EXTRA_TITLE"; public static final String EXTRA_BODY = "com.yourname.notes.EXTRA_BODY"; public static final String EXTRA_BACKGROUND = "com.yourname.notes.EXTRA_BACKGROUND"; private static final String TAG = "Lifecycle";
    private EditText textTitle; private EditText textBody;
    @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_note); Log.d(TAG, "Note onCreate");
    int id = getIntent().getIntExtra(EXTRA_ID, 0); String title = getIntent().getStringExtra(EXTRA_TITLE); String body = getIntent().getStringExtra(EXTRA_BODY); int background = getIntent().getIntExtra(EXTRA_BACKGROUND, R.drawable.bg_note_butter);
    textTitle = findViewById(R.id.textTitle); textBody = findViewById(R.id.textBody); textTitle.setText(title); textBody.setText(body); findViewById(R.id.noteSheet).setBackgroundResource(background);
    findViewById(R.id.buttonBack).setOnClickListener(v -> finish()); findViewById(R.id.buttonShare).setOnClickListener(v -> share()); findViewById(R.id.buttonSave).setOnClickListener(v -> save(id)); }
    private void save(int id) { String title = textTitle.getText().toString().trim(); String body = textBody.getText().toString().trim(); NoteInput input = new NoteInput(title, body); NotesApi.SERVER.updateNote(id, input).enqueue(new Callback<Note>() { @Override public void onResponse(Call<Note> call, Response<Note> response) { if (response.isSuccessful()) { Toast.makeText(NoteActivity.this, R.string.note_saved, Toast.LENGTH_SHORT).show(); finish(); } else { String message = getString(R.string.server_refused, response.code()); Toast.makeText(NoteActivity.this, message, Toast.LENGTH_LONG).show(); } }
    @Override public void onFailure(Call<Note> call, Throwable t) { Log.e(TAG, "No answer from the server", t); Toast.makeText(NoteActivity.this, R.string.no_answer, Toast.LENGTH_LONG).show(); } }); }
    private void share() { String title = textTitle.getText().toString(); String body = textBody.getText().toString(); Intent send = new Intent(Intent.ACTION_SEND); send.setType("text/plain"); send.putExtra(Intent.EXTRA_TEXT, title + "\n" + body); startActivity(Intent.createChooser(send, null)); }
    @Override protected void onDestroy() { super.onDestroy(); Log.d(TAG, "Note onDestroy"); }}

    save() sends the id and the new texts; finish() closes the page.

  4. Type openNote() sends the note’s id.

    1. In addNote(), replace openNote(note.title, note.description, background) with openNote(note, background).
    2. In openNote(), make the 4 marked lines match the panel: the EXTRA_ID line is new. Your line numbers may differ.
    kotlin+java › com.yourname.notes › MainActivity.javaAdd the marked lines
    package com.yourname.notes;
    import android.content.Intent;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast;
    import androidx.appcompat.app.AppCompatActivity;
    import java.util.List;
    import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;
    public class MainActivity extends AppCompatActivity {
    private static final String TAG = "Lifecycle"; private static final int[] NOTE_BACKGROUNDS = { R.drawable.bg_note_butter, R.drawable.bg_note_mint, R.drawable.bg_note_lavender, R.drawable.bg_note_peach };
    private TextView textCount; private TextView textEmpty; private LinearLayout notesContainer; private int notesAdded = 0;
    private EditText editTitle; private EditText editBody; private TextView textError; private TextView textCounter;
    private final TextWatcher formWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
    @Override public void onTextChanged(CharSequence s, int start, int before, int count) { }
    @Override public void afterTextChanged(Editable s) { updateForm(); } };
    @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d(TAG, "Main onCreate");
    textCount = findViewById(R.id.textCount); textEmpty = findViewById(R.id.textEmpty); notesContainer = findViewById(R.id.notesContainer);
    textEmpty.setOnClickListener(v -> loadNotes());
    editTitle = findViewById(R.id.editTitle); editBody = findViewById(R.id.editBody); textError = findViewById(R.id.textError); textCounter = findViewById(R.id.textCounter);
    Button buttonAdd = findViewById(R.id.buttonAdd); buttonAdd.setOnClickListener(v -> addNoteFromComposer());
    editTitle.addTextChangedListener(formWatcher); editBody.addTextChangedListener(formWatcher); }
    private void loadNotes() { textEmpty.setText(R.string.loading); updateCount(); NotesApi.SERVER.getNotes().enqueue(new Callback<List<Note>>() { @Override public void onResponse(Call<List<Note>> call, Response<List<Note>> response) { if (response.isSuccessful()) { showNotes(response.body()); } else { showRefused(response.code()); } }
    @Override public void onFailure(Call<List<Note>> call, Throwable t) { showNoAnswer(t); } }); }
    private void showRefused(int code) { Toast.makeText(this, getString(R.string.server_refused, code), Toast.LENGTH_LONG).show(); }
    private void showNoAnswer(Throwable t) { Log.e(TAG, "No answer from the server", t); textEmpty.setText(R.string.error_network); Toast.makeText(this, R.string.no_answer, Toast.LENGTH_LONG).show(); }
    private void showNotes(List<Note> notes) { notesContainer.removeAllViews(); notesAdded = 0; for (Note note : notes) { addNote(note); } textEmpty.setText(R.string.empty); updateCount(); }
    private void updateCount() { int count = notesContainer.getChildCount(); textCount.setText(String.valueOf(count)); textEmpty.setVisibility(count == 0 ? View.VISIBLE : View.GONE); }
    private void addNote(Note note) { View card = LayoutInflater.from(this).inflate(R.layout.item_note, notesContainer, false); TextView cardTitle = card.findViewById(R.id.textNoteTitle); TextView cardBody = card.findViewById(R.id.textNoteBody); cardTitle.setText(note.title); cardBody.setText(note.description); cardBody.setVisibility(note.description.isEmpty() ? View.GONE : View.VISIBLE); int background = NOTE_BACKGROUNDS[notesAdded % NOTE_BACKGROUNDS.length]; card.setBackgroundResource(background); notesAdded++;
    card.setOnClickListener(v -> openNote(note, background)); card.setOnLongClickListener(v -> { deleteNote(note, card); return true; });
    notesContainer.addView(card, 0); }
    private void deleteNote(Note note, View card) { NotesApi.SERVER.deleteNote(note.id).enqueue(new Callback<Void>() { @Override public void onResponse(Call<Void> call, Response<Void> response) { if (response.isSuccessful()) { notesContainer.removeView(card); updateCount(); Toast.makeText(MainActivity.this, R.string.note_deleted, Toast.LENGTH_SHORT).show(); } else { showRefused(response.code()); } }
    @Override public void onFailure(Call<Void> call, Throwable t) { showNoAnswer(t); } }); }
    private void addNoteFromComposer() { String title = editTitle.getText().toString().trim(); String body = editBody.getText().toString().trim(); if (title.isEmpty()) { textError.setVisibility(View.VISIBLE); return; } textError.setVisibility(View.GONE); NoteInput input = new NoteInput(title, body); NotesApi.SERVER.createNote(input).enqueue(new Callback<Note>() { @Override public void onResponse(Call<Note> call, Response<Note> response) { if (response.isSuccessful()) { addNote(response.body()); updateCount(); editTitle.setText(""); editBody.setText(""); Toast.makeText(MainActivity.this, R.string.note_added, Toast.LENGTH_SHORT).show(); } else { showRefused(response.code()); } }
    @Override public void onFailure(Call<Note> call, Throwable t) { showNoAnswer(t); } }); }
    private void updateForm() { int length = editBody.length(); textCounter.setText(getString(R.string.counter, length)); int colour = length >= 120 ? R.color.error : R.color.muted; textCounter.setTextColor(getColor(colour)); if (editTitle.length() > 0) { textError.setVisibility(View.GONE); } }
    public void onClearClicked(View view) { editTitle.setText(""); editBody.setText(""); }
    private void openNote(Note note, int background) { Intent intent = new Intent(this, NoteActivity.class); intent.putExtra(NoteActivity.EXTRA_ID, note.id); intent.putExtra(NoteActivity.EXTRA_TITLE, note.title); intent.putExtra(NoteActivity.EXTRA_BODY, note.description); intent.putExtra(NoteActivity.EXTRA_BACKGROUND, background); startActivity(intent); }
    @Override protected void onStart() { super.onStart(); Log.d(TAG, "Main onStart"); }
    @Override protected void onResume() { super.onResume(); Log.d(TAG, "Main onResume"); loadNotes(); }
    @Override protected void onPause() { super.onPause(); Log.d(TAG, "Main onPause"); }
    @Override protected void onStop() { super.onStop(); Log.d(TAG, "Main onStop"); }
    @Override protected void onRestart() { super.onRestart(); Log.d(TAG, "Main onRestart"); }
    @Override protected void onDestroy() { super.onDestroy(); Log.d(TAG, "Main onDestroy"); }}
  5. First, an empty title.

    Predict first

    The note page does not check the title. Empty it and tap Save: what happens?

    Break it

    1. Click ▶ Run 'app' (↻ Rerun if the app is running).
    2. On the phone, tap your Call Yasmine card: you can type in it.
    3. Click at the end of the title, then press Backspace until it is empty.
    4. Close the keyboard with its down arrow, at the bottom left of the phone.
    5. Tap Save.
    What happened

    The page stays, and a Toast says:

    The Toast The server answered 422, over the buttons of the note page, at real size.
    The Toast, at real size

    The server checks the title itself: it refuses an empty one, with the code 422.

  6. Then a real change.

    1. Click in the title, then type Call Yasmine at 6. In class, add your first name again.
    2. Close the keyboard with its down arrow, at the bottom left of the phone.
    3. Tap Save.
The note page before Save: the title reads Call Yasmine at 6, the text Before 6 pm., and three buttons at the bottom, Back to notes, Share and Save.
Before Save
Save
After Save: the notes list again, its first card reads Call Yasmine at 6, and the pill says 4.
After

You should see A Toast, “Note saved”, then the list with the new title.

Done I see “The server answered 422”, then my new title.

Stuck? 1 symptom · the files
  • A Toast says “The server answered 404” when I tap Save Someone deleted your note while it was open. Tap Back to notes, add it again, then edit it.

Behind? Actions a, b and c hold three of the files. Here is the fourth, MainActivity.java:

kotlin+java › com.yourname.notes › MainActivity.javaReplace the whole file
package com.yourname.notes;
import android.content.Intent;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.List;
import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Lifecycle"; private static final int[] NOTE_BACKGROUNDS = { R.drawable.bg_note_butter, R.drawable.bg_note_mint, R.drawable.bg_note_lavender, R.drawable.bg_note_peach };
private TextView textCount; private TextView textEmpty; private LinearLayout notesContainer; private int notesAdded = 0;
private EditText editTitle; private EditText editBody; private TextView textError; private TextView textCounter;
private final TextWatcher formWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
@Override public void onTextChanged(CharSequence s, int start, int before, int count) { }
@Override public void afterTextChanged(Editable s) { updateForm(); } };
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d(TAG, "Main onCreate");
textCount = findViewById(R.id.textCount); textEmpty = findViewById(R.id.textEmpty); notesContainer = findViewById(R.id.notesContainer);
textEmpty.setOnClickListener(v -> loadNotes());
editTitle = findViewById(R.id.editTitle); editBody = findViewById(R.id.editBody); textError = findViewById(R.id.textError); textCounter = findViewById(R.id.textCounter);
Button buttonAdd = findViewById(R.id.buttonAdd); buttonAdd.setOnClickListener(v -> addNoteFromComposer());
editTitle.addTextChangedListener(formWatcher); editBody.addTextChangedListener(formWatcher); }
private void loadNotes() { textEmpty.setText(R.string.loading); updateCount(); NotesApi.SERVER.getNotes().enqueue(new Callback<List<Note>>() { @Override public void onResponse(Call<List<Note>> call, Response<List<Note>> response) { if (response.isSuccessful()) { showNotes(response.body()); } else { showRefused(response.code()); } }
@Override public void onFailure(Call<List<Note>> call, Throwable t) { showNoAnswer(t); } }); }
private void showRefused(int code) { Toast.makeText(this, getString(R.string.server_refused, code), Toast.LENGTH_LONG).show(); }
private void showNoAnswer(Throwable t) { Log.e(TAG, "No answer from the server", t); textEmpty.setText(R.string.error_network); Toast.makeText(this, R.string.no_answer, Toast.LENGTH_LONG).show(); }
private void showNotes(List<Note> notes) { notesContainer.removeAllViews(); notesAdded = 0; for (Note note : notes) { addNote(note); } textEmpty.setText(R.string.empty); updateCount(); }
private void updateCount() { int count = notesContainer.getChildCount(); textCount.setText(String.valueOf(count)); textEmpty.setVisibility(count == 0 ? View.VISIBLE : View.GONE); }
private void addNote(Note note) { View card = LayoutInflater.from(this).inflate(R.layout.item_note, notesContainer, false); TextView cardTitle = card.findViewById(R.id.textNoteTitle); TextView cardBody = card.findViewById(R.id.textNoteBody); cardTitle.setText(note.title); cardBody.setText(note.description); cardBody.setVisibility(note.description.isEmpty() ? View.GONE : View.VISIBLE); int background = NOTE_BACKGROUNDS[notesAdded % NOTE_BACKGROUNDS.length]; card.setBackgroundResource(background); notesAdded++;
card.setOnClickListener(v -> openNote(note, background)); card.setOnLongClickListener(v -> { deleteNote(note, card); return true; });
notesContainer.addView(card, 0); }
private void deleteNote(Note note, View card) { NotesApi.SERVER.deleteNote(note.id).enqueue(new Callback<Void>() { @Override public void onResponse(Call<Void> call, Response<Void> response) { if (response.isSuccessful()) { notesContainer.removeView(card); updateCount(); Toast.makeText(MainActivity.this, R.string.note_deleted, Toast.LENGTH_SHORT).show(); } else { showRefused(response.code()); } }
@Override public void onFailure(Call<Void> call, Throwable t) { showNoAnswer(t); } }); }
private void addNoteFromComposer() { String title = editTitle.getText().toString().trim(); String body = editBody.getText().toString().trim(); if (title.isEmpty()) { textError.setVisibility(View.VISIBLE); return; } textError.setVisibility(View.GONE); NoteInput input = new NoteInput(title, body); NotesApi.SERVER.createNote(input).enqueue(new Callback<Note>() { @Override public void onResponse(Call<Note> call, Response<Note> response) { if (response.isSuccessful()) { addNote(response.body()); updateCount(); editTitle.setText(""); editBody.setText(""); Toast.makeText(MainActivity.this, R.string.note_added, Toast.LENGTH_SHORT).show(); } else { showRefused(response.code()); } }
@Override public void onFailure(Call<Note> call, Throwable t) { showNoAnswer(t); } }); }
private void updateForm() { int length = editBody.length(); textCounter.setText(getString(R.string.counter, length)); int colour = length >= 120 ? R.color.error : R.color.muted; textCounter.setTextColor(getColor(colour)); if (editTitle.length() > 0) { textError.setVisibility(View.GONE); } }
public void onClearClicked(View view) { editTitle.setText(""); editBody.setText(""); }
private void openNote(Note note, int background) { Intent intent = new Intent(this, NoteActivity.class); intent.putExtra(NoteActivity.EXTRA_ID, note.id); intent.putExtra(NoteActivity.EXTRA_TITLE, note.title); intent.putExtra(NoteActivity.EXTRA_BODY, note.description); intent.putExtra(NoteActivity.EXTRA_BACKGROUND, background); startActivity(intent); }
@Override protected void onStart() { super.onStart(); Log.d(TAG, "Main onStart"); }
@Override protected void onResume() { super.onResume(); Log.d(TAG, "Main onResume"); loadNotes(); }
@Override protected void onPause() { super.onPause(); Log.d(TAG, "Main onPause"); }
@Override protected void onStop() { super.onStop(); Log.d(TAG, "Main onStop"); }
@Override protected void onRestart() { super.onRestart(); Log.d(TAG, "Main onRestart"); }
@Override protected void onDestroy() { super.onDestroy(); Log.d(TAG, "Main onDestroy"); }}

If it doesn’t work

  • The app closes, and Logcat says Permission denied (missing INTERNET permission?) The manifest lacks the permission line of Part 9. Open the box at the top (Part 9 not finished, or a fresh project?), item 4.

Now you If you have time

Adapt the app

  • The date. The server also sends created_at with each note. Show it on the card.
  • A Refresh button. Add a button that calls loadNotes(): your classmates’ new notes show without a rotation.
  • Your own data. Tasks, books: what would change in NotesApi?
See the answer

The date: add public String created_at; to Note. Gson fills an instance variable from the JSON key of the same name: note.created_at then holds a text such as 2026-11-27T13:31:34Z. A key the JSON lacks leaves the variable null: test it before you call a method on it. Then show it, in addNote(): cardTitle.setText(note.title + " · " + note.created_at);

Refresh: a Button in activity_main.xml. In onCreate(), its click listener calls loadNotes(), as textEmpty’s does.

Your own data: the same four methods serve any list. Only the class, Note, and the paths, "notes", change.

End of the part

Recap

Add, Save and the long press now reach the server: your notes survive a rotation, and the whole class sees them. Here anybody can change or delete any note: a real API first asks who you are.

  • read an API in a Retrofit interface: which request each method sends;
  • send GET, POST, PUT and DELETE, and tell a yes, a refusal and no answer apart;
  • say what Retrofit and Gson do for you.
Your app at the end of Lab 1: the class’s shared notes, read from the server, with Call Yasmine at 6 on top and the pill 4.
Your app now

End of Lab 1

Eleven parts, one app: what you can do now

  1. Part 01–2 h, home

    Before class: install and prepare

    I can install Android Studio, start a virtual phone and create my project.

  2. Part 116 min

    Find your way in the project

    I can read the five Gradle values and add a library.

  3. Part 226 min

    Your first screen, piece by piece

    I can write the three pieces of a screen and run it.

  4. Part 342 min (+1 h by hand)

    Place the views with ConstraintLayout

    I can place views that keep their shape on any phone.

  5. Part 435 min

    Make it beautiful: resources

    I can define texts, colours, shapes and the theme once, in res/.

  6. Part 528 min

    From XML to Java: the activity and its life

    I can follow my activity’s life in Logcat.

  7. Part 637 min

    Java takes over the screen

    I can change views from Java and add note cards.

  8. Part 743 min

    The screen answers: events

    I can react to taps, long presses and typing.

  9. Part 835 min

    A second screen: Intents

    I can open a second screen with an Intent, and share a note.

  10. Part 945 min

    The notes come from a server

    I can ask a server for data on another thread, and turn its JSON into objects.

  11. Part 1075 min

    Create, edit, delete: the whole API

    I can read, create, edit and delete notes on a server, with Retrofit.

In class now: questions 7 and 8 of the quick check. Homework: step 10.6 if it is not finished, then “The date”, in “Now you”.

lab1-final.zip zip · 107 KB

The finished project, to compare with yours.