MOBPROG 100 V2

0.0(0)
Studied by 0 people
call kaiCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/99

encourage image

There's no tags or description

Looks like no tags are added yet.

100 Terms

1
New cards

[101 | Android] Which API levels correspond to Android 4.1, 4.2, 4.3, and 4.4? What does this show about dessert names?

4.1 = API 16; 4.2 = API 17; 4.3 = API 18; 4.4 = API 19. The first three are Jelly Bean; 4.4 is KitKat. One dessert name can span multiple platform versions and API levels.

2
New cards

[102 | Android] Match Android 5.1, 7.1, and 8.1 to their dessert names and API levels.

5.1 = Lollipop, API 22; 7.1 = Nougat, API 25; 8.1 = Oreo, API 27. Their major-version counterparts 5.0, 7.0, and 8.0 use API 21, 24, and 26 respectively.

3
New cards

[103 | Android] Which API levels identify Android 9, Android 10, and Android 11?

Android 9 (Pie) = API 28; Android 10 = API 29; Android 11 = API 30. The version number and API level are different numbering systems.

4
New cards

[104 | Android] Match Android 12, Android 12L, Android 14, and Android 15 to their API levels.

Android 12 = API 31; Android 12L = API 32; Android 14 = API 34; Android 15 = API 35. Android 12L is a distinct API revision even though its name still contains 12.

5
New cards

[105 | Android] Which Android versions introduced automatic permission reset for unused apps and the AppSearch on-device search API?

Android 11 introduced automatic permission reset for unused apps; Android 12 introduced the platform AppSearch API. Permission reset revokes eligible runtime permissions after prolonged disuse; AppSearch supports indexing and searching app data on the device.

6
New cards

[106 | Android] Match display-cutout support and a separate background-location permission to the Android versions that introduced them.

Android 9 (Pie): display-cutout support for screens with notches. Android 10: ACCESS_BACKGROUND_LOCATION for requesting location access in the background, separately from foreground location access.

7
New cards

[107 | Android] What do JIT and AOT stand for, and when does each compile code?

JIT = Just-In-Time: compilation happens during execution. AOT = Ahead-Of-Time: compilation happens before execution. Modern ART can combine AOT, JIT, and interpretation; ART should not be described as exclusively AOT.

8
New cards

[108 | Android] In the Android build pipeline, what is the role of DEX files relative to Java/Kotlin source code and an APK?

Java/Kotlin source is compiled and converted into DEX bytecode, which is packaged in the APK. ART executes DEX-based app code. DEX is executable code format, while APK is the application package containing code and resources.

9
New cards

[109 | Android] An app uses compileSdk 35 and minSdk 23. What does compileSdk control, and which setting sets the oldest supported device API?

compileSdk controls which Android API declarations are available when compiling the app. minSdk 23 sets the minimum supported device API. Compiling against API 35 does not make API 35 methods exist on an API 23 device.

10
New cards

[110 | Android] How does android:required="false" in a declaration affect device compatibility?

It declares that the hardware/software feature is optional, so that declaration does not filter out devices lacking it. The app must check availability and handle its absence. required="true" makes the feature a requirement for store filtering.

11
New cards

[111 | Kotlin] Trace Kotlin: class Counter(var count: Int); val c = Counter(1); c.count = 4; print(c.count). Why is this allowed?

It prints 4. val prevents assigning a different Counter to c, but count is a var property and can change. Reassigning c = Counter(9) would be invalid.

12
New cards

[112 | Kotlin] What is wrong with Kotlin: var score = 10; score = "ten"?

score is inferred as Int, so assigning a String is a compile-time type mismatch. var permits reassignment of compatible values; it does not make the variable dynamically typed.

13
New cards

[113 | Kotlin] What is the return type of Kotlin fun greet() { println("Hi") }, and what does calling it do?

Its return type is Unit. Calling greet() prints Hi and does not return a meaningful result such as a String. Printing a value is different from returning that value.

14
New cards

[114 | Kotlin] Why does Kotlin fun increment(x: Int): Int { x++; return x } fail, and how can it be fixed?

Function parameters are read-only, so x++ attempts an illegal reassignment. Return x + 1 instead, or copy x into a local var before changing the copy.

15
New cards

[115 | Kotlin] Trace Kotlin: fun label(name: String = "Guest", score: Int = 0) = "name:name:score". What does label(score = 7) return?

"Guest:7". The named argument assigns score while name uses its default. label(7) would be invalid because the first positional parameter expects a String.

16
New cards

[116 | Kotlin] Why does class User(name: String); val u = User("Ana"); print(u.name) fail in Kotlin?

name is a constructor parameter, not an exposed property. Use class User(val name: String) to create a readable property, or var name for a property that can be reassigned.

17
New cards

[117 | Kotlin] Given class Book(val title: String = "Untitled"), what do Book().title and Book("Android").title evaluate to?

"Untitled" and "Android". A default value lets the caller omit that constructor argument. A separate secondary constructor is unnecessary for this defaulted case.

18
New cards

[118 | Kotlin] Find the Kotlin error: open class Parent { fun greet() {} }; class Child : Parent() { override fun greet() {} }.

Parent is inheritable, but greet() is final by default. Declare open fun greet() in Parent before overriding it in Child. Opening a class does not automatically open its members.

19
New cards

[119 | Kotlin] How does defining show(Int) and show(String) differ from overriding an inherited show(Int)?

Different parameter lists create overloads. Overriding supplies a new implementation of an inherited, overridable function with the matching signature and requires override. Changing the parameter type alone does not override the original function.

20
New cards

[120 | Kotlin] Trace Kotlin: open class Base { open fun name() = "Base" }; class Child : Base() { override fun name() = "Child" }; val x: Base = Child(); print(x.name()).

It prints Child. An overridden member is dispatched according to the actual object, Child, even though the variable is declared as Base.

21
New cards

[121 | Kotlin] Trace Kotlin: open class Parent { init { print("P") } }; class Child : Parent() { init { print("C") } }. What does Child() print?

PC. Base-class initialization completes before the derived-class init block runs. The colon and Parent() invoke the superclass constructor.

22
New cards

[122 | Kotlin] Trace Kotlin: class Example { init { print("I") }; constructor() { print("S") } }. What does Example() print?

IS. The init block runs as part of object initialization before the secondary constructor body. It is not skipped just because a secondary constructor is used.

23
New cards

[123 | Kotlin] Trace Kotlin: class Demo { lateinit var title: String }; val d = Demo(); d.title = "A"; d.title = "B"; print(d.title).

It prints B. lateinit postpones the required first assignment; it does not make the property write-once or initialize it automatically. The property is still a var.

24
New cards

[124 | Kotlin] Trace Kotlin: var total = 0; for (n in arrayOf(2, 4, 6)) { if (n > 2) total += n }; print(total).

It prints 10. The loop visits the values 2, 4, and 6; only 4 and 6 satisfy n > 2. total must be var because the loop reassigns it.

25
New cards

[125 | Android Studio] Which Android Studio tool installs an Android platform package, and which creates a virtual device?

SDK Manager installs/manages SDK platforms and development tools. Device Manager creates/manages AVD configurations and their emulator instances. Installing an SDK platform alone does not create an AVD.

26
New cards

[126 | Android Studio] After changing a dependency in a Gradle build file, what does Sync do, and how is it different from Run?

Sync reads the build configuration, resolves dependencies, and updates Android Studio's project model. Run builds as needed, installs the app on the selected device, and launches it. A successful sync does not prove the app runs correctly.

27
New cards

[127 | Android Studio] A missing semicolon prevents a Java app from building; a null reference crashes a successfully launched app. Where should you inspect each failure?

Inspect the editor/build output for the Java compilation error. Inspect Logcat's exception and stack trace for the runtime crash. An app that cannot compile has not reached the failing runtime statement.

28
New cards

[128 | Android Studio] How do Cold Boot and Wipe Data differ when troubleshooting an AVD?

Cold Boot starts the emulator without restoring a saved running-state snapshot; it normally preserves installed apps and user data. Wipe Data resets the AVD's user data, removing installed apps and their stored data.

29
New cards

[129 | Android Studio] What extra information does Log.e("DB", "Insert failed", e) provide compared with Log.e("DB", "Insert failed")?

The three-argument overload also logs the Throwable e, including its stack trace. The two-argument call logs only the supplied tag and message.

30
New cards

[130 | Android Studio] How does Log.e("APP", "Problem") differ from throw new IllegalStateException("Problem")?

Log.e writes an ERROR-level message and normally lets execution continue. throw raises an exception and interrupts normal control flow; if uncaught, it can crash the app. Error severity alone does not mean a log statement throws.

31
New cards

[131 | Android Studio] What is ADB, and which command checks whether an emulator or connected physical device is recognized?

ADB means Android Debug Bridge, a command-line tool for communicating with Android devices. Use adb devices to list connected devices. It also supports tasks such as installing APKs and accessing logs; a USB-connected device must authorize debugging.

32
New cards

[132 | Components & Resources] What is a Fragment, and how does it relate to an Activity?

A Fragment represents a reusable portion of an app's UI and behavior hosted by an Activity or another Fragment. It has its own lifecycle, but it is not a fifth Android application component alongside Activities, Services, Receivers, and Providers.

33
New cards

[133 | Components & Resources] Complete the callback a BroadcastReceiver overrides to handle an incoming broadcast: public void ___(Context context, Intent intent).

onReceive. context supplies the receiving Context; intent describes the broadcast and may contain its action and extras. Keep this callback brief; the callback itself is not a long-running background service.

34
New cards

[134 | Components & Resources] res/values/ui.xml contains Hi. What Java and XML references access this string?

Java: R.string.welcome, or getString(R.string.welcome) for its text. XML: @string/welcome. The resource name comes from name="welcome", not the values file's name ui.xml.

35
New cards

[135 | Components & Resources] How do res/anim/ and res/animator/ differ, and what are the Java IDs for fade.xml in each folder?

res/anim/ holds view/tween animation resources, referenced as R.anim.fade. res/animator/ holds property animation resources, referenced as R.animator.fade. The resource type determines the R field.

36
New cards

[136 | Components & Resources] How would Java open assets/data/config.json compared with res/raw/config.json?

Assets: getAssets().open("data/config.json"), using AssetManager and the path inside assets. Raw resource: getResources().openRawResource(R.raw.config). Assets preserve filenames/subdirectories and do not receive R.raw IDs.

37
New cards

[137 | Components & Resources] Which intent-filter action and category identify an Activity as a launcher entry point?

android.intent.action.MAIN and android.intent.category.LAUNCHER. Merely declaring an Activity first in AndroidManifest.xml does not make it the launcher Activity. A launcher Activity should use android:exported="true" when an explicit exported setting is required.

38
New cards

[138 | Components & Resources] What does android.R.string.ok refer to, and what is its XML equivalent?

It refers to the Android framework's built-in OK string, not a string defined by your app. Its XML reference is @android:string/ok. App-owned resources normally use R.string.name and @string/name.

39
New cards

[139 | Components & Resources] A drawable image is named My-Logo.png. How should it be renamed for a normal file-based Android resource, and what Java ID would result?

For example, my_logo.png in res/drawable/. Use lowercase letters, digits, and underscores for the resource filename. The generated Java reference is R.drawable.my_logo, without the extension.

40
New cards

[140 | Components & Resources] An app has res/layout/main.xml and res/layout-land/main.xml. Which ID loads the suitable layout, and when is the second file selected?

Use R.layout.main in both orientations. Android selects the layout-land variant for landscape when it is the best match; the unqualified layout supplies the default. The qualifier does not create an R.layout_land type.

41
New cards

[141 | Activities] A resumed Activity rotates and Android uses normal configuration-change recreation. What happens to the old instance and the new instance?

Old instance: onPause() → onStop() → onDestroy(). New instance: onCreate() → onStart() → onResume(). This assumes no special configuration handling; the new screen is a new Activity object, even though it represents the same screen.

42
New cards

[142 | Activities] An Activity is launched for the first time with Intent extras. Why can onCreate(Bundle savedInstanceState) still receive null?

savedInstanceState contains previously saved instance state for recreation, not the incoming Intent extras. A fresh launch normally has no saved state. Read launch data from getIntent(); read restoration data from the saved-state Bundle when it is non-null.

43
New cards

[143 | Activities] Complete Java state handling: in onSaveInstanceState, outState.___("count", count); in onCreate, if (savedInstanceState != null) count = savedInstanceState.___("count", 0).

putInt and getInt. Override onSaveInstanceState(Bundle outState) and call super.onSaveInstanceState(outState) as well. The same key, "count", connects saving and restoration. This is for small instance/UI state, not permanent database storage.

44
New cards

[144 | Activities] What does Activity.isFinishing() tell you during destruction, and how does a normal rotation differ from finish()?

isFinishing() reports whether the Activity is finishing, such as after finish(). A normal configuration-change recreation is destruction without finishing, so isFinishing() is normally false; isChangingConfigurations() identifies that configuration-change case.

45
New cards

[145 | Activities] In a normal single-window launch, resumed Activity A opens a new opaque Activity B. What is the typical callback order across A and B?

A.onPause() → B.onCreate() → B.onStart() → B.onResume() → A.onStop(). A pauses before B resumes; A stops once B fully covers it. A is not automatically destroyed merely because B opened.

46
New cards

[146 | Activities] Activity A launches once, goes Home and returns, then is covered by a translucent Activity that only pauses A, and returns again. With no recreation, how many times do A's onCreate, onStart, and onResume run?

onCreate: 1; onStart: 2; onResume: 3. Returning from Home restarts the stopped instance, adding onStart and onResume. Returning from the pause-only interruption adds only onResume.

47
New cards

[147 | Activities] Why is a long download or heavy computation a poor fit for onPause()?

onPause() must finish quickly and normally runs on the main thread. Blocking it delays lifecycle transitions and can freeze the UI. Use appropriate background/asynchronous work instead of performing a long task directly inside the callback.

48
New cards

[148 | Activities] Why should app code not display a screen by doing new SecondActivity() and manually calling its onCreate()?

Android must create, attach, and manage an Activity through its framework. Use an Intent with startActivity(). A manually constructed object has not been properly attached to the system or given a managed window/lifecycle.

49
New cards

[149 | Android UI] Which units are normally appropriate for View dimensions and text sizes, and why?

Use dp for layout dimensions so sizes adapt to screen density. Use sp for text so text size adapts to density and the user's font-size preference. Fixed px values do not provide those adaptations.

50
New cards

[150 | Android UI] A LinearLayout has several children but no android:orientation attribute. What is its default orientation, and how would you stack children vertically?

The default is horizontal. Set android:orientation="vertical" in XML, or call layout.setOrientation(LinearLayout.VERTICAL) in Java, to arrange children in a vertical sequence.

51
New cards

[151 | Android UI] A horizontal LinearLayout has 300dp of available width. Its only two children have layout_width="0dp" and weights 1 and 2. With no margins or padding, how is the width divided?

100dp and 200dp. The total weight is 3, so the children receive 1/3 and 2/3 of the available width. The 0dp width lets weight allocate the horizontal space in this example.

52
New cards

[152 | Android UI] Two same-sized children overlap in a FrameLayout. With equal elevation and ordinary drawing order, which is drawn on top?

The child declared or added later is drawn on top. FrameLayout can layer multiple children; the later child does not automatically remove or replace the earlier child.

53
New cards

[153 | Android UI] In a GridLayout with at least three columns, a child has layout_row="0", layout_column="1", and layout_columnSpan="2". Which cells does it span?

The first row, spanning the second and third columns: column indexes 1 and 2. Row and column indexes start at 0; columnSpan is the number of columns occupied, not the final column index.

54
New cards

[154 | Android UI] The current layout contains a Button with ID submit. What happens in Java: EditText input = (EditText) findViewById(R.id.submit)?

The cast throws ClassCastException because the found object is a Button, not an EditText. This differs from a missing ID, which makes findViewById return null.

55
New cards

[155 | Android UI] Complete Kotlin inside an Activity after setContentView: val title = findViewById

TextView and text: val title = findViewById(R.id.title); title.text = "Ready". Kotlin's text property access calls the underlying TextView setter.

56
New cards

[156 | Android UI] An EditText uses android:inputType="number". What extra step is needed to add 1 to the entered number, and what input still needs checking?

Retrieve its text, convert the string to a number, then add: Integer.parseInt(input.getText().toString()) + 1. inputType influences input behavior but does not return an int. Check empty/invalid text to avoid NumberFormatException.

57
New cards

[157 | Android UI] Which listener handles a click on a ListView row, and how do you retrieve the clicked item using the supplied position?

Use setOnItemClickListener(...), whose callback receives parent, view, position, and id. Read parent.getItemAtPosition(position). position is the zero-based adapter position; it is not the clicked row's View resource ID.

58
New cards

[158 | Android UI] An ArrayAdapter uses the same mutable ArrayList referenced by items. After items.add("New") directly changes that list, what tells the displayed ListView to refresh?

Call adapter.notifyDataSetChanged(). It notifies observers that the adapter's data changed. Changing a different list that the adapter does not use would not update its data; use the adapter's actual backing data.

59
New cards

[159 | Android UI] A Button already belongs to layoutA. Why does layoutB.addView(button) fail, and how can you move that same Button?

A View cannot belong to two parents at once. Remove it first with layoutA.removeView(button), then add it to layoutB with appropriate LayoutParams. Alternatively, create a separate Button for the second parent.

60
New cards

[160 | Android UI] Trace Java: button.setOnClickListener(v -> label.setText("A")); button.setOnClickListener(v -> label.setText("B"));. What does a later click display?

B. setOnClickListener stores the current listener; the second call replaces the first. It does not register two separate click handlers to run in sequence.

61
New cards

[161 | Android UI] A normal Button has an OnClickListener, but its OnTouchListener returns true for every event and never calls performClick(). Why might tapping not invoke onClick?

The touch listener consumes the gesture before the Button's normal touch-to-click handling runs. Returning false allows normal handling to continue. If custom touch handling represents a click, performClick() can explicitly invoke click behavior.

62
New cards

[162 | Android UI] How do view.setVisibility(View.INVISIBLE) and view.setVisibility(View.GONE) differ?

Both hide the View. INVISIBLE keeps its allocated layout space; GONE removes that space from layout calculations. Neither call deletes the View object or removes it from its parent.

63
New cards

[163 | Intents] Which Intent action, MIME type, and extra are appropriate for sharing "Review now" with another app?

Use ACTION_SEND, type "text/plain", and EXTRA_TEXT. Java: Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_TEXT, "Review now"); startActivity(Intent.createChooser(i, "Share with"));

64
New cards

[164 | Intents] How do ACTION_DIAL and ACTION_CALL differ when the Intent data is a tel: URI?

ACTION_DIAL opens a dialer for the user to confirm the call and does not require CALL_PHONE permission. ACTION_CALL attempts to place the call directly and requires the appropriate CALL_PHONE permission, including runtime grant where applicable.

65
New cards

[165 | Intents] Why does adding putExtra("screen", "details") not by itself make an implicit Intent resolve to a particular Activity?

Implicit resolution matches the Intent's action, data/type, and categories against intent filters. Extras carry data for the eventual receiver; their keys and values are not used to choose the matching Activity.

66
New cards

[166 | Intents] Activity B was launched with putExtra("name", "Ana"). In B, why does new Intent().getStringExtra("name") return null?

new Intent() creates a different, empty Intent. Retrieve launch data from getIntent().getStringExtra("name") inside B. The incoming extras are not automatically copied into every Intent you construct.

67
New cards

[167 | Intents] Trace Java before launching: intent.putExtra("score", 4); intent.putExtra("score", 9);. What does getIntExtra("score", 0) read in the receiving Activity?

9. The second value replaces the earlier value under the same key. Extras are key/value mappings, not a list of every value ever assigned to a key.

68
New cards

[168 | Intents] A sends score=5 with startActivity(intent), then changes that local Intent to score=9. What score was sent to B, and does the later mutation update B automatically?

The launch sent score=5. Later changes to A's local Intent do not automatically update the already launched Activity. Extras transfer launch data; they are not a live shared variable between Activities.

69
New cards

[169 | Intents] A Bundle b contains name="Ana". How does reading data differ after i.putExtras(b) versus i.putExtra("payload", b)?

putExtras(b) merges b's entries into the Intent: getIntent().getStringExtra("name"). putExtra("payload", b) stores a nested Bundle: Bundle p = getIntent().getBundleExtra("payload"); then, if p != null, p.getString("name").

70
New cards

[170 | Intents] Why does getIntExtra("score", 0) alone not tell you whether a correctly typed score=0 was supplied, and what should you check?

Both a missing score and an explicitly supplied score of 0 can produce 0. Use getIntent().hasExtra("score") to test whether the key exists. Presence alone does not prove that its stored type is correct.

71
New cards

[171 | Intents] Compare getStringExtra("name") after putExtra("name", "") with the same getter when the name extra is absent.

The explicitly supplied empty string is "", with length 0; the absent String extra returns null. A null-only check will not reject an empty name. Java: name == null || name.isEmpty() handles both safely.

72
New cards

[172 | Notifications] Why is Toast.makeText(this, 5, Toast.LENGTH_SHORT).show() unsuitable for displaying the number 5?

The int overload interprets 5 as a string resource ID, not literal text, and may throw Resources.NotFoundException. Use "5" or String.valueOf(5), or pass a real string resource such as R.string.message.

73
New cards

[173 | Notifications] Why should you not pass 5000 as Toast.makeText(..., duration) to request exactly five seconds?

The duration parameter expects Toast.LENGTH_SHORT or Toast.LENGTH_LONG, not a millisecond count. The platform manages the display duration; this API does not provide an arbitrary exact duration.

74
New cards

[174 | Notifications] On Android 13/API 33+, what permission must an ordinary app obtain to post non-exempt system notifications?

POST_NOTIFICATIONS. Declare android.permission.POST_NOTIFICATIONS in the manifest and obtain the runtime grant when required. A valid channel and notification builder do not substitute for permission; Toasts do not use this notification permission.

75
New cards

[175 | Notifications] Permission is granted and a notification is built correctly, but its channel was disabled in system settings. Why may notify() produce no visible alert?

The user's channel settings control delivery/alerting; a blocked channel can suppress the notification. Apps must respect those settings. Correct builder code does not override a disabled app notification setting or channel.

76
New cards

[176 | Notifications] An app created channel "reminders" with low importance. Will recreating that same channel ID with high importance force it to become high?

No. After a channel is registered, the app cannot change its importance that way. The user controls the channel's importance through system settings. Recreating the same ID does not reset those choices.

77
New cards

[177 | Notifications] What does builder.setAutoCancel(true) do, and does it specify a timeout?

It requests that the notification dismiss automatically when the user taps it. It does not specify a duration or itself define an Activity to open; the tap action is configured separately, such as through setContentIntent().

78
New cards

[178 | Notifications] Which builder setting is useful when repeatedly updating a notification's progress without repeatedly triggering its sound/vibration?

setOnlyAlertOnce(true). It restricts alerting to the first posting while updates to the same notification can change its content. It does not prevent the notification from being updated.

79
New cards

[179 | Notifications] For ordinary notifications posted without tags, how do manager.cancel(7) and manager.cancelAll() differ?

cancel(7) removes this app's notification with ID 7. cancelAll() removes this app's posted notifications. Neither method deletes a notification channel or cancels notifications belonging to other apps.

80
New cards

[180 | Notifications] Which NotificationCompat style displays a longer body of text when a notification expands, and how is it attached?

NotificationCompat.BigTextStyle. Example: builder.setStyle(new NotificationCompat.BigTextStyle().bigText(longMessage));. BigTextStyle expands text content; it does not replace the required small icon or the call that posts the notification.

81
New cards

[181 | SQLite] How does SQLiteOpenHelper.onCreate(SQLiteDatabase db) differ from Activity.onCreate(Bundle state)?

The helper callback creates the schema when that database is first created. The Activity callback initializes each new Activity instance. Reopening a screen can call Activity.onCreate without recreating the database or calling the helper's onCreate again.

82
New cards

[182 | SQLite] After inserting a row into a normal on-disk SQLite database, the app closes the database and its Activity is destroyed. What should happen when the same database file is reopened?

Committed rows remain available. Closing the database or destroying an Activity does not delete the database file. Clearing the app's stored data normally removes that local database; an in-memory database has a different lifetime.

83
New cards

[183 | SQLite] Compare DELETE FROM students, DROP TABLE students, and db.close().

DELETE FROM students removes all rows but keeps the table definition. DROP TABLE students removes the table and its rows. db.close() releases the database connection/resources without deleting the table or its saved rows.

84
New cards

[184 | SQLite] Which method fits a CREATE TABLE statement, and which returns a Cursor for SELECT: db.execSQL(...) or db.rawQuery(...)?

execSQL() executes a statement that does not return a result set, such as CREATE TABLE. rawQuery() executes the supplied query SQL and returns a Cursor. execSQL() does not return query rows or an inserted-row ID.

85
New cards

[185 | SQLite] Row _id=3 has name="Ana", score=70. Interpret: ContentValues v = new ContentValues(); v.put("score", 90); int n = db.update("students", v, "_id = ?", new String[]{"3"});

The matching row's score becomes 90, while name remains Ana because it was not included in v. If exactly that one row matches, n is 1: the number of affected rows, not the new score or row ID.

86
New cards

[186 | SQLite] students has 20 rows. A Cursor runs SELECT COUNT(*) AS total FROM students. What do c.getCount() and, after moveToFirst(), c.getInt(c.getColumnIndexOrThrow("total")) return?

c.getCount() returns 1 because the aggregate query returns one result row. Reading its total column returns 20. The Cursor's number of result rows is different from a count stored inside one of those rows.

87
New cards

[187 | SQLite] The Cursor has no email column. How do c.getColumnIndex("email") and c.getColumnIndexOrThrow("email") behave?

getColumnIndex returns -1. getColumnIndexOrThrow throws IllegalArgumentException. Do not pass -1 into getString/getInt; select the needed column or handle its absence.

88
New cards

[188 | SQLite] A newly returned Cursor has five rows. Why is c.getCount(); c.getString(0); still unsafe?

getCount() reports the number of rows without moving the Cursor onto a row. It still begins before the first row. Call and check moveToFirst() or use a moveToNext() loop before reading values.

89
New cards

[189 | SQLite] A positioned Cursor came from SELECT age, name FROM students, and its row is age=21, name="Ana". What does c.getString(0) read?

The age column, represented as the string "21". Cursor column indexes are zero-based and follow the query's projected column order. Use the index for name, or getColumnIndexOrThrow("name"), to retrieve Ana.

90
New cards

[190 | SQLite] Interpret: SELECT name FROM students WHERE score >= 75 ORDER BY score DESC LIMIT 1. Assume passing scores are distinct.

It returns the name of the highest-scoring student among those scoring at least 75, or no rows if none qualify. WHERE filters rows, DESC sorts from highest to lowest, and LIMIT 1 keeps at most one result row.

91
New cards

[191 | JSON] In {"count":"3","active":true,"score":3}, what are the actual JSON value types of count, active, and score?

count is a string because "3" is quoted; active is a boolean; score is a number. A numeric-looking string is not a JSON number, even if a library getter can later convert it.

92
New cards

[192 | JSON] For {"age":21,"average":87.5,"passed":true}, which JSONObject getters retrieve age as int, average as double, and passed as boolean?

obj.getInt("age"), obj.getDouble("average"), and obj.getBoolean("passed"). Their return types differ from getString(), getJSONObject(), and getJSONArray(); a missing or incompatible value can cause JSONException.

93
New cards

[193 | JSON] Using Android org.json, obj contains {"score":80}. What does obj.getString("score") return?

The string "80". Android JSONObject.getString() can coerce a non-null value to a String; it does not always throw just because the stored JSON value was numeric. The original mapping remains a number.

94
New cards

[194 | JSON] How do obj.put("middle", JSONObject.NULL) and obj.put("middle", (Object) null) differ in Android org.json?

JSONObject.NULL stores an explicit JSON null under middle. Passing Java null to put removes the middle mapping if present. The sentinel JSONObject.NULL and the Java null reference have different meanings here.

95
New cards

[195 | JSON] For obj = {"middle":null}, compare has("middle"), isNull("middle"), has("missing"), and isNull("missing") in Android org.json.

They return true, true, false, and true. has() checks whether the key exists. isNull() is true for either a missing mapping or a value of JSONObject.NULL, so isNull() alone cannot distinguish those cases.

96
New cards

[196 | JSON] What does JSONObject.names() return for {"id":1,"name":"Ana"}, and what does it return for an empty JSONObject?

A JSONArray containing the keys id and name, with no guaranteed key order. It contains names, not values. For an empty object, Android JSONObject.names() returns null, so check before calling methods on the result.

97
New cards

[197 | JSON] What are JSONTokener and JSONStringer used for, and which is the correct Android org.json class name: JSONTokener or JSONTokenizer?

JSONTokener reads/parses JSON text into tokens and values; JSONStringer builds JSON text. JSONTokener is the correct class name. JSONObject and JSONArray model objects and arrays; JSONData is not one of these standard org.json classes.

98
New cards

[198 | JSON] JSONArray a represents the JSON ["Ana",{"scores":[5,9]},null]. Which getter chain returns the number 5?

a.getJSONObject(1).getJSONArray("scores").getInt(0). Index 1 selects the object, scores selects its array, and index 0 selects that array's first value. Root index 0 is a string, not the object.

99
New cards

[199 | JSON] Find the bug: for (int i = 0; i

Use i < a.length(). Valid indexes end at length() - 1; the

100
New cards

[200 | JSON] Trace Android org.json: JSONObject o = new JSONObject(); o.put("x", 1); o.put("x", 2); o.put("y", new JSONArray("[3,4]"));. What are o.length() and o.getInt("x")?

o.length() is 2 and o.getInt("x") is 2. The second put replaces x's earlier value instead of adding another key. The y array is one mapping, regardless of its two elements.