From 6e7ca0f9df1340383db517f600fa032397cccc20 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 20:03:37 +0000 Subject: [PATCH 1/4] Add a failing test: puzzle screen is blank after recreation When Android recreates SolvePuzzle, onCreate's savedInstanceState != null branch never calls setContentView, so the user gets an empty screen under the action bar. This happens after the app is killed in the background, or after a setting change the manifest doesn't list in configChanges (dark mode, font size, language, split-screen resizing). Robolectric tests, run on the JVM as part of ./gradlew build, cover both cases: a configuration change, and process death (a brand new activity built from the saved state alone). Each test enters one correct country, recreates the activity, and checks that the same puzzle and progress are shown and that the next correct country is still accepted. Both tests fail at this commit. The fix follows in the next commit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HwXCddsMirbBTNqxSqT6iv --- app/build.gradle | 10 + .../SolvePuzzleRecreationTest.java | 186 ++++++++++++++++++ gradle/libs.versions.toml | 4 + 3 files changed, 200 insertions(+) create mode 100644 app/src/test/java/atorch/shortestpaths/SolvePuzzleRecreationTest.java diff --git a/app/build.gradle b/app/build.gradle index 024670a..236b6e5 100755 --- a/app/build.gradle +++ b/app/build.gradle @@ -23,6 +23,13 @@ android { } } + testOptions { + unitTests { + // Robolectric tests read the app's resources (strings, puzzle CSVs) + includeAndroidResources = true + } + } + compileOptions { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 @@ -31,4 +38,7 @@ android { dependencies { implementation libs.androidx.appcompat + + testImplementation libs.junit + testImplementation libs.robolectric } diff --git a/app/src/test/java/atorch/shortestpaths/SolvePuzzleRecreationTest.java b/app/src/test/java/atorch/shortestpaths/SolvePuzzleRecreationTest.java new file mode 100644 index 0000000..da40cdf --- /dev/null +++ b/app/src/test/java/atorch/shortestpaths/SolvePuzzleRecreationTest.java @@ -0,0 +1,186 @@ +package atorch.shortestpaths; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import android.content.Intent; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; +import android.os.Bundle; +import android.view.View; +import android.widget.AutoCompleteTextView; +import android.widget.LinearLayout; +import android.widget.ListAdapter; +import android.widget.TextView; + +import androidx.core.text.HtmlCompat; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.Robolectric; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.RuntimeEnvironment; +import org.robolectric.android.controller.ActivityController; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Android can destroy and recreate SolvePuzzle at any time: when the app is killed in the background + * and the user comes back to it, or when a setting such as dark mode, font size or language changes. + * The user should get back the same puzzle, with the countries they've already entered, and be able + * to carry on solving it. + */ +@RunWith(RobolectricTestRunner.class) +public class SolvePuzzleRecreationTest { + + // Level 1 puzzles need 3 or 4 countries, so there's progress to keep after entering one + private static final int LEVEL = 1; + + private String[] countries; + + @Before + public void fillDatabase() { + // MainActivity fills the puzzle database the first time the app is opened + Robolectric.buildActivity(MainActivity.class).setup(); + countries = RuntimeEnvironment.getApplication().getResources().getStringArray(R.array.countries); + } + + @Test + public void puzzleSurvivesConfigurationChange() { + ActivityController controller = startPuzzle(); + String[] path = shortestPath(controller.get()); + enterCountry(controller.get(), path[0]); + PuzzleScreen before = PuzzleScreen.of(controller.get()); + + controller.recreate(); // e.g. the user switches dark mode on mid-puzzle + + assertSamePuzzleAndProgress(before, controller.get()); + assertCanCarryOn(controller.get(), path, before); + } + + @Test + public void puzzleSurvivesProcessDeath() { + ActivityController controller = startPuzzle(); + String[] path = shortestPath(controller.get()); + enterCountry(controller.get(), path[0]); + PuzzleScreen before = PuzzleScreen.of(controller.get()); + + // The user leaves the app, Android kills it, and later the user comes back: a brand new + // SolvePuzzle is created from nothing but the saved instance state + Bundle savedState = new Bundle(); + controller.pause().stop().saveInstanceState(savedState).destroy(); + ActivityController restored = + Robolectric.buildActivity(SolvePuzzle.class, puzzleIntent()).setup(savedState); + + assertSamePuzzleAndProgress(before, restored.get()); + assertCanCarryOn(restored.get(), path, before); + } + + private ActivityController startPuzzle() { + return Robolectric.buildActivity(SolvePuzzle.class, puzzleIntent()).setup(); + } + + private static Intent puzzleIntent() { + return new Intent(RuntimeEnvironment.getApplication(), SolvePuzzle.class) + .putExtra(MainActivity.LEVEL, LEVEL); + } + + private static void assertSamePuzzleAndProgress(PuzzleScreen before, SolvePuzzle activity) { + AutoCompleteTextView answerField = activity.findViewById(R.id.autocomplete_country); + assertNotNull("After recreation the puzzle screen is blank: there's no answer field", answerField); + assertEquals(View.VISIBLE, answerField.getVisibility()); + assertEquals("Different puzzle after recreation", before.statement, PuzzleScreen.of(activity).statement); + assertEquals("Countries entered so far were lost", before.route, PuzzleScreen.of(activity).route); + } + + /** The next country on the same shortest path is still accepted, and shows up on the route. */ + private static void assertCanCarryOn(SolvePuzzle activity, String[] path, PuzzleScreen before) { + enterCountry(activity, path[1]); + String[] route = PuzzleScreen.of(activity).route; + assertTrue("The second correct country wasn't accepted after recreation: " + Arrays.toString(route), + Arrays.asList(route).contains(path[1])); + assertEquals(before.route.length + 1, route.length); + } + + /** One of the shortest paths for the puzzle on screen, as the countries the user has to enter. */ + private String[] shortestPath(SolvePuzzle activity) { + PuzzleScreen screen = PuzzleScreen.of(activity); + String from = screen.route[0]; + String to = null; + String format = activity.getString(R.string.puzzle_statement_format_string); + for (String country : countries) { + String statement = HtmlCompat.fromHtml(String.format(format, from, country), + HtmlCompat.FROM_HTML_MODE_LEGACY).toString(); + if (statement.equals(screen.statement)) { + to = country; + } + } + assertNotNull("Couldn't work out the destination from: " + screen.statement, to); + + SQLiteDatabase db = new MySQLiteHelper(activity).getReadableDatabase(); + try (Cursor c = db.query(MySQLiteHelper.PATH_TABLE_NAME, new String[]{MySQLiteHelper.COL_PATH}, + MySQLiteHelper.COL_FROM + "=? and " + MySQLiteHelper.COL_TO + "=?", + new String[]{String.valueOf(indexOf(from)), String.valueOf(indexOf(to))}, + null, null, null, "1")) { + assertTrue("No path stored from " + from + " to " + to, c.moveToFirst()); + String[] indices = c.getString(0).split(";"); + String[] path = new String[indices.length]; + for (int i = 0; i < indices.length; i++) { + path[i] = countries[Integer.parseInt(indices[i])]; + } + assertTrue("Expected a level " + LEVEL + " puzzle with at least 3 countries to enter", path.length >= 3); + return path; + } + } + + private int indexOf(String country) { + int index = Arrays.asList(countries).indexOf(country); + assertTrue("Unknown country " + country, index >= 0); + return index; + } + + /** What the user does: pick a country from the answer field's suggestions. */ + private static void enterCountry(SolvePuzzle activity, String country) { + AutoCompleteTextView answerField = activity.findViewById(R.id.autocomplete_country); + assertNotNull("No answer field on screen", answerField); + ListAdapter suggestions = answerField.getAdapter(); + for (int position = 0; position < suggestions.getCount(); position++) { + if (country.equals(suggestions.getItem(position).toString())) { + answerField.getOnItemClickListener().onItemClick(null, answerField, position, position); + return; + } + } + throw new AssertionError(country + " isn't one of the suggestions"); + } + + /** The parts of the puzzle screen that should look the same after recreation. */ + private static final class PuzzleScreen { + final String statement; + final String[] route; // The start, then each country entered so far + + private PuzzleScreen(String statement, String[] route) { + this.statement = statement; + this.route = route; + } + + static PuzzleScreen of(SolvePuzzle activity) { + TextView statement = activity.findViewById(R.id.puzzle_statement); + LinearLayout countriesVisited = activity.findViewById(R.id.countries_visited); + assertNotNull("After recreation the puzzle screen is blank: there's no puzzle statement", statement); + assertNotNull("After recreation the puzzle screen is blank: there's no route", countriesVisited); + // The route is a column of country names with arrows between them + List route = new ArrayList<>(); + for (int i = 0; i < countriesVisited.getChildCount(); i++) { + View child = countriesVisited.getChildAt(i); + if (child instanceof TextView) { + route.add(((TextView) child).getText().toString()); + } + } + return new PuzzleScreen(statement.getText().toString(), route.toArray(new String[0])); + } + } +} diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index a812f7b..0a1912c 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,9 +1,13 @@ [versions] agp = "9.5.0" appcompat = "1.8.0" +junit = "4.13.2" +robolectric = "4.17" [libraries] androidx-appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" } +junit = { group = "junit", name = "junit", version.ref = "junit" } +robolectric = { group = "org.robolectric", name = "robolectric", version.ref = "robolectric" } [plugins] android-application = { id = "com.android.application", version.ref = "agp" } From 4584cfa0921e89613947ec9ad5e5d21cb359128d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 20:07:01 +0000 Subject: [PATCH 2/4] Print full stack traces for failing unit tests CI only keeps the build log, and Gradle's default test output there is one line per failure, which isn't enough to diagnose anything. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HwXCddsMirbBTNqxSqT6iv --- app/build.gradle | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/app/build.gradle b/app/build.gradle index 236b6e5..42d51d7 100755 --- a/app/build.gradle +++ b/app/build.gradle @@ -42,3 +42,11 @@ dependencies { testImplementation libs.junit testImplementation libs.robolectric } + +// Print the full stack trace of failing tests in the build log (CI keeps nothing else) +tasks.withType(Test).configureEach { + testLogging { + events 'failed' + exceptionFormat = 'full' + } +} From 58b299a63e88cd8ebab4fdb65c3b2823fdc577ee Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 20:10:16 +0000 Subject: [PATCH 3/4] Let Robolectric's Android 16 sandbox start on JDK 21 Both tests failed before running any test code. Robolectric's FileDescriptorInterceptor (used by ApplicationSharedMemory.create while setting up the Android 16 environment) calls jdk.internal.access.SharedSecrets through reflection, which JDK 17+ refuses unless that package is exported. Export it, and open java.io for the interceptor's fallback path. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HwXCddsMirbBTNqxSqT6iv --- app/build.gradle | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/app/build.gradle b/app/build.gradle index 42d51d7..15f9727 100755 --- a/app/build.gradle +++ b/app/build.gradle @@ -43,8 +43,13 @@ dependencies { testImplementation libs.robolectric } -// Print the full stack trace of failing tests in the build log (CI keeps nothing else) tasks.withType(Test).configureEach { + // Robolectric sets up Android 16's file descriptors through JDK internals, + // which JDK 17+ only allows when they're exported/opened explicitly + jvmArgs '--add-exports=java.base/jdk.internal.access=ALL-UNNAMED', + '--add-opens=java.base/java.io=ALL-UNNAMED' + + // Print the full stack trace of failing tests in the build log (CI keeps nothing else) testLogging { events 'failed' exceptionFormat = 'full' From 377a7d9e2dec397f3979d1e842988e420dcc5c16 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 20:16:50 +0000 Subject: [PATCH 4/4] Rebuild the puzzle screen when SolvePuzzle is recreated onCreate now always calls setContentView. It used to skip it when savedInstanceState != null, leaving a blank screen. - The puzzle state moves from static fields to instance fields. Statics don't survive the app being killed in the background, and the static TextView/ImageView fields leaked the activity. - onSaveInstanceState saves the start and destination indices and the countries entered so far. - On restore, onCreate reloads that puzzle's paths and replays the entered countries (moveTo), without repeating the toasts or database updates. A solved puzzle comes back solved. - The answer check uses equals() instead of ==. Strings restored from a Bundle are new objects, so == would reject correct answers. - path_length_inner comes from the stored path itself. Every puzzle in graph_paths_summary.csv has paths in graph_paths_subset.csv whose length matches, so this doesn't change new puzzles. Makes SolvePuzzleRecreationTest pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HwXCddsMirbBTNqxSqT6iv --- .../atorch/shortestpaths/SolvePuzzle.java | 310 ++++++++++-------- 1 file changed, 178 insertions(+), 132 deletions(-) diff --git a/app/src/main/java/atorch/shortestpaths/SolvePuzzle.java b/app/src/main/java/atorch/shortestpaths/SolvePuzzle.java index 9ebd739..de16a0c 100755 --- a/app/src/main/java/atorch/shortestpaths/SolvePuzzle.java +++ b/app/src/main/java/atorch/shortestpaths/SolvePuzzle.java @@ -1,6 +1,7 @@ package atorch.shortestpaths; import android.content.ContentValues; +import java.util.ArrayList; import java.util.Arrays; import java.util.Random; @@ -32,27 +33,35 @@ public class SolvePuzzle extends AppCompatActivity { - public final static String COUNTRY_TO = "atorch.shortestpaths.COUNTRY_TO"; + // Saved instance state: enough to rebuild the puzzle after Android recreates this activity + // (for example after killing the app in the background, or when dark mode is switched on) + private static final String STATE_FROM = "atorch.shortestpaths.STATE_FROM"; + private static final String STATE_TO = "atorch.shortestpaths.STATE_TO"; + private static final String STATE_ROUTE = "atorch.shortestpaths.STATE_ROUTE"; - static TextView root_country; - static ImageView arrow; + private TextView root_country; + private ImageView arrow; + private AutoCompleteTextView country_input; - public static int level; + private int level; - static String[] congratulations_array; + private String[] congratulations_array; - static String[] countries; - static int country_from_index; - static int country_to_index; - static String country_from; - static String country_to; + private String[] countries; + private int country_from_index; + private int country_to_index; + private String country_from; + private String country_to; - static int path_length; - static int path_length_inner; // Equal to path_length - 2, i.e. number of countries user has to input - static int number_of_paths; - static String paths[][]; // Paths[i] is an array of country names - static boolean path_indicators[]; // When user's guess is consistent with paths[i], path_indicators[i] will be true - static int user_progress; // How far along path user has traveled + private int path_length; + private int path_length_inner; // Equal to path_length - 2, i.e. number of countries user has to input + private int number_of_paths; + private String[][] paths; // Paths[i] is an array of country names + private boolean[] path_indicators; // When user's guess is consistent with paths[i], path_indicators[i] will be true + private int user_progress; // How far along path user has traveled + private final ArrayList user_route = new ArrayList<>(); // Countries the user has correctly entered, in order + + private SQLiteDatabase db; public static final Random random = new Random(); @@ -139,137 +148,174 @@ private void reachedDestinationCountry(Context context, Resources res) { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - if (savedInstanceState != null) { - // TODO This is most likely wrong - country_to = savedInstanceState.getString(COUNTRY_TO); + // Always build the screen, including when Android recreates this activity + // (savedInstanceState != null), otherwise the user gets a blank screen + setContentView(R.layout.activity_solve_puzzle); + SystemBars.setUp(this); + + Intent intent = getIntent(); + if (intent != null) { + level = intent.getIntExtra(MainActivity.LEVEL, 0); + } + int path_length_lower = 3 + 2 * level; + int path_length_upper = 4 + 2 * level; + if (level == 2) { + path_length_upper = 20; // Not binding; current maximum in data is 9 + } + + final ActionBar actionBar = getSupportActionBar(); + actionBar.setHomeButtonEnabled(true); + actionBar.setDisplayHomeAsUpEnabled(true); + actionBar.setDisplayShowHomeEnabled(true); + + final Resources res = getResources(); + countries = res.getStringArray(R.array.countries); + congratulations_array = res.getStringArray(R.array.correct_guess_congratulations); + + final Context context = getApplicationContext(); + MySQLiteHelper mSQLiteHelper = new MySQLiteHelper(context); + db = mSQLiteHelper.getReadableDatabase(); + + ArrayList restored_route = null; + if (savedInstanceState != null && savedInstanceState.containsKey(STATE_FROM)) { + // Same puzzle as before Android recreated us + country_from_index = savedInstanceState.getInt(STATE_FROM); + country_to_index = savedInstanceState.getInt(STATE_TO); + restored_route = savedInstanceState.getStringArrayList(STATE_ROUTE); } else { - setContentView(R.layout.activity_solve_puzzle); - SystemBars.setUp(this); + Cursor c = getSummaryCursor(path_length_lower, path_length_upper, db); + country_from_index = c.getInt(c.getColumnIndexOrThrow(MySQLiteHelper.COL_FROM)); + country_to_index = c.getInt(c.getColumnIndexOrThrow(MySQLiteHelper.COL_TO)); + c.close(); + } + country_from = countries[country_from_index]; + country_to = countries[country_to_index]; + + root_country = (TextView) findViewById(R.id.countries_visited_root); + root_country.setText(country_from); + arrow = (ImageView) findViewById(R.id.countries_visited_arrow); + int id = getResources().getIdentifier("arrow", "drawable", getPackageName()); + arrow.setImageResource(id); + + Cursor c2 = getPathCursor(country_from_index, country_to_index, db); + number_of_paths = c2.getCount(); + String[][] paths_tokenized = new String[number_of_paths][]; + int i = 0; + while (c2.moveToNext()) { + paths_tokenized[i] = c2.getString(c2.getColumnIndexOrThrow(MySQLiteHelper.COL_PATH)).split(";"); + i++; + } + c2.close(); + // Every shortest path between the same two countries has the same length + path_length_inner = paths_tokenized[0].length; // Number of countries the user has to input + path_length = path_length_inner + 2; + paths = new String[number_of_paths][path_length_inner]; + for (i = 0; i < number_of_paths; i++) { + for (int j = 0; j < path_length_inner; j++) { + paths[i][j] = countries[Integer.parseInt(paths_tokenized[i][j])]; + } + } + path_indicators = new boolean[number_of_paths]; // Paths with which current answer is consistent + Arrays.fill(path_indicators, true); + user_progress = 0; + user_route.clear(); - user_progress = 0; + setPuzzleStatement(res); - Intent intent = getIntent(); - if (intent != null) { - level = intent.getIntExtra(MainActivity.LEVEL, 0); - } - int path_length_lower = 3 + 2 * level; - int path_length_upper = 4 + 2 * level; - if (level == 2) { - path_length_upper = 20; // Not binding; current maximum in data is 9 + Button buttonGiveUp = (Button) findViewById(R.id.button_give_up); + buttonGiveUp.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + openGiveUpDialog(v); } + }); - final ActionBar actionBar = getSupportActionBar(); - actionBar.setHomeButtonEnabled(true); - actionBar.setDisplayHomeAsUpEnabled(true); - actionBar.setDisplayShowHomeEnabled(true); + country_input = (AutoCompleteTextView) findViewById(R.id.autocomplete_country); - final Resources res = getResources(); - countries = res.getStringArray(R.array.countries); - congratulations_array = res.getStringArray(R.array.correct_guess_congratulations); - - final Context context = getApplicationContext(); - MySQLiteHelper mSQLiteHelper = new MySQLiteHelper(context); - SQLiteDatabase db = mSQLiteHelper.getReadableDatabase(); + final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, countries); + country_input.setAdapter(adapter); + country_input.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView parent, View view, int position, long id) { + countryEntered(adapter.getItem(position).toString()); + } + }); + + if (restored_route != null) { + // Put back the countries the user had already entered, without repeating + // the toasts or the database updates + for (String country : restored_route) { + if (!moveTo(country)) { + break; // Shouldn't happen: the route was valid when it was saved + } + } + } + } - Cursor c = getSummaryCursor(path_length_lower, path_length_upper, db); - country_from_index = c.getInt(c.getColumnIndexOrThrow(MySQLiteHelper.COL_FROM)); - country_to_index = c.getInt(c.getColumnIndexOrThrow(MySQLiteHelper.COL_TO)); - country_from = countries[country_from_index]; - country_to = countries[country_to_index]; - path_length = c.getInt(c.getColumnIndexOrThrow(MySQLiteHelper.COL_PATH_LENGTH)); - path_length_inner = path_length - 2; // Number of countries the user has to input - c.close(); + private void countryEntered(String user_answer) { + final Context context = getApplicationContext(); + final Resources res = getResources(); + if (moveTo(user_answer)) { + // TODO Put this in a fn, and call it for very last country seen + ContentValues content = new ContentValues(); + content.put(MySQLiteHelper.COL_COUNTRY_NAME, user_answer); + content.put(MySQLiteHelper.COL_COUNTRY_VISIT_COUNT, 1); // TODO Get previous count and increment + db.update(MySQLiteHelper.VISIT_COUNT_TABLE_NAME, content, MySQLiteHelper.COL_COUNTRY_NAME + " = ?", new String[]{user_answer}); + + if (user_progress < path_length_inner) { + String congratulations = congratulations_array[random.nextInt(congratulations_array.length)]; + Toast.makeText(context, congratulations, Toast.LENGTH_SHORT).show(); + } else { + String greatGuide = res.getString(R.string.great_guide); + Toast.makeText(context, greatGuide, Toast.LENGTH_LONG).show(); + } + } else { + Toast.makeText(context, "Sorry, " + user_answer + " won\'t help.", Toast.LENGTH_LONG).show(); + } + country_input.setText(""); + } - root_country = (TextView) findViewById(R.id.countries_visited_root); - root_country.setText(country_from); - arrow = (ImageView) findViewById(R.id.countries_visited_arrow); - int id = getResources().getIdentifier("arrow", "drawable", getPackageName()); - arrow.setImageResource(id); - - Cursor c2 = getPathCursor(country_from_index, country_to_index, db); - number_of_paths = c2.getCount(); - paths = new String[number_of_paths][path_length_inner]; - path_indicators = new boolean[number_of_paths]; // Paths with which current answer is consistent - Arrays.fill(path_indicators, true); - String[] current_path_tokenized; - int i = 0; - String current_path; - while (c2.moveToNext()) { - current_path = c2.getString(c2.getColumnIndexOrThrow(MySQLiteHelper.COL_PATH)); - current_path_tokenized = current_path.split(";"); - for (int j = 0; j < path_length_inner; j++) - paths[i][j] = countries[Integer.parseInt(current_path_tokenized[j])]; - i++; + /** + * Moves the user to country if it's the next country on a shortest path consistent with the + * countries entered so far, and updates the route on screen. Returns whether it was. + */ + private boolean moveTo(String country) { + boolean correct = false; + boolean[] new_path_indicators = new boolean[number_of_paths]; // Default to false + for (int i = 0; i < number_of_paths; i++) { + if (path_indicators[i] && paths[i][user_progress].equals(country)) { + correct = true; + new_path_indicators[i] = true; } - c2.close(); + } + if (!correct) { + return false; + } + user_progress++; + user_route.add(country); + path_indicators = new_path_indicators; + addCountryVisited(getApplicationContext(), country); - setPuzzleStatement(res); + if (user_progress >= path_length_inner) { + // Done solving puzzle: make country_input invisible; close keyboard + InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + imm.hideSoftInputFromWindow(country_input.getWindowToken(), 0); + country_input.setVisibility(View.GONE); - Button buttonGiveUp = (Button) findViewById(R.id.button_give_up); - buttonGiveUp.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - openGiveUpDialog(v); - } - }); - - final AutoCompleteTextView country_input = (AutoCompleteTextView) findViewById(R.id.autocomplete_country); - - final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, countries); - country_input.setAdapter(adapter); - country_input.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView parent, View view, int position, long id) { - String user_answer = adapter.getItem(position).toString(); - boolean user_answer_is_correct = false; - boolean new_path_indicators[] = new boolean[number_of_paths]; // Default to false - for (int i = 0; i < number_of_paths; i++) { - if (path_indicators[i] && paths[i][user_progress] == user_answer) { - user_answer_is_correct = true; - new_path_indicators[i] = true; - } - } - if (user_answer_is_correct) { - user_progress++; - path_indicators = new_path_indicators; - addCountryVisited(context, user_answer); - - // TODO Put this in a fn, and call it for very last country seen - ContentValues content = new ContentValues(); - content.put(MySQLiteHelper.COL_COUNTRY_NAME, user_answer); - content.put(MySQLiteHelper.COL_COUNTRY_VISIT_COUNT, 1); // TODO Get previous count and increment - db.update(MySQLiteHelper.VISIT_COUNT_TABLE_NAME, content, MySQLiteHelper.COL_COUNTRY_NAME + " = ?", new String[]{user_answer}); - - if (user_progress < path_length_inner) { - String congratulations = congratulations_array[random.nextInt(congratulations_array.length)]; - Toast.makeText(context, congratulations, Toast.LENGTH_SHORT).show(); - } else { - // Done solving puzzle: make country_input invisible; close keyboard - InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); - imm.hideSoftInputFromWindow(country_input.getWindowToken(), 0); - country_input.setVisibility(View.GONE); - - reachedDestinationCountry(context, res); - - String greatGuide = res.getString(R.string.great_guide); - Toast.makeText(context, greatGuide, Toast.LENGTH_LONG).show(); - - LinearLayout buttons = (LinearLayout) findViewById(R.id.buttons); - buttons.setVisibility(View.VISIBLE); - } - } else { - Toast.makeText(context, "Sorry, " + user_answer + " won\'t help.", Toast.LENGTH_LONG).show(); - } - country_input.setText(""); - } - }); + reachedDestinationCountry(getApplicationContext(), getResources()); + + LinearLayout buttons = (LinearLayout) findViewById(R.id.buttons); + buttons.setVisibility(View.VISIBLE); } + return true; } @Override public void onSaveInstanceState(Bundle savedInstanceState) { - super.onSaveInstanceState(savedInstanceState); // TODO Am I using this? - savedInstanceState.putString(COUNTRY_TO, country_to); + super.onSaveInstanceState(savedInstanceState); + savedInstanceState.putInt(STATE_FROM, country_from_index); + savedInstanceState.putInt(STATE_TO, country_to_index); + savedInstanceState.putStringArrayList(STATE_ROUTE, new ArrayList<>(user_route)); } public void backToMain(View view) { @@ -279,7 +325,7 @@ public void backToMain(View view) { public void newPuzzle(View view) { Intent intent = new Intent(this, SolvePuzzle.class); - intent.putExtra(MainActivity.LEVEL, SolvePuzzle.level); + intent.putExtra(MainActivity.LEVEL, level); startActivity(intent); }