1/99
Looks like no tags are added yet.
[001 | Android] What five main parts appear in the module's simplified Android architecture list?
Applications → Android Framework → Android Runtime → Platform Libraries → Linux Kernel. This is the course's simplified list; modern architecture diagrams also show a hardware abstraction layer (HAL), and native libraries and the runtime sit alongside one another beneath the framework.
[002 | Android] Match the Android architecture parts to these jobs: hardware drivers/process management, reusable system services, native C/C++ functionality, and end-user apps.
Linux kernel: drivers and process/memory management. Application framework: high-level services such as activity and notification management. Platform/native libraries: C/C++ capabilities such as graphics and database support. Applications layer: user-facing apps.
[003 | Android] What do Dalvik and ART do, and how are they related?
They execute Android app code in DEX format. Dalvik is the older runtime; ART (Android Runtime) replaced it as the default in Android 5.0. Dalvik is associated with JIT compilation; ART introduced AOT compilation and modern ART also uses JIT/profile-guided compilation.
[004 | Android] What is an Android API level? Give the levels for Android 5.0, 6.0, 7.0, 8.0, and 13.
An integer identifying a platform API revision, rather than the marketing version number. Android 5.0 = API 21; 6.0 = 23; 7.0 = 24; 8.0 = 26; 13 = 33. Android 16 is API 36.
[005 | Android] An app has minSdk 23 and targetSdk 35. Considering only these settings, can devices on API 22, 26, and 36 run it?
API 22: no, it is below the minimum. API 26 and 36: eligible. minSdk is the oldest supported API; targetSdk declares the API level the app targets and affects compatibility behavior. targetSdk is neither the minimum nor a maximum supported version.
[006 | Android] An app supports API 23 but calls a method introduced in API 26. Does setting targetSdk to 35 make that method available on API 23?
No. The device must actually provide the API. Guard the call with Build.VERSION.SDK_INT >= 26 and use a supported alternative on older devices. Test supported API levels and device configurations; required hardware/features also affect compatibility.
[007 | Android] Match Android 1.5, 1.6, 2.0/2.1, and 2.2 to their dessert names and the class features: video recording, larger screens, live wallpaper, and Wi-Fi hotspot.
1.5 Cupcake: video recording. 1.6 Donut: support for more screen sizes. 2.0/2.1 Eclair: live wallpaper, added in 2.1. 2.2 Froyo: Wi-Fi hotspot. Android 1.0 and 1.1 had no official dessert codenames.
[008 | Android] Match Gingerbread, Honeycomb, and Ice Cream Sandwich to their version families and major class features.
Gingerbread: Android 2.3, improved copy/paste and keyboard/UI changes. Honeycomb: Android 3.x, tablet-focused interface. Ice Cream Sandwich: Android 4.0, Face Unlock and Wi-Fi Direct. Use 2.3 for Gingerbread; the slide's 2.4 label is erroneous.
[009 | Android] Which version families are associated with Google Now, "OK Google," and Material Design plus ART as the default runtime?
Google Now: Android 4.1-4.3 Jelly Bean. "OK Google": Android 4.4 KitKat in the class slides. Material Design and default ART: Android 5.0-5.1 Lollipop.
[010 | Android] Match Android 6.0, 7.0, and 8.0 to their names and the features: runtime permissions, split-screen/Data Saver, and picture-in-picture/notification channels.
6.0 Marshmallow: runtime permissions and fingerprint authentication. 7.0 Nougat: split-screen and Data Saver. 8.0 Oreo: picture-in-picture, adaptive icons, and notification channels.
[011 | Android] Which releases are associated with Adaptive Battery/Brightness, a system-wide dark theme, and native screen recording/notification history?
Android 9 Pie: Adaptive Battery and Adaptive Brightness. Android 10 (internal name Quince Tart): system-wide dark theme. Android 11 (Red Velvet Cake): native screen recording and notification history.
[012 | Android] Match Android 12, 13, 14, 15, and 16 to their internal dessert names and the features emphasized in the slides.
12 Snow Cone: scrolling screenshots and one-handed mode. 13 Tiramisu: more Material You themes and QR scanner support. 14 Upside Down Cake: notification flashes and predictive back. 15 Vanilla Ice Cream: partial screen sharing and sensitive-notification protection. 16 Baklava. The slide also labels Cinnamon Bun as Android 16; that duplicate label is incorrect.
[013 | Kotlin] Why does val score = 10; score = 11 fail, while var score = 10; score = 11 succeeds?
val prevents reassignment after initialization; var allows reassignment. The initial integer value lets Kotlin infer Int. val makes the reference read-only, not necessarily the referenced object's contents immutable.
[014 | Kotlin] What does fun main() { println(5 > 3 && 5 < 10) } print, and what do fun and main mean?
It prints true, followed by a newline, because both comparisons are true. fun declares a function; main is the entry point of this standalone program. Semicolons are optional; // starts a line comment and /* ... */ encloses a block comment.
[015 | Kotlin] Given fun add(a: Int, b: Int = 2): Int { return a + b }, what does println(add(3)) print? Which names are parameters?
5. a and b are parameters; 3 is the supplied argument for a, and b uses its default value 2. The final : Int declares the return type.
[016 | Kotlin] Given class Student(val name: String), how do you create student with the name "Alex," and what does println(student.name) print?
val student = Student("Alex"); the output is Alex. Student is the class, student is an object reference, and val name declares a primary-constructor parameter that becomes a read-only property. Kotlin does not use new for constructor calls.
[017 | Kotlin] Complete the secondary constructor: class Student(val name: String) { constructor() : ___("Guest") }. What does Student().name return?
Use this: constructor() : this("Guest"). The result is "Guest". A secondary constructor uses the constructor keyword and must delegate to the primary constructor when one exists, directly or through another secondary constructor.
[018 | Kotlin] Why does class Base; class Child : Base() fail, and how is ordinary class inheritance enabled?
Kotlin classes are final by default. Write open class Base and then class Child : Base(). The colon introduces the superclass, and Base() invokes its constructor. Members that subclasses override must also permit overriding.
[019 | Kotlin] Trace: open class Base { open fun show() { print("A") } }; class Child : Base() { override fun show() { super.show(); print("B") } }. What does Child().show() print?
AB. open permits overriding, override supplies the subclass implementation, and super.show() explicitly runs the superclass implementation before the subclass prints B.
[020 | Kotlin] What does lateinit var title: String allow, and who must initialize title?
It postpones initialization of a non-null String variable/property. Your code must assign a value before reading it. lateinit does not construct an object or initialize the value automatically.
[021 | Kotlin] Which declarations are invalid, and why? (1) lateinit val a: String; (2) lateinit var b: Int; (3) lateinit var c: String?; (4) lateinit var d: String
(1) Invalid: lateinit requires var. (2) Invalid: Int is a primitive type. (3) Invalid: String? is nullable. (4) Valid: a non-null, non-primitive var can be initialized later.
[022 | Kotlin] A class declares lateinit var title: String. What happens if a method reads title before any assignment?
Kotlin throws UninitializedPropertyAccessException. It does not return null or an empty string. Within an allowed scope, this::title.isInitialized can test whether the property has been assigned.
[023 | Kotlin] Trace: class Sample { val x = 2; init { print(x) }; init { print("!") } }. What does Sample() print, and when do init blocks run?
2!. Property initializers and init blocks run in declaration order during construction of each object. init performs initialization work immediately during construction; lateinit delays a variable's assignment until your code supplies it later.
[024 | Kotlin] What does var name: String? = null; println(name?.length ?: 0) print?
0. String? permits null; ?. accesses length only when name is non-null; ?: supplies the fallback when the left side is null. Using name!! instead would throw a NullPointerException here.
[025 | Android Studio] How do Android Studio, the Android SDK, and Gradle differ?
Android Studio is the IDE for editing, running, and debugging projects. The Android SDK supplies platform APIs and development tools. Gradle, with the Android Gradle plugin, runs build tasks, resolves dependencies, and packages the app; build.gradle or build.gradle.kts configures the build.
[026 | Android Studio] What is an Android Virtual Device (AVD), and how do you create/manage one?
An AVD is an emulator configuration describing a device's hardware profile and Android system image/API level. Use Device Manager → Create Device, choose a hardware profile and system image, then launch it in the emulator. Device Manager also lets you edit, delete, or reset virtual devices.
[027 | Android Studio] What are the basic steps for running/debugging an app on a physical phone over USB?
Enable Developer Options (usually by tapping Build number repeatedly), enable USB debugging, connect with a data-capable USB cable, authorize the computer's debugging prompt, choose the device in Android Studio, and run the app. Debugging authorization and a working device connection are required.
[028 | Android Studio] Which Android Studio tool helps you inspect app logs and the exception/stack trace behind a crash?
Logcat. Select the correct device/process and filter by package, tag, or severity. It displays runtime messages from the device, including messages your app writes using android.util.Log.
[029 | Android Studio] Match Log.v(), Log.d(), Log.i(), Log.w(), Log.e(), and Log.wtf() to their log levels. What do the two strings in Log.d("MainActivity", "Loaded") mean?
v = VERBOSE, d = DEBUG, i = INFO, w = WARN, e = ERROR, wtf = ASSERT (a severe condition that should not occur). "MainActivity" is the tag identifying the source; "Loaded" is the message.
[030 | Android Studio] List Logcat severity levels from lowest to highest. Which appear with the filter level:WARN?
VERBOSE → DEBUG → INFO → WARN → ERROR → ASSERT. level:WARN includes WARN, ERROR, and ASSERT, while lower-severity entries are filtered out.
[031 | Components & Resources] Match these jobs to the four main Android components: interactive screen, background work, response to a broadcast, and structured data sharing.
Activity: interactive screen. Service: background operations. BroadcastReceiver: responds to system/app broadcasts. ContentProvider: exposes structured data through an interface accessed by ContentResolver. A Service does not automatically create a separate worker thread.
[032 | Components & Resources] What does AndroidManifest.xml describe, and where is an Activity declared?
It declares essential app information such as components, permissions, intent filters, and required features. Declare an Activity with an
[033 | Components & Resources] Match these resource types to folders: UI layouts, images/drawables, menu definitions, unchanged raw files, and simple values.
Layouts → res/layout/; images and drawable XML → res/drawable/; menus → res/menu/; raw files → res/raw/; strings/colors/dimensions/styles → res/values/. Typical value files are strings.xml, colors.xml, dimens.xml, and styles.xml.
[034 | Components & Resources] What is the generated R class, and does R.string.app_name contain the actual app-name text?
R contains generated resource identifiers. R.string.app_name is an ID, not the text itself; getString(R.string.app_name) loads the string. R.layout, R.drawable, R.color, and R.id identify other resource types.
[035 | Components & Resources] For res/layout/activity_main.xml, give its Java resource expression and its XML reference.
Java: R.layout.activity_main. XML: @layout/activity_main. Omit the .xml extension. Example Java use: setContentView(R.layout.activity_main);.
[036 | Components & Resources] For res/drawable/logo.png, complete image.setImageResource(___) in Java and android:src="___" in XML.
Java: image.setImageResource(R.drawable.logo); XML: android:src="@drawable/logo". Resource references use the drawable's name without its file extension.
[037 | Components & Resources] For
Java: label.setText(R.string.welcome); XML: android:text="@string/welcome". To obtain the actual Java String, call getString(R.string.welcome). The reference uses welcome, not the filename strings.
[038 | Components & Resources] For
Java ID: R.color.primary. XML: android:textColor="@color/primary". A resource ID is not the resolved color value; resolve it before passing it to a Java method that expects a color integer.
[039 | Components & Resources] How do @+id/saveButton, @id/saveButton, and R.id.saveButton differ?
@+id/saveButton declares the ID if needed in XML. @id/saveButton references an existing ID in XML. R.id.saveButton is its generated Java/Kotlin resource expression, used for example with findViewById().
[040 | Activities] What is the usual callback sequence when a new Activity instance first opens?
onCreate() → onStart() → onResume(). onCreate() initializes the instance; onStart() makes it visible; onResume() makes it active for foreground interaction.
[041 | Activities] Which callback is appropriate for initial layout setup, and which runs again when an existing paused Activity resumes?
Initial setup: onCreate(). Resuming interaction: onResume(). An existing instance can enter onResume() many times without repeating onCreate().
[042 | Activities] How do onPause() and onStop() differ?
onPause(): the Activity loses foreground interaction but may still be visible. onStop(): it is no longer visible. A paused Activity can still execute code; "paused" does not mean its code is completely frozen.
[043 | Activities] Activity A is resumed. The user goes Home or opens an opaque Activity B that fully covers A. What callbacks normally run on A?
A.onPause() → A.onStop(). Leaving does not by itself mean A is destroyed; it can remain as a stopped instance.
[044 | Activities] The user returns to Activity A, which was stopped and whose instance was retained. Which callbacks normally run?
onRestart() → onStart() → onResume(). onCreate() is not repeated for that retained instance.
[045 | Activities] A translucent Activity covers part of A, so A receives onPause() but never onStop(). When it is dismissed, which callback resumes A?
onResume(). There is no onRestart() or onCreate() because A only paused and the same instance is being resumed.
[046 | Activities] A's process was killed while it was in the background. How does returning to A differ from resuming a retained instance?
Android must create a new instance: onCreate() → onStart() → onResume(), with state restoration when available. This is not the retained-instance onRestart() path. Process death does not guarantee a call to onDestroy().
[047 | Activities] A resumed Activity calls finish(). What is the normal lifecycle sequence, and can that same finished instance resume later?
Normally onPause() → onStop() → onDestroy(). finish() ends that Activity instance; opening the screen later requires a new instance. It does not necessarily terminate the entire app process.
[048 | Activities] Complete the Java layout-loading call for res/layout/activity_main.xml. Why should it precede Activity.findViewById() for views in that layout?
setContentView(R.layout.activity_main); usually inside onCreate() after super.onCreate(savedInstanceState). It installs the Activity's content view hierarchy so findViewById() can locate the views in it.
[049 | User Interface] What is the difference between a View and a ViewGroup?
A View represents a UI element; a ViewGroup is a View subclass that contains and arranges child Views or ViewGroups. TextView is a View; LinearLayout is a ViewGroup. A regular XML view layout has one root element.
[050 | User Interface] Which control is appropriate for displaying a label, accepting editable user text, and triggering an action when pressed?
TextView displays the label; EditText accepts editable text; Button triggers the action through a listener. EditText and Button inherit text-handling behavior from TextView.
[051 | User Interface] Choose the layout for (a) controls in one vertical column and (b) one control positioned below another or aligned with its parent.
(a) LinearLayout with android:orientation="vertical". (b) RelativeLayout, using rules such as android:layout_below="@id/title" or android:layout_alignParentTop="true". Horizontal LinearLayout places children in one row.
[052 | User Interface] Which layout suits overlapping/stacked views, and which arranges child views in a rectangular row-and-column grid?
FrameLayout suits stacking/overlap. GridLayout arranges children in rows and columns, using settings such as android:columnCount, android:layout_row, and android:layout_column. GridLayout directly arranges children; it is different from the adapter-based GridView.
[053 | User Interface] How do match_parent, wrap_content, layout_margin, and padding affect a View?
layout_width/layout_height set its dimensions. match_parent uses the parent's available space; wrap_content fits the content. layout_margin adds space outside the View; padding adds space inside its boundary around its content. android:gravity positions content inside a View; android:layout_gravity positions the View within a supporting parent layout.
[054 | User Interface] After setContentView(), complete: TextView result = ___(R.id.resultText);. What happens if no matching View exists in the loaded hierarchy?
Use findViewById: TextView result = findViewById(R.id.resultText); It returns null if no matching View exists, so calling result.setText(...) then causes a NullPointerException. Check the loaded layout and the ID.
[055 | User Interface] In Java, nameInput is an EditText and label is a TextView. How do you copy the entered text to label? Why is label.setText(5) different from label.setText("5")?
label.setText(nameInput.getText().toString()); setText(5) treats 5 as a string resource ID and may throw Resources.NotFoundException; setText("5") displays the character 5. To display a number, use String.valueOf(5).
[056 | User Interface] Complete the Java code to change a TextView named label when button is clicked: button.___(v -> label.setText("Saved"));
button.setOnClickListener(v -> label.setText("Saved")); The listener interface is View.OnClickListener and its callback is onClick(View v). A click callback returns void.
[057 | User Interface] Which listener handles a long press, and what does returning true from its callback mean?
setOnLongClickListener(...) registers View.OnLongClickListener; its callback is onLongClick(View v). Returning true means the long-click event was handled/consumed. Example: button.setOnLongClickListener(v -> { label.setText("Held"); return true; });
[058 | User Interface] Which listener receives touch actions such as finger down, move, and up? What is its callback's boolean result used for?
View.OnTouchListener, registered with setOnTouchListener(...), receives onTouch(View v, MotionEvent event). Inspect actions such as ACTION_DOWN, ACTION_MOVE, and ACTION_UP. true means the listener consumed the event; false allows normal View handling to continue.
[059 | User Interface] Which listener detects when an EditText gains or loses focus, and how do you tell the two cases apart?
Use setOnFocusChangeListener(...), whose callback is onFocusChange(View v, boolean hasFocus). hasFocus is true when focus is gained and false when it is lost. Example: input.setOnFocusChangeListener((v, hasFocus) -> { if (!hasFocus) label.setText("Left field"); });
[060 | User Interface] Inside an Activity, how do you create a Button in Java, set its text to "Save," and attach it to an existing LinearLayout named container?
Button b = new Button(this); b.setText("Save"); container.addView(b); Constructing a View alone does not attach it to the visible hierarchy; addView() places it inside the parent.
[061 | User Interface] What does an adapter do for a ListView? Complete: ArrayAdapter
Use list.setAdapter(a); The adapter connects the data collection (names) to row Views displayed by the ListView. The ListView displays the scrolling rows; the adapter supplies their data and presentation.
[062 | Intents] Which Intent type suits opening your app's specific DetailsActivity, and which suits asking a compatible app to open a web URL?
Explicit Intent for DetailsActivity: it names the target component. Implicit Intent for opening a URL: it specifies an action/data and lets Android find a matching component through intent filters.
[063 | Intents] Inside MainActivity, write Java code to open DetailsActivity using an explicit Intent.
Intent i = new Intent(MainActivity.this, DetailsActivity.class); startActivity(i); The constructor supplies the current Context and destination class. The Activity must be declared in the manifest.
[064 | Intents] What kind of Intent is new Intent(Intent.ACTION_VIEW, Uri.parse("https://example.com")), and how is it launched?
An implicit Intent asking to view the URL. Pass it to startActivity(i). If no component can handle it, launching can throw ActivityNotFoundException; handle that case. ACTION_DIAL with a tel: URI similarly asks for a dialer instead of naming a specific Activity.
[065 | Intents] Complete this Java data flow: before startActivity(i), attach the String "Alex" under "name"; then read it in the destination Activity.
Sender: i.putExtra("name", "Alex"); startActivity(i); Receiver: String name = getIntent().getStringExtra("name"); Add the extra to the Intent actually used to launch the destination, before launching.
[066 | Intents] The sender uses i.putExtra("userName", "Alex"), but the receiver calls getIntent().getStringExtra("username"). What is returned, and what is the fix?
null, assuming no separate "username" extra exists. Keys are case-sensitive and must match exactly. Retrieve with "userName", preferably using one shared key constant, and check for null before calling methods such as length().
[067 | Intents] What does getIntent().getIntExtra("age", -1) return if "age" is absent? What if the sender supplied it as the String "20"?
-1 in both cases: the getter returns its default when an int of the requested key/type is unavailable. If the sender uses putExtra("age", 20), it returns 20. Match both the key and the stored type.
[068 | Intents] How can you send the String "Alex" under "name" using a Bundle, then retrieve it safely in Java?
Sender: Bundle b = new Bundle(); b.putString("name", "Alex"); i.putExtras(b); startActivity(i); Receiver: Bundle b = getIntent().getExtras(); String name = b != null ? b.getString("name") : null; A Bundle groups typed values under String keys; the resulting name can still be null.
[069 | Intents] Why can getIntent().getExtras().getString("name").length() crash, and what is a safe Java alternative?
getExtras() can be null, and the requested String can also be null. Safer: String name = getIntent().getStringExtra("name"); int length = name != null ? name.length() : 0; Do not assume a Bundle or a specific extra is present.
[070 | Notifications] When would you use a Toast rather than a system notification?
Use a Toast for brief feedback such as "Saved"; it disappears automatically and does not create a notification-drawer entry. Use a system notification for information the user can view or act on outside the app's normal UI, including through the notification drawer.
[071 | Notifications] Inside an Activity, complete the Java Toast and identify its three makeText parameters: Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).___();
show(). The parameters are Context, message text, and duration. Full call: Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show(); LENGTH_SHORT and LENGTH_LONG are duration constants; makeText() creates the Toast, and show() displays it.
[072 | Notifications] What is a heads-up notification, and what happens after its floating banner disappears?
A brief banner for eligible notifications, introduced in Android 5.0. The notification normally remains in the drawer after the banner disappears. High channel importance is relevant on Android 8.0+; older versions use notification priority, but display behavior also depends on system/user settings.
[073 | Notifications] Can a notification appear on the lock screen, and must all of its sensitive content be shown?
Notifications can appear on the lock screen from Android 5.0. Their visibility/detail can be restricted, for example to hide sensitive content; user notification and lock-screen settings also affect what appears.
[074 | Notifications] What does a notification dot on an app's launcher icon indicate, and which Android version introduced platform support?
It indicates active notifications for that app on supported launchers. Platform support began with Android 8.0/API 26; users can often long-press the icon to inspect the notifications.
[075 | Notifications] How do NotificationCompat.Builder and NotificationManager/NotificationManagerCompat differ? Does build() display anything by itself?
The Builder configures content such as title, text, and icons; build() creates the Notification object. The manager posts or updates it through notify(). Example builder methods: setContentTitle("Reminder") and setContentText("Review now"). build() alone does not post it.
[076 | Notifications] For an app targeting API 26+, what channel setup is required before posting on Android 8.0+?
Create NotificationChannel(channelId, userVisibleName, importance) and register it with NotificationManager.createNotificationChannel(...). Use the same channelId in NotificationCompat.Builder(context, channelId). Channel importance controls interruptiveness on 8.0+; setPriority() applies to 7.1 and below.
[077 | Notifications] How do setSmallIcon(...) and setLargeIcon(...) differ? Can a large icon replace the required small icon?
setSmallIcon(R.drawable.ic_notification) supplies the required small notification/status icon. setLargeIcon(bitmap) optionally adds a larger content image, such as an avatar, when supported by the template. A large icon does not replace the required small icon.
[078 | Notifications] Assume permission and channel requirements are satisfied. What happens when you call manager.notify(7, builder.build()) again with changed text? How do you post a separate notification?
Reusing ID 7 updates/replaces that notification for the same app (and tag, if used). Use a different ID for a separate notification. notify() posts the built object; the notification ID is different from the channel ID.
[079 | Notifications] How does a notification arrange to open an Activity when the user taps it?
Create a PendingIntent for the desired Activity action and attach it with builder.setContentIntent(pendingIntent). The system can execute that action later when the user taps. setContentTitle() changes the title; it does not define the tap action.
[080 | SQLite] Where does a normal named SQLite database live in an Android app, and does using it require a remote database server?
It is stored locally in a database file, normally in the app's private databases directory. SQLite is embedded, so a remote server/network connection is not required. The database uses SQLite's binary format, not an ordinary plain-text file.
[081 | SQLite] How does SQLiteOpenHelper differ from SQLiteDatabase? Does constructing your helper immediately create the database file?
SQLiteOpenHelper manages opening, initial creation, and version changes. SQLiteDatabase exposes operations such as insert() and query(). Constructing a helper alone does not open/create the database; opening is triggered by getReadableDatabase() or getWritableDatabase().
[082 | SQLite] When are SQLiteOpenHelper.onCreate() and onUpgrade() called, and what must you change to trigger an upgrade?
onCreate(SQLiteDatabase db) initializes a new database, usually with CREATE TABLE. onUpgrade(db, oldVersion, newVersion) handles an existing database opened with a higher requested version. Increase the helper's database version and implement the migration; editing a CREATE TABLE string alone does not update existing tables.
[083 | SQLite] Is getReadableDatabase() guaranteed to return a read-only database? How does it differ from getWritableDatabase()?
No. getReadableDatabase() normally returns the same read/write database as getWritableDatabase(), but can fall back to read-only when writing is unavailable. getWritableDatabase() requires read/write access and throws if it cannot obtain it. Both return SQLiteDatabase objects.
[084 | SQLite] What belongs in a database contract class, and why is it useful?
Constants for table names, column names, and related identifiers. A contract keeps the schema names consistent across CREATE TABLE, insert, and query code, so a name can be changed in one place.
[085 | SQLite] Interpret: ContentValues values = new ContentValues(); values.put("name", "Alex"); long id = db.insert("students", null, values);
ContentValues maps the name column to "Alex"; insert() adds a row to students. The returned long is the new row ID, or -1 if insertion fails. It is not the number of rows inserted.
[086 | SQLite] Match CREATE TABLE, INSERT INTO, SELECT, UPDATE, and DELETE FROM to their jobs. What do Android db.update() and db.delete() return?
CREATE TABLE defines a table; INSERT INTO adds rows; SELECT reads rows; UPDATE changes existing rows; DELETE FROM removes rows. db.update() and db.delete() return the number of affected rows. A missing WHERE condition can affect every row.
[087 | SQLite] Assume age is an INTEGER column. Interpret: Cursor c = db.query("students", new String[]{"name"}, "age > ?", new String[]{"18"}, null, null, "name ASC");
Read name from students where age > 18, ordered by name ascending. {"name"} is the projection; "age > ?" is the selection; {"18"} supplies selectionArgs. The result is a Cursor. Bind user values with ?/selectionArgs instead of concatenating them into SQL.
[088 | SQLite] A query Cursor starts at position -1. What does while (c.moveToNext()) do, including when the result set is empty?
Each successful call moves to the next row, starting with row 0, and returns true. The loop body runs once per row. For an empty result it immediately returns false, so the body does not run. Position the Cursor before reading column values.
[089 | SQLite] For a nonempty Cursor, why does c.moveToFirst(); while (c.moveToNext()) { ... } skip data?
moveToFirst() already moves to row 0; the first moveToNext() advances to row 1, so row 0 is skipped. Use while (c.moveToNext()) from the initial position, or if (c.moveToFirst()) { do { ... } while (c.moveToNext()); }.
[090 | SQLite] Once c points to a valid row, how do you read the name column and release the Cursor afterward?
String name = c.getString(c.getColumnIndexOrThrow("name")); A column index identifies a column, not a row. After all reads, call c.close(), preferably in finally or try-with-resources. close() frees resources; it does not delete database records.
[091 | JSON Parser] Identify the root, students, and each student in {"students":[{"name":"Ana","age":20,"active":true}],"note":null}. Which JSON value types are shown?
Root: an object. students: an array containing a student object. name: string; age: number; active: boolean; note: null. JSON objects contain name/value pairs; arrays contain ordered values. JSON means JavaScript Object Notation.
[092 | JSON Parser] Why is {name: 'Ana', "active": True,} invalid standard JSON? Rewrite it correctly.
{"name":"Ana","active":true}. Standard JSON requires double-quoted object names and strings, lowercase true/false/null, colons between names and values, and commas between entries without a trailing comma. Comments are not standard JSON.
[093 | JSON Parser] Which Java class should parse jsonText when the root is {"name":"Ana"}, and which should parse arrayText when the root is ["Ana","Ben"]?
Object root: JSONObject obj = new JSONObject(jsonText); Array root: JSONArray arr = new JSONArray(arrayText); Choose the class that matches the root structure and handle/declare JSONException in Java when required.
[094 | JSON Parser] Given {"user":{"name":"Ana","hobbies":["reading","gaming"]}}, complete root.___("user").___("name") to retrieve Ana.
root.getJSONObject("user").getString("name"). getJSONObject() retrieves a nested object; getString() retrieves/converts its named value as a string. To retrieve hobbies as an array, use root.getJSONObject("user").getJSONArray("hobbies").
[095 | JSON Parser] Given {"user":{"hobbies":["reading","gaming"]}}, what does root.getJSONObject("user").getJSONArray("hobbies").getString(1) return?
"gaming". Arrays use zero-based indexes: 0 is "reading", 1 is "gaming". The final getString() takes an index because it is called on a JSONArray; JSONObject.getString() takes a key.
[096 | JSON Parser] Given {"company":{"employees":[{"name":"John"},{"name":"Jane"}]}}, write the org.json chain to retrieve Jane from root.
root.getJSONObject("company").getJSONArray("employees").getJSONObject(1).getString("name"); Follow object key → array key → element index → object key. getJSONObject(1) selects the second employee object.
[097 | JSON Parser] For root = {"students":[{"name":"Ana"},{"name":"Ben"}],"count":2}, what do root.length() and root.getJSONArray("students").length() return?
2 and 2. JSONObject.length() counts that object's immediate name/value mappings (students and count); JSONArray.length() counts elements. Object length is not a recursive count of all nested keys.
[098 | JSON Parser] If obj contains only {"name":"Ana"}, what happens with obj.getString("email")? How can you supply a default for an absent key?
getString("email") throws JSONException because the mapping is missing. obj.optString("email", "Unknown") returns the fallback for that absent key, or check obj.has("email") first. Unlike Intent.getStringExtra(), this getter does not simply return null for a missing key.
[099 | JSON Parser] Given {"students":[{"name":"Ana"}]}, why does root.getJSONObject("students") fail, and which chain gets Ana?
students is an array, not a JSONObject, so getJSONObject("students") throws JSONException. Use root.getJSONArray("students").getJSONObject(0).getString("name");.
[100 | JSON Parser] What happens in these Android org.json cases: new JSONObject("{"); obj.getInt("age") when age is "twenty"; arr.getString(2) for a two-element array?
Each throws JSONException: the object text is unfinished; "twenty" cannot be converted to an int; index 2 is outside valid indexes 0 and 1. In Java, use try/catch (JSONException e) or declare it. Some getters coerce compatible values, so not every differing primitive type causes an exception.