Mehdi TmimiMobile DevelopmentMobile

Mobile Development Lab 1 Part 9 · parts 0–10

The notes come from a server

Until now, the three notes were written inside the app. Now they live on a server, and the app asks for them.

Part 8 not finished, or a fresh project? Start here about 5 min
  1. The project: your own from Part 8, 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-part9-res.zip | tar -x

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

    lab1-part9-res.zip zip · 9.7 KB
  5. Java: open MainActivity.java, select all, then paste the first file. Do the same in NoteActivity.java with the second. 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;
    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);
    addNote(getString(R.string.seed_title_1), getString(R.string.seed_body_1)); addNote(getString(R.string.seed_title_2), getString(R.string.seed_body_2)); addNote(getString(R.string.seed_title_3), getString(R.string.seed_body_3)); updateCount();
    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 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"); }}
  6. ▶. You are ready when the phone shows three cards, and a tap on one opens its page.

The emulator at the end of Part 8, at launch: the notes screen with three cards, Exam: the lifecycle, Ideas for the app and Saturday, and the pill 3.
Where you start

Before you start

By the end you can

  • say what a request, a response and JSON are;
  • say why the request runs on another thread, and how its result comes back;
  • read a JSON array, and the code that turns it into objects.
  • Android Studio Project
  • Manifest
  • Resources
  • Java
  • Emulator
  • Logcat

Step 1 of 5

See the server

6 min

Goal See what a server answers when you ask it for the notes.

  1. The notes, asked for by your browser.

    1. Click https://bachelor-gl.site/notes: the address opens in a new tab.
    2. Read what comes back: text, not a page. Then come back to the lab’s tab.
The words of this step
Request and responseYour browser sent a request to the server in HTTP, the web’s rules for asking and answering. The server’s answer, its response, is the text in the tab.
GETThe kind of request that only reads.
JSONThe way that text is written. [ ] holds a list (JSON says an array), { } one object, "title": "Saturday" a key and its value.

One list for everybody who does this lab. Sign your notes with your first name, and change only yours. An empty list answers []: send the first note.

GET https://bachelor-gl.site/notes

The server’s answer, right nowOpen the address in a new tab to read it.

Step 2 of 5

Follow one request, line by line

8 min

Goal Follow the request from the app to the server and back, before you write it.

A thread runs code, one line after the other. Your app starts with one, the main thread: it draws the screen and responds to touch. A JavaScript page has one thread too: when it waited for a server, the page froze.

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"); }}

new Thread: a helper for the slow work

The main thread must never wait. So it starts a second thread, the helper: the lambda is its work, as in step 7.1, and start() launches it.

download(): the request leaves

On the helper thread, download() sends the request GET /notes and waits for the answer: a second, or ten. After ten, it gives up. The screen keeps responding.

String json: the answer is text

The server answers with text written in JSON. download() returns it as one long String. It is not a note yet.

parse(): text in, objects out

parse() reads the text and makes one Note object for each { }, with its id, its title and its description.

runOnUiThread: back to the main thread

Only the main thread may touch the views. runOnUiThread hands it a piece of code to run, a callback as in JavaScript: showNotes() draws one card per note.

The two rules

  • Rule 1. No network on the main thread. It must never wait for a server.
  • Rule 2. No view touched from another thread. runOnUiThread hands the result to the main thread.

JSON: from text to objects

In JavaScript, JSON.parse(text) gave you the objects in one call. Java wants the type of every value: you ask for each one by its key, and copy it into a Note.

The text in json[ { "id": 4, "title": "Saturday", "description": "Football at 10…" },
  { "id": 5, "title": "Ideas for the app", "description": "Pastel cards…" } ]

Line 97, closer: how parse() reads the JSON

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"); }}
  1. new JSONArray(json): the text’s [ ], as a list you can count.
  2. getJSONObject(i): object number i, one { }.
  3. getString("title"): the value written after the key "title". getInt does the same for a number.
  4. notes.add(note): one more Note in the Java list.

Predict

With this text, what does array.length() return? And array.getJSONObject(1).getString("title")?

See the answer

2: two { } between the [ ]. "Ideas for the app": the count starts at 0, as in a Java array.

Step 3 of 5

Ask for the permission, describe a note

7 min

Goal Give the app the right to use the Internet, and a class that holds one note.

  • Manifest manifests › AndroidManifest.xml
  • Java kotlin+java › com.yourname.notes › Note.java
  1. Paste The permission line, in the manifest.

    1. In Project, open manifests › AndroidManifest.xml.
    2. In the panel below, click Copy 2 lines.
    3. Click in line 4, the empty line above <application, then press Enter.
    4. Press Ctrl+V: line 5 appears, with an empty line under it.
    manifests › AndroidManifest.xmlAdd the marked lines
    <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools">
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:allowBackup="true" android:dataExtractionRules="@xml/data_extraction_rules" android:fullBackupContent="@xml/backup_rules" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.Notes"> <activity android:name=".MainActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".NoteActivity" android:exported="false" /> </application>
    </manifest>

    Without this line, Android refuses every request the app sends.

  2. A new class, Note, created as in step 8.1.

    1. In Project, right-click the plain kotlin+java › com.yourname.notes, without (test) or (androidTest).
    2. Choose NewJava Class.
    3. A New Java Class popup opens: type Note, then press Enter.
    New Java Class A dialogFull size
    The small New Java Class popup: Note is typed, Class is selected below; Interface, Enum, Annotation and Exception follow.
    1. New Java Class: type Note, then press Enter.
    2. Class stays selected: a Note is a class.
  3. Type Its three instance variables, named as the server names them.

    1. The class opens: click right after the { of public class Note {, then press Enter.
    2. Completion lists open as you type: keep typing.
    3. Type the panel’s lines 4 to 6.
    kotlin+java › com.yourname.notes › Note.javaNew file
    package com.yourname.notes;
    public class Note { public int id; public String title; public String description;}

    Grey lines: Android Studio writes them. The server sends five values per note; the app keeps these three.

Why Public instance variables and no method: a Note only carries data.

Done I see Note.java with its three instance variables, and no red code.

Stuck? 2 symptoms · the files
  • Note.java sits in a package marked (test) or (androidTest) It is not in the plain package. Drag it onto the plain com.yourname.notes.
  • The permission line is not on line 5 It goes above <application, not inside it. Delete it, then do action a again.
AndroidManifest.xml Editor · centreFull size
The editor on AndroidManifest.xml after the paste: line 5 is uses-permission android.permission.INTERNET, between the empty lines 4 and 6, above application.
  1. Line 5, the permission: above <application, with an empty line on each side.

Behind? The files at the end of this step

manifests › AndroidManifest.xmlReplace the whole file
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET" />
<application android:allowBackup="true" android:dataExtractionRules="@xml/data_extraction_rules" android:fullBackupContent="@xml/backup_rules" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.Notes"> <activity android:name=".MainActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".NoteActivity" android:exported="false" /> </application>
</manifest>
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;}

Step 4 of 5

Write the request

12 min

Goal Make the app ask the server for the notes, and draw one card per note.

  • Resources res › values › strings.xml
  • Java kotlin+java › com.yourname.notes › MainActivity.java
  • Emulator Running Devices
  1. Paste strings.xml: two new strings, and the 6 seed strings go.

    1. In Project, open res › values › strings.xml.
    2. Click Copy the file, on the panel below.
    3. Click in the code, press Ctrl+A, then Ctrl+V.
    4. MainActivity.java still uses the seed strings: it stays red until action b.
    res › values › strings.xmlReplace the whole file
    <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="error_network">No answer from the server.\nTap here to try again.</string></resources>

    loading shows while the app waits; error_network if no answer comes.

  2. Paste MainActivity.java, the whole file: the request of step 9.2.

    1. Open kotlin+java › com.yourname.notes › MainActivity.java.
    2. Click Copy the file, on the panel 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 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"); }}

    Marked: the address, and onCreate() calling loadNotes() in place of the three seed notes. New, lines 91 to 144: loadNotes() (step 9.2), download() (the HTTP chore), parse() (its own section) and showNotes(). If the network or the JSON fails, the catch shows the message of action a.

  3. The server’s notes, on the phone.

    1. Click ▶ Run 'app' (↻ Rerun if the app is running).
  4. The proof: a note added on the server reaches the phone.

    1. On this page, in step 9.1, type a title under “Send a note to the server yourself”, then click Send.
    2. In Running Devices, click Rotate Left, then Rotate Right, as in step 8.6.
    3. Your note is on top of the list: Android created the screen again, and onCreate() asked the server again.
The emulator: the notes screen with three cards that come from the server, Exam: the lifecycle, Ideas for the app and Saturday, and the pill 3.

You should see The server’s notes, one card each. The whole class shares the list: yours may not match the picture. If you work alone at home, it may hold three notes, strangers’ notes, or none.

Done I see the server’s notes, and the note I added in step 9.1.

Stuck? 4 symptoms · the files
  • The screen says “No answer from the server. Tap here to try again.” On the PC, open https://bachelor-gl.site/notes in the browser. No text? The PC is offline, or the room blocks the address: call your teacher. Text? Check the address on line 33 (it starts with https), then tap the message. The same message shows if the server answers with an error, or with text that is not JSON: Logcat’s red line says which.
    The notes screen, at real size: under YOUR NOTES, the message No answer from the server. Tap here to try again.
    The message, at real size
  • The app closes at launch: java.lang.SecurityException: Permission denied (missing INTERNET permission?) The manifest lacks its line 5. Do step 9.3, action a, again.
  • Note stays red in MainActivity.java Note.java is missing, or not in the plain package. Do step 9.3, actions b and c, again.
  • R.string.loading stays red strings.xml lacks the two new strings. Do action a again.

The two panels above hold the files at the end of this step: click Copy the file.

Step 5 of 5

Break it: the two rules

12 min

Goal Break each rule of step 9.2, and read what Android answers.

  • Java kotlin+java › com.yourname.notes › MainActivity.java
  • Emulator
  • Logcat package:mine

Predict first

The request runs on the main thread. What does Android do?

  1. Paste Rule 1, broken: the request without its thread.

    1. In the panel below, click Copy 8 lines.
    2. In MainActivity.java, click at the end of line 93, updateCount();.
    3. Hold Shift and click at the end of line 103, }).start();: the 10 lines of the thread are selected.
    4. Press Enter, then Ctrl+V: the 8 lines take their place.
    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 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(); try { String json = download(NOTES_URL); List<Note> notes = parse(json); showNotes(notes); } catch (IOException | JSONException e) { Log.e(TAG, "loadNotes failed", e); textEmpty.setText(R.string.error_network); } }
    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"); }}
  2. The app, run with the request on the main thread.

    1. In Logcat’s query field, delete tag:Lifecycle: keep only package:mine.
    2. Click ▶ Run 'app' (↻ Rerun if the app is running).
    What happened

    The app closes at launch. Among Logcat’s red lines:

    You should see11-28 15:52:13.535  3579  3579 E AndroidRuntime: FATAL EXCEPTION: main
    11-28 15:52:13.535  3579  3579 E AndroidRuntime: Process: com.yourname.notes, PID: 3579
    11-28 15:52:13.535  3579  3579 E AndroidRuntime: Caused by: android.os.NetworkOnMainThreadException
    11-28 15:52:13.535  3579  3579 E AndroidRuntime: 	at com.yourname.notes.MainActivity.download(MainActivity.java:109)

    Your times and process numbers will differ.

    FATAL EXCEPTION: main: the main thread stopped. NetworkOnMainThreadException: it tried to use the network. The last line names your method, download().

  3. The thread, back in place.

    1. In the editor, press Ctrl+Z until line 94 reads new Thread(() -> { again.
  4. Rule 2, broken: the cards drawn by the helper thread.

    Predict first

    The helper thread draws the cards itself: will they show?

    1. On line 98, delete runOnUiThread(() -> and the last ): the line reads showNotes(notes);.
    2. Click ▶ Run 'app' (↻ Rerun if the app is running).
    What happened

    The app opens, then closes about a second later. Among Logcat’s red lines:

    You should see11-28 15:52:25.103  3635  3684 E AndroidRuntime: FATAL EXCEPTION: Thread-2
    11-28 15:52:25.103  3635  3684 E AndroidRuntime: Process: com.yourname.notes, PID: 3635
    11-28 15:52:25.103  3635  3684 E AndroidRuntime: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. Expected: main Calling: Thread-2
    11-28 15:52:25.103  3635  3684 E AndroidRuntime: 	at com.yourname.notes.MainActivity.showNotes(MainActivity.java:137)

    The message says it: only the thread that created the views may touch them. Expected: main, Calling: Thread-2: your helper thread, in showNotes().

  5. The line, back as it was.

    1. Press Ctrl+Z until line 98 reads runOnUiThread(() -> showNotes(notes)); again.
    2. Click ▶ Run 'app': the server’s notes are back.

Done I see both exceptions in Logcat, then the server’s notes again.

Stuck? 2 symptoms
  • The app closes, but Logcat shows no red line The query still says tag:Lifecycle, which hides Android’s lines. Keep package:mine only.
  • Red code after Ctrl+Z, or the app still closes Paste the whole file again: step 9.4, action b.

No file stays changed in this step: step 9.4 holds the files.

If it doesn’t work

  • Logcat shows no line of yours Type package:mine tag:Lifecycle in its query field, as in step 5.2.

Now you If you have time

Three more things to try

  1. On line 130 of MainActivity.java, write "body" in place of "description". Run the app: what does the screen say, what does Logcat say, and why does the app not close? Then put "description" back.
  2. On line 33, add /999999 after notes. Run: what does Logcat say? Then take it away.
  3. Read the date: add public String created_at; to Note and one line to parse(); check it with Log.d.
See the answer
  1. org.json.JSONException: No value for body. A key must be the server’s word, letter for letter. It is a JSONException: your catch catches it, so the app stays open and says “No answer from the server.”
  2. java.io.FileNotFoundException: https://bachelor-gl.site/notes/999999: the server answered 404, no such note, and HttpURLConnection turns an error code into an IOException. Part 10 reads the code itself.
  3. note.created_at = object.getString("created_at");

End of the part

Recap

The notes live on a server. Your app sends a GET from a helper thread, turns the JSON into Note objects, and draws the cards on the main thread. But Add still lies: add a note on the phone, turn the phone, it is gone. The server never heard of it.

  • say what a request, a response and JSON are;
  • say why the request runs on another thread, and how its result comes back;
  • read a JSON array, and the code that turns it into objects.
Your app at the end of Part 9: the notes screen with the three notes that come from the server, and the pill 3.
Your app now