Part 8 not finished, or a fresh project? Start here about 5 min
The project: your own from Part 8, or a fresh one: Part 0, steps 0.3 and 0.4 (about 5 minutes).
Your package name, for the code of this page:
Without JavaScript, the code says com.yourname.notes: replace yourname by the name you chose.
Gradle: in build.gradle.kts (Module :app), check this line;
implementation(works too. Missing? Click Copy 1 line, then in the editor click at the end of line 37,libs.constraintlayout) implementation(. Press Enter, then Ctrl+V, and click Sync Now.libs.material) Gradle Scripts › build.gradle.kts (Module :app)Add the marked linesplugins { 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)}resand manifest: download the pack and open it in Explorer. Drag itsappfolder onto your project folder (C:\Users\<you>\), 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.AndroidStudioProjects\ Notes resand 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 wholeappfolder and deletes your code. In Android Studio, open ViewTool WindowsTerminal: its line must end withNotes %, 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 -xThen, in res › values › themes, delete themes.xml (night) if it is still there.
lab1-part9-res.zip zip · 9.7 KBJava: 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 filepackage 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 filepackage 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"); }}▶. You are ready when the phone shows three cards, and a tap on one opens its page.
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
Goal See what a server answers when you ask it for the notes.
-
The notes, asked for by your browser.
- Click https://bachelor-gl.site/notes: the address opens in a new tab.
- Read what comes back: text, not a page. Then come back to the lab’s tab.
| Request and response | Your 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. |
|---|---|
| GET | The kind of request that only reads. |
| JSON | The 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
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.
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.
runOnUiThreadhands 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
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 JSONArray(json): the text’s[ ], as a list you can count.getJSONObject(i): object number i, one{ }.getString("title"): the value written after the key"title".getIntdoes the same for a number.notes.add(note): one moreNotein 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
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
-
Paste The permission line, in the manifest.
- In Project, open manifests › AndroidManifest.xml.
- In the panel below, click Copy 2 lines.
- Click in line 4, the empty line above
<application, then press Enter. - 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.
-
A new class,
Note, created as in step 8.1.- In Project, right-click the plain kotlin+java › com.yourname.notes, without
(test)or(androidTest). - Choose NewJava Class.
- A New Java Class popup opens: type
Note, then press Enter.
New Java Class A dialogFull size
- New Java Class: type
Note, then press Enter. - Class stays selected: a
Noteis a class.
- In Project, right-click the plain kotlin+java › com.yourname.notes, without
-
Type Its three instance variables, named as the server names them.
- The class opens: click right after the
{ofpublic class Note {, then press Enter. - Completion lists open as you type: keep typing.
- Type the panel’s lines 4 to 6.
kotlin+java › com.yourname.notes › Note.javaNew filepackage 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.
- The class opens: click right after the
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.javasits 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.

- Line 5, the permission: above
<application, with an empty line on each side.
Behind? The files at the end of this step
<?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>package com.yourname.notes;
public class Note { public int id; public String title; public String description;}Step 4 of 5
Write the request
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
-
Paste strings.xml: two new strings, and the 6 seed strings go.
- In Project, open res › values › strings.xml.
- Click Copy the file, on the panel below.
- Click in the code, press Ctrl+A, then Ctrl+V.
MainActivity.javastill 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>loadingshows while the app waits;error_networkif no answer comes. -
Paste MainActivity.java, the whole file: the request of step 9.2.
- Open kotlin+java › com.yourname.notes › MainActivity.java.
- Click Copy the file, on the panel below.
- Click in the code, press Ctrl+A, then Ctrl+V.
kotlin+java › com.yourname.notes › MainActivity.javaReplace the whole filepackage 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()callingloadNotes()in place of the three seed notes. New, lines 91 to 144:loadNotes()(step 9.2),download()(the HTTP chore),parse()(its own section) andshowNotes(). If the network or the JSON fails, thecatchshows the message of action a. -
The server’s notes, on the phone.
- Click ▶ Run 'app' (↻ Rerun if the app is running).
-
The proof: a note added on the server reaches the phone.

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/notesin 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 withhttps), 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 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. Notestays red inMainActivity.javaNote.javais missing, or not in the plain package. Do step 9.3, actions b and c, again.R.string.loadingstays 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
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?
-
Paste Rule 1, broken: the request without its thread.
- In the panel below, click Copy 8 lines.
- In MainActivity.java, click at the end of line 93,
updateCount();. - Hold Shift and click at the end of line 103,
}).start();: the 10 lines of the thread are selected. - Press Enter, then Ctrl+V: the 8 lines take their place.
kotlin+java › com.yourname.notes › MainActivity.javaAdd the marked linespackage 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"); }} -
The app, run with the request on the main thread.
- In Logcat’s query field, delete
tag:Lifecycle: keep onlypackage:mine. - 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(). - In Logcat’s query field, delete
-
The thread, back in place.
- In the editor, press Ctrl+Z until line 94 reads
new Thread(() -> {again.
- In the editor, press Ctrl+Z until line 94 reads
-
Rule 2, broken: the cards drawn by the helper thread.
Predict first
The helper thread draws the cards itself: will they show?
- On line 98, delete
runOnUiThread(() ->and the last): the line readsshowNotes(notes);. - 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, inshowNotes(). - On line 98, delete
-
The line, back as it was.
- Press Ctrl+Z until line 98 reads
runOnUiThread(() -> showNotes(notes));again. - Click ▶ Run 'app': the server’s notes are back.
- Press Ctrl+Z until line 98 reads
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. Keeppackage:mineonly. - 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:Lifecyclein its query field, as in step 5.2.
Now you If you have time
Three more things to try
- 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. - On line 33, add
/999999afternotes. Run: what does Logcat say? Then take it away. - Read the date: add
public String created_at;toNoteand one line toparse(); check it withLog.d.
See the answer
org.json.JSONException: No value for body. A key must be the server’s word, letter for letter. It is aJSONException: yourcatchcatches it, so the app stays open and says “No answer from the server.”java.io.FileNotFoundException: https://bachelor-gl.site/notes/999999: the server answered 404, no such note, andHttpURLConnectionturns an error code into anIOException. Part 10 reads the code itself.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.

