Skip to main content

Chapter 4

Mobile Programming

TU BCA past exam questions

Past questions and answers

59 questions set from this chapter, 1 of them more than once. Most repeated first.

  • Asked 2 times
  • 2021 · 5 marks
  • 2024 · 5 marks

Explain android architecture briefly with a suitable diagram.

Answer

Android is a layered, Linux-based software stack. From bottom to top:

+---------------------------------------------+
|              Applications                   |
|  (Home, Contacts, Browser, user apps)       |
+---------------------------------------------+
|          Application Framework              |
| Activity Mgr, Window Mgr, Content Providers,|
| View System, Notification Mgr, Resource Mgr |
+----------------------+----------------------+
|  Native Libraries    |   Android Runtime    |
| SQLite, OpenGL ES,   |  ART, core Java      |
| WebKit, SSL, libc,   |  libraries           |
| Media, Surface Mgr   |                      |
+----------------------+----------------------+
|        Hardware Abstraction Layer           |
+---------------------------------------------+
|              Linux Kernel                   |
| (drivers, memory, power, process, security) |
+---------------------------------------------+
  1. Linux kernel: the base layer. It provides device drivers (display, camera, Wi-Fi, audio), memory and process management, power management and security.
  2. Hardware abstraction layer (HAL): standard interfaces that expose hardware capabilities to the higher layers.
  3. Native libraries: C and C++ libraries such as SQLite (database), OpenGL ES (graphics), WebKit (browser engine), SSL, Media Framework and Surface Manager.
  4. Android runtime: ART (earlier Dalvik) runs the app bytecode, together with the core Java libraries.
  5. Application framework: Java and Kotlin APIs used by developers, such as Activity Manager, Content Providers, Resource Manager, Notification Manager and the View System.
  6. Applications: the top layer, with built-in apps and third-party apps installed by the user.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 10 marks

Develop an android application to display a list of students (student_name) in ListView and display the student details (roll, name and address) in a fragment when a ListView item is selected.

Similar questions: Develop an android application to display a (2024)

Answer

The main activity holds a ListView of student names and a container for a DetailFragment. When an item is selected, the fragment is created with the student's roll, name and address in a Bundle.

Student.java

public class Student {
    int roll;
    String name, address;
    public Student(int roll, String name, String address) {
        this.roll = roll;
        this.name = name;
        this.address = address;
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical">
    <ListView android:id="@+id/listStudents" android:layout_width="match_parent"
        android:layout_height="0dp" android:layout_weight="1"/>
    <FrameLayout android:id="@+id/detailContainer" android:layout_width="match_parent"
        android:layout_height="0dp" android:layout_weight="1"/>
</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        List<Student> students = new ArrayList<>();
        students.add(new Student(1, "Ram Sharma", "Kathmandu"));
        students.add(new Student(2, "Sita Thapa", "Pokhara"));
        students.add(new Student(3, "Hari Gurung", "Lalitpur"));
        students.add(new Student(4, "Gita Rai", "Bhaktapur"));

        List<String> names = new ArrayList<>();
        for (Student s : students) names.add(s.name);

        ListView list = findViewById(R.id.listStudents);
        list.setAdapter(new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, names));

        list.setOnItemClickListener((parent, view, position, id) -> {
            Student s = students.get(position);
            Bundle b = new Bundle();
            b.putInt("roll", s.roll);
            b.putString("name", s.name);
            b.putString("address", s.address);
            DetailFragment fragment = new DetailFragment();
            fragment.setArguments(b);
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.detailContainer, fragment)
                    .commit();
        });
    }
}

fragment_detail.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical" android:padding="16dp">
    <TextView android:id="@+id/tvRoll" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:textSize="18sp"/>
    <TextView android:id="@+id/tvName" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:textSize="18sp"/>
    <TextView android:id="@+id/tvAddress" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:textSize="18sp"/>
</LinearLayout>

DetailFragment.java

public class DetailFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle state) {
        View view = inflater.inflate(R.layout.fragment_detail, container, false);
        Bundle b = getArguments();
        if (b != null) {
            ((TextView) view.findViewById(R.id.tvRoll)).setText("Roll: " + b.getInt("roll"));
            ((TextView) view.findViewById(R.id.tvName)).setText("Name: " + b.getString("name"));
            ((TextView) view.findViewById(R.id.tvAddress))
                    .setText("Address: " + b.getString("address"));
        }
        return view;
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 · 10 marks

Develop an android application to display a list of Students (Student name) in ListView and display the student details (student image, roll, name, and college) in a Custom Dialog when a ListView item is selected.

Similar questions: Develop an android application to display a (2023)

Answer

Approach

A ListView shows student names. Clicking an item inflates a custom dialog layout containing an ImageView and three TextViews for image, roll, name and college.

activity_main.xml

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listView"
    android:layout_width="match_parent" android:layout_height="match_parent"/>

res/layout/dialog_student.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="wrap_content"
    android:orientation="vertical" android:padding="16dp" android:gravity="center_horizontal">
    <ImageView android:id="@+id/imgStudent"
        android:layout_width="120dp" android:layout_height="120dp"/>
    <TextView android:id="@+id/tvRoll"    android:layout_width="wrap_content" android:layout_height="wrap_content"/>
    <TextView android:id="@+id/tvName"    android:layout_width="wrap_content" android:layout_height="wrap_content"/>
    <TextView android:id="@+id/tvCollege" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    String[] names    = {"Ram Sharma", "Sita Thapa", "Hari Karki"};
    int[]    rolls    = {1, 2, 3};
    String[] colleges = {"Patan College", "Kathmandu College", "Pokhara College"};
    int[]    images   = {R.drawable.s1, R.drawable.s2, R.drawable.s3};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ListView listView = findViewById(R.id.listView);
        listView.setAdapter(new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, names));

        listView.setOnItemClickListener((parent, view, position, id) -> {
            Dialog dialog = new Dialog(MainActivity.this);
            dialog.setContentView(R.layout.dialog_student);
            dialog.setTitle("Student Details");

            ((ImageView) dialog.findViewById(R.id.imgStudent)).setImageResource(images[position]);
            ((TextView) dialog.findViewById(R.id.tvRoll)).setText("Roll: " + rolls[position]);
            ((TextView) dialog.findViewById(R.id.tvName)).setText("Name: " + names[position]);
            ((TextView) dialog.findViewById(R.id.tvCollege)).setText("College: " + colleges[position]);
            dialog.show();
        });
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2021 · 5 marks

What do you mean by mobile device? List and explain any four popular programming languages used for developing mobile applications.

Answer

Mobile device

A mobile device is a small, portable, battery-powered computing device that can be carried and used anywhere, usually with wireless connectivity. Examples are smartphones, tablets, smartwatches, e-readers and PDAs.

Programming languages for mobile applications

  1. Java: the original language of Android development. It is object oriented and has a huge library ecosystem, and it runs on the Android runtime.
  2. Kotlin: a modern, concise and null-safe language, fully interoperable with Java. Google has made it the preferred language for Android.
  3. Swift: Apple's language for iOS, iPadOS, macOS and watchOS. It is fast, safe and has a clean syntax. It replaced Objective-C for new apps.
  4. Objective-C: the older language of Apple platforms, a C superset with Smalltalk-style messaging, still found in legacy iOS code.

Other options are Dart (with Flutter), JavaScript (React Native) and C# (Xamarin or .NET MAUI) for cross-platform apps.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2021 · 5 marks

What is an event? How many ways to handle events in android programming?

Answer

Event

An event is an action or occurrence, usually caused by the user, that the application can detect and respond to. Examples are clicking a button, touching or long-pressing the screen, pressing a key, or changing text in a field.

Ways to handle events in Android

  1. Event listeners (programmatic): get the view with findViewById() and register a listener interface such as View.OnClickListener, OnLongClickListener or OnTouchListener.
Button b = findViewById(R.id.btn);
b.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) { /* handle */ }
});
  1. Activity implements the listener interface: the activity itself implements View.OnClickListener and overrides onClick(View v), then calls b.setOnClickListener(this).

  2. Lambda expression: b.setOnClickListener(v -> { ... });

  3. XML android:onClick attribute: write android:onClick="doSomething" in the layout and define public void doSomething(View v) in the activity.

  4. Event handlers (overriding callbacks): override methods of the view or activity, such as onKeyDown(), onTouchEvent() or onBackPressed().

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2021 · 5 marks

Why is fragment needed in android application? How can a fragment be added to an activity?

Answer

Why fragments are needed

A fragment is a modular portion of the user interface with its own layout and lifecycle, hosted inside an activity. Fragments are needed because they:

  • let one UI be reused in several activities;
  • support flexible layouts for different screen sizes, for example two panes (list and detail) on a tablet and one pane on a phone;
  • make a large activity easier to manage by splitting it into smaller parts;
  • allow adding, removing or replacing parts of the screen dynamically at run time, with a back stack.

Adding a fragment to an activity

Statically, in the layout XML:

<fragment
    android:id="@+id/frag1"
    android:name="com.example.app.MyFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Dynamically, in code (the layout holds a container such as FrameLayout with id container):

FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.container, new MyFragment());
ft.addToBackStack(null);
ft.commit();

The fragment class extends Fragment and returns its view from onCreateView() using the LayoutInflater.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2021 · 5 marks

What are different types of UI controls used in IOS programming? Write a swift program to find the sum of all elements of a 1-D array.

Answer

UI controls in iOS (UIKit)

  • UILabel: displays read-only text.
  • UIButton: triggers an action when tapped.
  • UITextField and UITextView: accept single-line and multi-line text input.
  • UISwitch: an on/off toggle.
  • UISlider: selects a value from a continuous range.
  • UISegmentedControl: chooses one option from a set of segments.
  • UIStepper: increments or decrements a value.
  • UIPickerView and UIDatePicker: select values or dates by scrolling.
  • UIImageView: shows images.
  • UITableView and UICollectionView: show lists and grids.
  • UIPageControl, UIActivityIndicatorView and UIProgressView: show page position and progress.

Swift program: sum of a 1-D array

let numbers = [10, 20, 30, 40, 50]
var sum = 0
for n in numbers {
    sum += n
}
print("Sum = \(sum)")      // Sum = 150
// Alternative: let total = numbers.reduce(0, +)

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2021 · 5 marks

How is List View differ from Recycler View? Explain with an example.

Answer

ListView vs RecyclerView

PointListViewRecyclerView
View reuseOptional, done by hand with the convertView and ViewHolder patternView recycling is built in and required (ViewHolder)
LayoutVertical list onlyAny layout through a LayoutManager: linear, grid, staggered
AdapterBaseAdapter / ArrayAdapterRecyclerView.Adapter
AnimationsLimitedItemAnimator supports item animations
PerformanceSlower with large listsBetter for large data sets
Item clickBuilt-in setOnItemClickListenerMust be implemented in the adapter or ViewHolder
DividersBuilt-inNeeds ItemDecoration

Example (RecyclerView)

RecyclerView rv = findViewById(R.id.rv);
rv.setLayoutManager(new LinearLayoutManager(this));
rv.setAdapter(new MyAdapter(Arrays.asList("Java", "Kotlin", "Swift")));

class MyAdapter extends RecyclerView.Adapter<MyAdapter.VH> {
    List<String> data;
    MyAdapter(List<String> d) { data = d; }
    static class VH extends RecyclerView.ViewHolder {
        TextView tv;
        VH(View v) { super(v); tv = v.findViewById(android.R.id.text1); }
    }
    public VH onCreateViewHolder(ViewGroup p, int type) {
        View v = LayoutInflater.from(p.getContext())
            .inflate(android.R.layout.simple_list_item_1, p, false);
        return new VH(v);
    }
    public void onBindViewHolder(VH h, int i) { h.tv.setText(data.get(i)); }
    public int getItemCount() { return data.size(); }
}

The same list in a ListView would be listView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, data));.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2021 · 5 marks

How do you find a view element in your program? Which dialog boxes can you use in your android application?

Answer

Finding a view element

A view declared in the layout XML with an android:id is found in the activity with findViewById(), after setContentView() has been called:

setContentView(R.layout.activity_main);
EditText name = findViewById(R.id.etName);
Button btn = findViewById(R.id.btnOk);

The XML declares the id as android:id="@+id/etName". Alternatives are View Binding (binding.etName) and, in Kotlin, synthetic or binding properties.

Dialog boxes in Android

  1. AlertDialog: shows a title, message and up to three buttons (positive, negative, neutral), or a list of items. It is built with AlertDialog.Builder.
  2. DatePickerDialog: lets the user pick a date.
  3. TimePickerDialog: lets the user pick a time.
  4. ProgressDialog: shows progress (deprecated; ProgressBar is preferred).
  5. Custom dialog: a Dialog or AlertDialog with a custom layout inflated into it.
  6. DialogFragment: a fragment-based dialog that survives configuration changes.
new AlertDialog.Builder(this)
    .setTitle("Exit")
    .setMessage("Are you sure?")
    .setPositiveButton("Yes", (d, w) -> finish())
    .setNegativeButton("No", null)
    .show();

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2021 · 10 marks

Provided that a SQLite database named "College" with a table named Student with the following columns (Roll as Integer, Name as Text and Address as Text). Develop an android application to connect to the database and insert five student records and display the student information.

Answer

The application uses a SQLiteOpenHelper subclass to create the College database with the Student table. The activity inserts five records through the helper and then reads them back with a cursor to display them in a TextView.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical" android:padding="16dp">
    <Button android:id="@+id/btnInsert" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:text="Insert 5 Records"/>
    <Button android:id="@+id/btnShow" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:text="Display Students"/>
    <TextView android:id="@+id/tvResult" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:textSize="16sp"/>
</LinearLayout>

DBHelper.java

public class DBHelper extends SQLiteOpenHelper {
    public DBHelper(Context context) {
        super(context, "College", null, 1);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE Student(Roll INTEGER PRIMARY KEY, Name TEXT, Address TEXT)");
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
        db.execSQL("DROP TABLE IF EXISTS Student");
        onCreate(db);
    }
    public boolean insertStudent(int roll, String name, String address) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("Roll", roll);
        cv.put("Name", name);
        cv.put("Address", address);
        return db.insert("Student", null, cv) != -1;
    }
    public Cursor getAllStudents() {
        return getReadableDatabase().rawQuery("SELECT * FROM Student", null);
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {
    DBHelper helper;
    TextView tvResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        helper = new DBHelper(this);
        tvResult = findViewById(R.id.tvResult);

        findViewById(R.id.btnInsert).setOnClickListener(v -> {
            helper.insertStudent(1, "Ram Sharma", "Kathmandu");
            helper.insertStudent(2, "Sita Thapa", "Pokhara");
            helper.insertStudent(3, "Hari Gurung", "Lalitpur");
            helper.insertStudent(4, "Gita Rai", "Bhaktapur");
            helper.insertStudent(5, "Shyam Karki", "Butwal");
            Toast.makeText(this, "5 records inserted", Toast.LENGTH_SHORT).show();
        });

        findViewById(R.id.btnShow).setOnClickListener(v -> {
            Cursor c = helper.getAllStudents();
            StringBuilder sb = new StringBuilder();
            while (c.moveToNext()) {
                sb.append("Roll: ").append(c.getInt(0))
                  .append("\nName: ").append(c.getString(1))
                  .append("\nAddress: ").append(c.getString(2))
                  .append("\n\n");
            }
            c.close();
            tvResult.setText(sb.toString());
        });
    }
}

Roll is the primary key, so pressing the insert button a second time fails silently (insert() returns -1) instead of duplicating rows.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2021 · 10 marks

Develop an android application to calculate simple interest using a customize dialog box.

Answer

The simple interest is SI=P×T×R100SI = \dfrac{P \times T \times R}{100}. A custom dialog layout holds three EditText fields (principal, time, rate); the dialog's button computes the interest and shows it.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:gravity="center" android:orientation="vertical">
    <Button android:id="@+id/btnOpen" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="Calculate Simple Interest"/>
    <TextView android:id="@+id/tvResult" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_marginTop="20dp"
        android:textSize="18sp"/>
</LinearLayout>

dialog_interest.xml (custom dialog layout)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="wrap_content"
    android:orientation="vertical" android:padding="16dp">
    <EditText android:id="@+id/etPrincipal" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:hint="Principal (Rs)"
        android:inputType="numberDecimal"/>
    <EditText android:id="@+id/etTime" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:hint="Time (years)"
        android:inputType="numberDecimal"/>
    <EditText android:id="@+id/etRate" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:hint="Rate (%)"
        android:inputType="numberDecimal"/>
    <Button android:id="@+id/btnCalc" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:text="Calculate"/>
</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView tvResult = findViewById(R.id.tvResult);

        findViewById(R.id.btnOpen).setOnClickListener(v -> {
            Dialog dialog = new Dialog(MainActivity.this);
            dialog.setContentView(R.layout.dialog_interest);
            dialog.setTitle("Simple Interest");

            EditText etP = dialog.findViewById(R.id.etPrincipal);
            EditText etT = dialog.findViewById(R.id.etTime);
            EditText etR = dialog.findViewById(R.id.etRate);
            Button btnCalc = dialog.findViewById(R.id.btnCalc);

            btnCalc.setOnClickListener(view -> {
                String p = etP.getText().toString();
                String t = etT.getText().toString();
                String r = etR.getText().toString();
                if (p.isEmpty() || t.isEmpty() || r.isEmpty()) {
                    Toast.makeText(MainActivity.this, "Fill all fields",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                double si = Double.parseDouble(p) * Double.parseDouble(t)
                        * Double.parseDouble(r) / 100;
                tvResult.setText("Simple Interest = Rs " + si);
                dialog.dismiss();
            });
            dialog.show();
        });
    }
}

For example, P=10000P = 10000, T=2T = 2, R=5R = 5 gives SI=10000×2×5100=1000SI = \dfrac{10000 \times 2 \times 5}{100} = 1000, so the result shows Rs 1000.0.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2021 · 10 marks

Develop an android application to input your Name, Age, gender and other personal information. Pass and display this information in another activity.

Answer

The first activity collects the data and passes it to the second activity in an Intent using extras. The second activity reads the extras and displays them.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical" android:padding="16dp">
    <EditText android:id="@+id/etName" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:hint="Name"/>
    <EditText android:id="@+id/etAge" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:hint="Age" android:inputType="number"/>
    <RadioGroup android:id="@+id/rgGender" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:orientation="horizontal">
        <RadioButton android:id="@+id/rbMale" android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:text="Male" android:checked="true"/>
        <RadioButton android:id="@+id/rbFemale" android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:text="Female"/>
        <RadioButton android:id="@+id/rbOther" android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:text="Other"/>
    </RadioGroup>
    <EditText android:id="@+id/etAddress" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:hint="Address"/>
    <EditText android:id="@+id/etPhone" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:hint="Phone" android:inputType="phone"/>
    <EditText android:id="@+id/etEmail" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:hint="Email"
        android:inputType="textEmailAddress"/>
    <Button android:id="@+id/btnSubmit" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:text="Submit"/>
</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        EditText etName = findViewById(R.id.etName);
        EditText etAge = findViewById(R.id.etAge);
        EditText etAddress = findViewById(R.id.etAddress);
        EditText etPhone = findViewById(R.id.etPhone);
        EditText etEmail = findViewById(R.id.etEmail);
        RadioGroup rgGender = findViewById(R.id.rgGender);

        findViewById(R.id.btnSubmit).setOnClickListener(v -> {
            RadioButton rb = findViewById(rgGender.getCheckedRadioButtonId());
            Intent intent = new Intent(MainActivity.this, DetailActivity.class);
            intent.putExtra("name", etName.getText().toString());
            intent.putExtra("age", etAge.getText().toString());
            intent.putExtra("gender", rb.getText().toString());
            intent.putExtra("address", etAddress.getText().toString());
            intent.putExtra("phone", etPhone.getText().toString());
            intent.putExtra("email", etEmail.getText().toString());
            startActivity(intent);
        });
    }
}

activity_detail.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical" android:padding="16dp">
    <TextView android:id="@+id/tvInfo" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:textSize="18sp"/>
</LinearLayout>

DetailActivity.java

public class DetailActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);

        Intent intent = getIntent();
        String info = "Name: " + intent.getStringExtra("name")
                + "\nAge: " + intent.getStringExtra("age")
                + "\nGender: " + intent.getStringExtra("gender")
                + "\nAddress: " + intent.getStringExtra("address")
                + "\nPhone: " + intent.getStringExtra("phone")
                + "\nEmail: " + intent.getStringExtra("email");
        ((TextView) findViewById(R.id.tvInfo)).setText(info);
    }
}

AndroidManifest.xml (inside <application>; the new activity must be declared)

<activity android:name=".DetailActivity"/>

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 5 marks

What is a smart mobile device? Explain different platforms used in mobile devices.

Answer

Smart mobile device. A smart mobile device is a portable, handheld computing device with a mobile operating system, a touchscreen, wireless connectivity (Wi-Fi, cellular, Bluetooth, GPS) and sensors (accelerometer, gyroscope, camera, proximity). Unlike a basic feature phone, it can install and run third-party applications, browse the internet, and carry out computing tasks. Smartphones, tablets and smartwatches are examples.

Mobile platforms.

  • Android: Open-source platform from Google, based on the Linux kernel. Apps are written in Java or Kotlin and distributed through Google Play. It has the largest market share and runs on devices from many manufacturers.
  • iOS: Apple's closed platform for iPhone and iPad, derived from macOS (Darwin/Unix). Apps are written in Swift or Objective-C using Xcode and distributed through the App Store. It is known for tight hardware-software integration and strict app review.
  • HarmonyOS: Huawei's distributed operating system, designed to run across phones, wearables and smart-home devices. Early versions were compatible with Android apps.
  • Windows Phone / Windows Mobile: Microsoft's mobile platform using .NET and C#. It has been discontinued but is part of the history of mobile platforms.
  • BlackBerry OS: Early enterprise-oriented platform, known for secure email and physical keyboards. It is now discontinued.
  • Symbian, KaiOS, Tizen: Symbian was the leading platform of the feature-phone era (Nokia). KaiOS is a lightweight web-based OS for feature phones. Tizen is a Linux-based OS used by Samsung on watches and TVs.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 5 marks

What is a surface manager library? How DVM is different from ART?

Answer

Surface Manager. The Surface Manager is a native C/C++ library in the Android libraries layer (also called SurfaceFlinger). It composes the drawing surfaces of all running applications into one final image and sends it to the display. It combines 2D and 3D graphics, handles transparency and window ordering, and uses double buffering so the screen is updated without flicker. It also provides access to the display subsystem and lets many apps share the screen.

DVM versus ART.

BasisDVM (Dalvik Virtual Machine)ART (Android Runtime)
CompilationJust-In-Time (JIT): bytecode is compiled while the app runsAhead-Of-Time (AOT): bytecode is compiled to native code at install time (later versions mix AOT, JIT and profile-guided compilation)
Execution speedSlower, because compilation happens at run timeFaster, because native code runs directly
App start-upFaster install, slower start-upSlower install, faster start-up
StorageNeeds less spaceNeeds more space for the compiled code
BatteryUses more CPU at run time, so more powerLess run-time work, so better battery life
Garbage collectionPauses the app more oftenImproved, with fewer pauses
IntroducedUsed up to Android 4.4Default from Android 5.0 (Lollipop)

Both run .dex (Dalvik Executable) files produced from the Java/Kotlin bytecode.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 5 marks

What are important attributes used in Absolute Layout? Develop a simple calculator application with two input fields for inputting numbers and two buttons for performing multiplication and division and display the result in TextView using Absolute Layout.

Answer

Important attributes of AbsoluteLayout. AbsoluteLayout places each child at an exact coordinate. It is deprecated since API level 3 because the layout does not adapt to different screen sizes.

  • android:layout_x: x-coordinate (horizontal position) of the child, for example 50dp.
  • android:layout_y: y-coordinate (vertical position) of the child.
  • android:layout_width and android:layout_height: size of the child (wrap_content, match_parent or a fixed size).

Calculator application

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <EditText android:id="@+id/etNum1" android:layout_width="200dp"
        android:layout_height="wrap_content" android:layout_x="50dp"
        android:layout_y="40dp" android:hint="First number"
        android:inputType="numberDecimal|numberSigned"/>

    <EditText android:id="@+id/etNum2" android:layout_width="200dp"
        android:layout_height="wrap_content" android:layout_x="50dp"
        android:layout_y="110dp" android:hint="Second number"
        android:inputType="numberDecimal|numberSigned"/>

    <Button android:id="@+id/btnMul" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_x="40dp"
        android:layout_y="190dp" android:text="Multiply"/>

    <Button android:id="@+id/btnDiv" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_x="170dp"
        android:layout_y="190dp" android:text="Divide"/>

    <TextView android:id="@+id/tvResult" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_x="50dp"
        android:layout_y="270dp" android:textSize="20sp" android:text="Result"/>
</AbsoluteLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    EditText etNum1, etNum2;
    TextView tvResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        etNum1 = findViewById(R.id.etNum1);
        etNum2 = findViewById(R.id.etNum2);
        tvResult = findViewById(R.id.tvResult);

        findViewById(R.id.btnMul).setOnClickListener(v -> {
            if (!valid()) return;
            double a = Double.parseDouble(etNum1.getText().toString());
            double b = Double.parseDouble(etNum2.getText().toString());
            tvResult.setText("Product = " + (a * b));
        });

        findViewById(R.id.btnDiv).setOnClickListener(v -> {
            if (!valid()) return;
            double a = Double.parseDouble(etNum1.getText().toString());
            double b = Double.parseDouble(etNum2.getText().toString());
            if (b == 0) {
                tvResult.setText("Cannot divide by zero");
            } else {
                tvResult.setText("Quotient = " + (a / b));
            }
        });
    }

    private boolean valid() {
        if (etNum1.getText().toString().isEmpty()
                || etNum2.getText().toString().isEmpty()) {
            tvResult.setText("Enter both numbers");
            return false;
        }
        return true;
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 5 marks

What is the difference between activity and fragment? Develop an android application to create a user interface for input length, width, and height of a Rectangular box and Button for Volume in one fragment when the button is clicked then these input data are passed into the second fragment and calculate the volume of the Rectangular box and display the result in TextView.

Answer

Activity versus fragment.

ActivityFragment
A single screen with a user interface; a core application component declared in the manifestA reusable portion of the UI that lives inside an activity
Can exist on its ownCannot exist on its own; it needs a host activity
Declared in AndroidManifest.xmlNot declared in the manifest
Managed by the system back stackManaged by the FragmentManager of the host activity
One activity shows one screen layoutOne activity can host many fragments, and a fragment can be reused in many activities
Has its own lifecycleHas its own lifecycle that depends on the host activity's lifecycle

Volume of a box using two fragments. The first fragment takes length, width and height; the button sends them to the second fragment in a Bundle, which computes V=l×w×hV = l \times w \times h.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent" android:layout_height="match_parent"/>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.container, new InputFragment())
                    .commit();
        }
    }
}

fragment_input.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical" android:padding="16dp">
    <EditText android:id="@+id/etLength" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:hint="Length"
        android:inputType="numberDecimal"/>
    <EditText android:id="@+id/etWidth" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:hint="Width"
        android:inputType="numberDecimal"/>
    <EditText android:id="@+id/etHeight" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:hint="Height"
        android:inputType="numberDecimal"/>
    <Button android:id="@+id/btnVolume" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:text="Volume"/>
</LinearLayout>

InputFragment.java

public class InputFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle state) {
        View view = inflater.inflate(R.layout.fragment_input, container, false);
        EditText etL = view.findViewById(R.id.etLength);
        EditText etW = view.findViewById(R.id.etWidth);
        EditText etH = view.findViewById(R.id.etHeight);

        view.findViewById(R.id.btnVolume).setOnClickListener(v -> {
            if (etL.getText().toString().isEmpty() || etW.getText().toString().isEmpty()
                    || etH.getText().toString().isEmpty()) {
                Toast.makeText(getContext(), "Enter all values", Toast.LENGTH_SHORT).show();
                return;
            }
            Bundle b = new Bundle();
            b.putDouble("length", Double.parseDouble(etL.getText().toString()));
            b.putDouble("width", Double.parseDouble(etW.getText().toString()));
            b.putDouble("height", Double.parseDouble(etH.getText().toString()));
            ResultFragment result = new ResultFragment();
            result.setArguments(b);
            requireActivity().getSupportFragmentManager().beginTransaction()
                    .replace(R.id.container, result)
                    .addToBackStack(null)
                    .commit();
        });
        return view;
    }
}

fragment_result.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:gravity="center" android:orientation="vertical">
    <TextView android:id="@+id/tvVolume" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:textSize="22sp"/>
</LinearLayout>

ResultFragment.java

public class ResultFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle state) {
        View view = inflater.inflate(R.layout.fragment_result, container, false);
        TextView tv = view.findViewById(R.id.tvVolume);
        Bundle b = getArguments();
        if (b != null) {
            double volume = b.getDouble("length") * b.getDouble("width")
                    * b.getDouble("height");
            tv.setText("Volume = " + volume + " cubic units");
        }
        return view;
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 5 marks

What is Toast? Develop an android application to create an alert dialog to input any number and then calculate the factorial of the number and display the result in Toast.

Answer

Toast. A Toast is a small, non-modal message that pops up briefly at the bottom of the screen and disappears automatically. It does not take focus and needs no user action. It is created with Toast.makeText(context, message, duration).show(), where the duration is Toast.LENGTH_SHORT (about 2 seconds) or Toast.LENGTH_LONG (about 3.5 seconds).

Factorial application. A button opens an AlertDialog containing an EditText. On OK, the factorial is computed and shown in a Toast.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:gravity="center">
    <Button android:id="@+id/btnOpen" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="Enter a Number"/>
</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.btnOpen).setOnClickListener(v -> {
            EditText input = new EditText(this);
            input.setInputType(InputType.TYPE_CLASS_NUMBER);
            input.setHint("Number (0 to 20)");

            new AlertDialog.Builder(this)
                    .setTitle("Factorial")
                    .setMessage("Enter a non-negative integer")
                    .setView(input)
                    .setPositiveButton("OK", (dialog, which) -> {
                        String s = input.getText().toString();
                        if (s.isEmpty()) {
                            Toast.makeText(this, "Please enter a number",
                                    Toast.LENGTH_SHORT).show();
                            return;
                        }
                        int n = Integer.parseInt(s);
                        if (n > 20) {
                            Toast.makeText(this, "Enter a number up to 20",
                                    Toast.LENGTH_SHORT).show();
                            return;
                        }
                        long fact = 1;
                        for (int i = 2; i <= n; i++) {
                            fact *= i;
                        }
                        Toast.makeText(this, n + "! = " + fact,
                                Toast.LENGTH_LONG).show();
                    })
                    .setNegativeButton("Cancel", null)
                    .show();
        });
    }
}

The limit of 20 is used because 21!21! overflows a Java long. For input 5 the Toast shows 5! = 120.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 5 marks

What are different data types supported by SQLite? How to decode JSON data in an android application? Explain with a suitable example.

Answer

Data types in SQLite. SQLite is dynamically typed and uses storage classes:

  • NULL: a missing value.
  • INTEGER: a signed integer stored in 1 to 8 bytes.
  • REAL: an 8-byte floating-point number.
  • TEXT: a string stored as UTF-8 or UTF-16.
  • BLOB: binary data stored exactly as given, for example an image.

Declared types such as VARCHAR, BOOLEAN or DATE are mapped to one of these classes by type affinity. Booleans are stored as the integers 0 and 1, and dates as TEXT, REAL or INTEGER.

Decoding JSON in Android. The built-in org.json package is used. JSONObject represents { } and JSONArray represents [ ]. The string is parsed by passing it to the constructor, then values are read with getString(), getInt(), getJSONArray() and similar methods.

Example JSON:

{
  "college": "ABC College",
  "students": [
    {"roll": 1, "name": "Ram"},
    {"roll": 2, "name": "Sita"}
  ]
}

Decoding code:

String json = "{\"college\":\"ABC College\",\"students\":["
        + "{\"roll\":1,\"name\":\"Ram\"},{\"roll\":2,\"name\":\"Sita\"}]}";
try {
    JSONObject root = new JSONObject(json);
    String college = root.getString("college");
    JSONArray students = root.getJSONArray("students");
    StringBuilder sb = new StringBuilder("College: " + college + "\n");
    for (int i = 0; i < students.length(); i++) {
        JSONObject s = students.getJSONObject(i);
        sb.append(s.getInt("roll")).append(" - ")
          .append(s.getString("name")).append("\n");
    }
    textView.setText(sb.toString());
} catch (JSONException e) {
    e.printStackTrace();
}

The output shown in the TextView is the college name followed by 1 - Ram and 2 - Sita. Parsing must be inside a try/catch because JSONException is a checked exception.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 5 marks

What do you mean by View hierarchy in IOS programming? Write a swift program to find the sum of all elements of a 1-D array.

Answer

View hierarchy in iOS. Every screen in an iOS app is built as a tree of views. The root is a UIWindow, which holds the view controller's root UIView. That view contains subviews (labels, buttons, image views, table views, stack views), and each of those can contain more subviews. A view has exactly one parent (its superview) and any number of children (subviews). The hierarchy decides three things:

  • Drawing order: a child is drawn on top of its parent, and later siblings are drawn above earlier ones.
  • Coordinates: a subview's frame is expressed in its superview's coordinate system, so moving a parent moves all its children.
  • Event handling: touches are passed down the tree by hit-testing and up the responder chain.

Views are added in code with addSubview(_:) or in Interface Builder (storyboard).

Swift program: sum of a 1-D array

let numbers = [10, 20, 30, 40, 50]

var sum = 0
for n in numbers {
    sum += n
}
print("Sum of the elements = \(sum)")

// The same result using reduce
let total = numbers.reduce(0, +)
print("Sum using reduce = \(total)")

Output:

Sum of the elements = 150
Sum using reduce = 150

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 10 marks

What is the difference between ArrayAdapter and CursorAdapter? Develop an android application to display the application name with logo (i.e., YouTube, Facebook, Twitter, Tiktok, Snapchat, Telegram etc.) in Grid View and display their site in another activity when a Grid View item is clicked.

Answer

ArrayAdapter versus CursorAdapter.

ArrayAdapterCursorAdapter
Binds an array or List of objects to a list-type viewBinds the rows of a database Cursor to a list-type view
Data source is in memory (String[], ArrayList)Data source is a database query result (SQLite or ContentProvider)
Uses getView(), with toString() of each item for the default textUses newView() to create a row and bindView() to fill it
The cursor needs no _id columnThe cursor must contain an _id column
Suitable for small static dataSuitable for database data that can change

Grid of applications. A GridView shows each app's logo and name. Clicking an item starts a second activity that opens the app's website in a WebView. The logos are image files placed in res/drawable (youtube.png, facebook.png, and so on).

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridView" android:layout_width="match_parent"
    android:layout_height="match_parent" android:numColumns="2"
    android:horizontalSpacing="8dp" android:verticalSpacing="8dp"
    android:padding="8dp"/>

grid_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="wrap_content"
    android:gravity="center" android:orientation="vertical" android:padding="8dp">
    <ImageView android:id="@+id/imgLogo" android:layout_width="72dp"
        android:layout_height="72dp"/>
    <TextView android:id="@+id/tvName" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:textSize="16sp"/>
</LinearLayout>

AppAdapter.java

public class AppAdapter extends BaseAdapter {
    private final Context context;
    private final String[] names;
    private final int[] logos;

    public AppAdapter(Context context, String[] names, int[] logos) {
        this.context = context;
        this.names = names;
        this.logos = logos;
    }
    @Override public int getCount() { return names.length; }
    @Override public Object getItem(int position) { return names[position]; }
    @Override public long getItemId(int position) { return position; }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(context)
                    .inflate(R.layout.grid_item, parent, false);
        }
        ((ImageView) convertView.findViewById(R.id.imgLogo)).setImageResource(logos[position]);
        ((TextView) convertView.findViewById(R.id.tvName)).setText(names[position]);
        return convertView;
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {
    String[] names = {"YouTube", "Facebook", "Twitter", "TikTok", "Snapchat", "Telegram"};
    String[] sites = {"https://www.youtube.com", "https://www.facebook.com",
            "https://www.twitter.com", "https://www.tiktok.com",
            "https://www.snapchat.com", "https://web.telegram.org"};
    int[] logos = {R.drawable.youtube, R.drawable.facebook, R.drawable.twitter,
            R.drawable.tiktok, R.drawable.snapchat, R.drawable.telegram};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        GridView grid = findViewById(R.id.gridView);
        grid.setAdapter(new AppAdapter(this, names, logos));
        grid.setOnItemClickListener((parent, view, position, id) -> {
            Intent intent = new Intent(MainActivity.this, WebActivity.class);
            intent.putExtra("title", names[position]);
            intent.putExtra("url", sites[position]);
            startActivity(intent);
        });
    }
}

activity_web.xml

<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webView" android:layout_width="match_parent"
    android:layout_height="match_parent"/>

WebActivity.java

public class WebActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        setTitle(getIntent().getStringExtra("title"));
        WebView web = findViewById(R.id.webView);
        web.getSettings().setJavaScriptEnabled(true);
        web.setWebViewClient(new WebViewClient());
        web.loadUrl(getIntent().getStringExtra("url"));
    }
}

AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>
<!-- inside <application> -->
<activity android:name=".WebActivity"/>

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 10 marks

Why we use API in android? Provided that SQLite database named "Hospital" with table named Doctor with the following columns (Did as Integer, Dname as Text, and Specialization as Text and Experience as Real). Develop an android application to connect to the database and insert records of Doctor and display the Doctor information whose experience is less than 5.5 years.

Answer

Why APIs are used in Android. An API (Application Programming Interface) is a defined set of classes, methods and rules that lets one piece of software use the services of another without knowing its internal details. In Android, APIs are used because:

  • The Android framework API gives access to the UI, database, sensors, camera, location, telephony and networking, so developers need not write these from scratch.
  • Web APIs (REST/JSON) allow the app to fetch or send data to remote servers, such as weather, maps or payments.
  • They save development time and give a standard, tested way of doing common tasks.
  • They let the app run on many devices and versions, because the API level hides hardware differences.

Hospital application. DBHelper creates Hospital.db with the Doctor table. The activity inserts doctors and displays only those whose experience is less than 5.5 years.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical" android:padding="16dp">
    <EditText android:id="@+id/etId" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:hint="Doctor ID"
        android:inputType="number"/>
    <EditText android:id="@+id/etName" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:hint="Doctor name"/>
    <EditText android:id="@+id/etSpec" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:hint="Specialization"/>
    <EditText android:id="@+id/etExp" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:hint="Experience (years)"
        android:inputType="numberDecimal"/>
    <Button android:id="@+id/btnInsert" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:text="Insert"/>
    <Button android:id="@+id/btnShow" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:text="Show Experience &lt; 5.5"/>
    <TextView android:id="@+id/tvResult" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:textSize="16sp"/>
</LinearLayout>

DBHelper.java

public class DBHelper extends SQLiteOpenHelper {
    public DBHelper(Context context) {
        super(context, "Hospital", null, 1);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE Doctor(Did INTEGER PRIMARY KEY, Dname TEXT, "
                + "Specialization TEXT, Experience REAL)");
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int o, int n) {
        db.execSQL("DROP TABLE IF EXISTS Doctor");
        onCreate(db);
    }
    public boolean insertDoctor(int id, String name, String spec, double exp) {
        ContentValues cv = new ContentValues();
        cv.put("Did", id);
        cv.put("Dname", name);
        cv.put("Specialization", spec);
        cv.put("Experience", exp);
        return getWritableDatabase().insert("Doctor", null, cv) != -1;
    }
    public Cursor getJuniorDoctors() {
        return getReadableDatabase().rawQuery(
                "SELECT * FROM Doctor WHERE Experience < ?", new String[]{"5.5"});
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        DBHelper helper = new DBHelper(this);
        EditText etId = findViewById(R.id.etId);
        EditText etName = findViewById(R.id.etName);
        EditText etSpec = findViewById(R.id.etSpec);
        EditText etExp = findViewById(R.id.etExp);
        TextView tvResult = findViewById(R.id.tvResult);

        findViewById(R.id.btnInsert).setOnClickListener(v -> {
            try {
                boolean ok = helper.insertDoctor(
                        Integer.parseInt(etId.getText().toString()),
                        etName.getText().toString(),
                        etSpec.getText().toString(),
                        Double.parseDouble(etExp.getText().toString()));
                Toast.makeText(this, ok ? "Inserted" : "Insert failed",
                        Toast.LENGTH_SHORT).show();
            } catch (NumberFormatException e) {
                Toast.makeText(this, "Enter valid ID and experience",
                        Toast.LENGTH_SHORT).show();
            }
        });

        findViewById(R.id.btnShow).setOnClickListener(v -> {
            Cursor c = helper.getJuniorDoctors();
            StringBuilder sb = new StringBuilder();
            while (c.moveToNext()) {
                sb.append("ID: ").append(c.getInt(0))
                  .append("\nName: ").append(c.getString(1))
                  .append("\nSpecialization: ").append(c.getString(2))
                  .append("\nExperience: ").append(c.getDouble(3)).append(" years\n\n");
            }
            c.close();
            tvResult.setText(sb.length() == 0 ? "No matching doctors" : sb.toString());
        });
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 10 marks

What does android APK file contain? Develop an android application with a context menu having menu items "Red", "Yellow", "Green", "Black" and "Blue" etc. and change the background color of the layout when the user selects a menu item accordingly.

Answer

Contents of an APK file. An APK (Android Package) is a ZIP-format archive containing everything needed to install an app:

  • AndroidManifest.xml: package name, components, permissions, minimum SDK (in binary form).
  • classes.dex: the compiled code in Dalvik Executable format.
  • resources.arsc: compiled resource table (strings, styles, and so on).
  • res/: resources that are not compiled into resources.arsc, such as layouts, drawables and menus.
  • assets/: raw files bundled with the app.
  • lib/: native libraries (.so) for each CPU architecture.
  • META-INF/: the signature and manifest of the package (MANIFEST.MF, CERT.SF, CERT.RSA).

Context menu application. A context menu appears on a long press of a registered view. The layout has a TextView as the long-press target, and the root layout's background changes.

res/menu/context_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_red" android:title="Red"/>
    <item android:id="@+id/menu_yellow" android:title="Yellow"/>
    <item android:id="@+id/menu_green" android:title="Green"/>
    <item android:id="@+id/menu_black" android:title="Black"/>
    <item android:id="@+id/menu_blue" android:title="Blue"/>
</menu>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout" android:layout_width="match_parent"
    android:layout_height="match_parent" android:gravity="center"
    android:background="#FFFFFF">
    <TextView android:id="@+id/tvHint" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:padding="24dp"
        android:text="Long press here to change colour" android:textSize="20sp"/>
</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    LinearLayout layout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        layout = findViewById(R.id.layout);
        registerForContextMenu(findViewById(R.id.tvHint));
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderTitle("Choose colour");
        getMenuInflater().inflate(R.menu.context_menu, menu);
    }

    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.menu_red) {
            layout.setBackgroundColor(Color.RED);
        } else if (id == R.id.menu_yellow) {
            layout.setBackgroundColor(Color.YELLOW);
        } else if (id == R.id.menu_green) {
            layout.setBackgroundColor(Color.GREEN);
        } else if (id == R.id.menu_black) {
            layout.setBackgroundColor(Color.BLACK);
        } else if (id == R.id.menu_blue) {
            layout.setBackgroundColor(Color.BLUE);
        } else {
            return super.onContextItemSelected(item);
        }
        return true;
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 5 marks

What are different mobile application development approaches? Explain in detail.

Answer

There are four main approaches to developing a mobile application.

1. Native approach. The app is written for one platform using its official language and SDK: Java or Kotlin with Android Studio for Android, and Swift or Objective-C with Xcode for iOS.

  • Advantages: best performance, full access to device hardware and APIs, the best user experience and latest platform features.
  • Disadvantages: separate code base for each platform, so higher cost and longer development time.

2. Mobile web approach. The app is a responsive website built with HTML, CSS and JavaScript, and opened in the mobile browser. Nothing is installed.

  • Advantages: one code base for all devices, easy updates, no app-store approval.
  • Disadvantages: limited access to hardware, needs a network connection, lower performance and no store presence.

3. Hybrid approach. The app is built with web technologies (HTML, CSS, JavaScript) and wrapped in a native container (a WebView) using frameworks such as Apache Cordova, Ionic or Capacitor. Plugins give access to device features.

  • Advantages: one code base, installable from stores, lower cost, quick development.
  • Disadvantages: slower than native, and the UI may not match native look and feel.

4. Cross-platform (compiled) approach. One code base is compiled or rendered into native UI components on each platform, using frameworks such as Flutter (Dart), React Native (JavaScript) or Xamarin/.NET MAUI (C#).

  • Advantages: near-native performance, shared code, access to native features through bridges or plugins.
  • Disadvantages: dependency on the framework, larger app size, and delay in supporting new platform features.

Progressive Web Apps (PWA) are a variation of the web approach. They can be installed to the home screen, work offline through service workers, and send push notifications.

Choosing. Native suits performance-heavy apps such as games; hybrid and cross-platform suit business apps with a limited budget; mobile web suits content-based services needing wide reach.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 5 marks

Draw the hierarchical directory structure of an android application. How can you use string and string array in android? Explain.

Answer

Directory structure of an Android project (Android Studio).

MyApplication/
├── app/
│   ├── manifests/
│   │   └── AndroidManifest.xml
│   ├── java/
│   │   └── com.example.myapp/
│   │       └── MainActivity.java
│   ├── res/
│   │   ├── drawable/        (images, shapes)
│   │   ├── layout/          (activity_main.xml)
│   │   ├── menu/            (menu XML)
│   │   ├── mipmap/          (launcher icons)
│   │   ├── values/          (strings.xml, colors.xml, styles/themes.xml, arrays.xml)
│   │   └── xml/
│   ├── build.gradle         (module level)
│   └── proguard-rules.pro
├── build.gradle             (project level)
├── settings.gradle
└── gradle/
  • manifests declares the app's components, permissions and the launcher activity.
  • java holds the source code. The R.java file is generated automatically and maps resource names to integer IDs.
  • res holds all non-code resources.
  • Gradle Scripts hold the build configuration and dependencies.

String resource. Text is kept in res/values/strings.xml instead of hard-coding it, which makes the app easy to translate and maintain.

<resources>
    <string name="app_name">My App</string>
    <string name="welcome">Welcome to Android</string>
</resources>

Use in a layout: android:text="@string/welcome". Use in Java:

String msg = getResources().getString(R.string.welcome);
// or inside an activity
String msg2 = getString(R.string.welcome);

String array resource. A list of strings is defined in strings.xml (or arrays.xml).

<string-array name="subjects">
    <item>Mobile Programming</item>
    <item>Distributed System</item>
    <item>Network Programming</item>
</string-array>

Use in Java:

String[] subjects = getResources().getStringArray(R.array.subjects);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
        android.R.layout.simple_list_item_1, subjects);
listView.setAdapter(adapter);

It can also be bound in XML, for example to a spinner with android:entries="@array/subjects".

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 5 marks

How to create AVD's? How to use spinner in android? Explain with a suitable example.

Answer

Creating an AVD (Android Virtual Device). An AVD is an emulated device used to test apps without a physical phone.

  1. In Android Studio open Tools > Device Manager (or AVD Manager).
  2. Click Create Device.
  3. Choose a hardware profile (for example Pixel 6) and click Next.
  4. Select a system image (Android version, such as API 34) and download it if needed, then click Next.
  5. Give the AVD a name and set options (orientation, RAM, storage, camera) under Show Advanced Settings.
  6. Click Finish. The device appears in the Device Manager.
  7. Click the Run (play) button to start the emulator, then run the app on it.

Hardware acceleration (HAXM or the Hypervisor) should be enabled so the emulator is fast.

Spinner. A Spinner is a drop-down list that lets the user choose one item from several. The data is supplied with an adapter and the selection is handled with OnItemSelectedListener.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical" android:padding="16dp">
    <Spinner android:id="@+id/spinner" android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <TextView android:id="@+id/tvSelected" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_marginTop="16dp"
        android:textSize="18sp"/>
</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Spinner spinner = findViewById(R.id.spinner);
        TextView tvSelected = findViewById(R.id.tvSelected);
        String[] cities = {"Kathmandu", "Pokhara", "Biratnagar", "Butwal", "Dharan"};

        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item, cities);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                tvSelected.setText("Selected city: " + cities[pos]);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) { }
        });
    }
}

When the user opens the spinner and chooses "Pokhara", the text view shows Selected city: Pokhara.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 5 marks

What are the uses of fragments? How fragments are differing from activity?

Answer

Uses of fragments. A fragment is a modular portion of an activity's user interface with its own layout and lifecycle. It is used for:

  • Reusability: the same fragment can be used in several activities.
  • Adaptive layouts: on a tablet, a list fragment and a detail fragment can be shown side by side, while on a phone they are shown one after another in separate screens.
  • Modular design: a complex screen is divided into small, independent, easier-to-maintain parts.
  • Dynamic UI: fragments can be added, removed or replaced at run time with FragmentTransaction, and kept on the back stack.
  • Navigation patterns: tabs, ViewPager and bottom navigation are built from fragments, which reduces the number of activities.

Fragment versus activity.

ActivityFragment
Independent application component representing a full screenPart of the UI that always lives inside an activity
Must be declared in AndroidManifest.xmlNot declared in the manifest
Started with an IntentAdded through FragmentManager and FragmentTransaction
Lifecycle controlled by the systemLifecycle controlled by the host activity (extra callbacks such as onAttach(), onCreateView(), onDestroyView())
Cannot be nested inside another activityCan be nested and combined; many in one activity
Less reusableHighly reusable

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 5 marks

Develop an android application to display an alert dialog box.

Answer

An AlertDialog is a small window that asks the user to make a decision. It is built using AlertDialog.Builder, with a title, a message and up to three buttons (positive, negative, neutral).

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:gravity="center">
    <Button android:id="@+id/btnShow" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="Show Alert Dialog"/>
</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.btnShow).setOnClickListener(v -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("Exit");
            builder.setMessage("Do you want to close the application?");
            builder.setIcon(android.R.drawable.ic_dialog_alert);
            builder.setCancelable(false);

            builder.setPositiveButton("Yes", (dialog, which) -> finish());
            builder.setNegativeButton("No", (dialog, which) -> dialog.cancel());
            builder.setNeutralButton("Later", (dialog, which) ->
                    Toast.makeText(MainActivity.this, "Maybe later",
                            Toast.LENGTH_SHORT).show());

            AlertDialog dialog = builder.create();
            dialog.show();
        });
    }
}

Pressing the button opens the dialog. "Yes" closes the app, "No" dismisses the dialog and "Later" shows a Toast.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 5 marks

Develop an android application to display 8 programming languages in ListView.

Answer

A ListView shows a scrollable vertical list. An ArrayAdapter supplies one row of text per item of a String array.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical">
    <ListView android:id="@+id/listView" android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ListView listView = findViewById(R.id.listView);
        String[] languages = {"Java", "Kotlin", "Python", "C", "C++",
                "JavaScript", "Swift", "PHP"};

        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, languages);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener((parent, view, position, id) ->
                Toast.makeText(MainActivity.this, languages[position],
                        Toast.LENGTH_SHORT).show());
    }
}

The eight languages appear in the list, and touching an item shows its name in a Toast.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 5 marks

What do you mean by view hierarchy in iOS programming? Write a swift function to calculate the factorial of any positive integer.

Answer

View hierarchy in iOS. An iOS screen is a tree of UIView objects. The UIWindow is the root, which holds the view controller's main view, and that view contains subviews such as labels, buttons, image views, table views and stack views. Each view has one superview and any number of subviews. The hierarchy determines the drawing order (children are drawn over their parents), the coordinate system (a subview's frame is relative to its superview, so moving a parent moves its children), and how touch events are passed down by hit-testing and back up the responder chain. Views are added with addSubview(_:) or in the storyboard.

Swift function for factorial

func factorial(_ n: Int) -> Int {
    if n < 0 {
        return -1          // not defined for negative numbers
    }
    var result = 1
    if n >= 2 {
        for i in 2...n {
            result *= i
        }
    }
    return result
}

let number = 5
print("Factorial of \(number) is \(factorial(number))")

Output:

Factorial of 5 is 120

Here 5!=5×4×3×2×1=1205! = 5 \times 4 \times 3 \times 2 \times 1 = 120. A recursive version is func fact(_ n: Int) -> Int { return n <= 1 ? 1 : n * fact(n - 1) }. An Int is 64-bit on modern devices, so the function is correct up to 20!20!.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 10 marks

Develop an android application to demonstrate the retrieval of content from a remote server.

Answer

The app downloads text (JSON) from a remote URL using HttpURLConnection. Network work must not run on the main (UI) thread, otherwise Android throws NetworkOnMainThreadException. A background thread does the download and posts the result back to the UI thread through a Handler.

AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>

For plain http:// URLs, android:usesCleartextTraffic="true" is also needed in <application>; an https:// URL needs nothing extra.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical" android:padding="16dp">
    <Button android:id="@+id/btnFetch" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:text="Fetch from Server"/>
    <ScrollView android:layout_width="match_parent" android:layout_height="match_parent">
        <TextView android:id="@+id/tvContent" android:layout_width="match_parent"
            android:layout_height="wrap_content" android:textSize="15sp"/>
    </ScrollView>
</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    private static final String URL_STRING =
            "https://jsonplaceholder.typicode.com/posts/1";
    TextView tvContent;
    final Handler handler = new Handler(Looper.getMainLooper());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvContent = findViewById(R.id.tvContent);

        findViewById(R.id.btnFetch).setOnClickListener(v -> {
            tvContent.setText("Loading...");
            new Thread(() -> {
                String result;
                try {
                    result = download(URL_STRING);
                } catch (IOException e) {
                    result = "Error: " + e.getMessage();
                }
                final String text = result;
                handler.post(() -> tvContent.setText(text));
            }).start();
        });
    }

    private String download(String urlString) throws IOException {
        HttpURLConnection conn = null;
        try {
            URL url = new URL(urlString);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(10000);
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                throw new IOException("HTTP " + conn.getResponseCode());
            }
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
            reader.close();
            return sb.toString();
        } finally {
            if (conn != null) conn.disconnect();
        }
    }
}

When the button is pressed, the thread connects to the server, reads the response line by line, and the Handler shows the returned content in the TextView. Libraries such as Volley or Retrofit do the same job with less code.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 10 marks

How to generate a signed APK? Write a program to locate the user's current location (write only .java and manifest file).

Answer

Generating a signed APK. An app must be digitally signed with a private key before it can be published to the Play Store.

  1. In Android Studio choose Build > Generate Signed Bundle / APK.
  2. Select APK and click Next.
  3. Under Key store path click Create new. Give a file location, a keystore password, then an alias, key password, validity (for example 25 years) and certificate details (name, organization, country). Click OK. To use an existing keystore, choose Choose existing and enter its details.
  4. Click Next, select the release build variant and the signature versions (V1 and V2).
  5. Click Finish. The signed APK is created in app/release/.

The keystore and its passwords must be kept safe: the same key is required for every update of the app.

Current location application. The app uses the FusedLocationProviderClient from Google Play Services.

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.locationapp">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/Theme.AppCompat.Light">
        <activity android:name=".MainActivity" android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

The build.gradle dependency is implementation 'com.google.android.gms:play-services-location:21.0.1'.

MainActivity.java

public class MainActivity extends AppCompatActivity {
    private static final int REQ_LOCATION = 101;
    private FusedLocationProviderClient client;
    private TextView tvLocation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tvLocation = new TextView(this);
        tvLocation.setTextSize(18);
        tvLocation.setPadding(32, 64, 32, 32);
        setContentView(tvLocation);

        client = LocationServices.getFusedLocationProviderClient(this);
        getLocation();
    }

    private void getLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQ_LOCATION);
            return;
        }
        client.getLastLocation().addOnSuccessListener(location -> {
            if (location != null) {
                tvLocation.setText("Latitude: " + location.getLatitude()
                        + "\nLongitude: " + location.getLongitude());
            } else {
                tvLocation.setText("Location not available. Turn on GPS and retry.");
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQ_LOCATION && grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            getLocation();
        } else {
            tvLocation.setText("Location permission denied");
        }
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 · 5 marks

What is Android? Explain different categories of mobile devices.

Answer

Android. Android is an open-source, Linux-based mobile operating system developed by Google (originally by Android Inc., acquired by Google in 2005 and first released commercially in 2008). It provides a complete software stack: the Linux kernel, native libraries, the Android Runtime (ART), the application framework and built-in applications. Applications are mainly written in Java or Kotlin and distributed through Google Play. Because it is open source and customizable, it runs on devices from many manufacturers.

Categories of mobile devices.

  • Smartphones: handheld phones with a touchscreen, internet access, sensors and an app ecosystem.
  • Tablets: larger-screen touch devices, used for reading, media, drawing and productivity.
  • Wearables: devices worn on the body, such as smartwatches and fitness bands, with sensors and notifications. Wear OS is Android for wearables.
  • E-readers: devices for reading digital books with e-ink displays, such as Kindle.
  • Feature phones: basic phones with calls, SMS and limited apps.
  • Laptops and 2-in-1 devices: portable computers, sometimes with Android or Chrome OS.
  • Android TV and Android Auto devices: Android adapted for televisions and car dashboards (infotainment).
  • Embedded and IoT devices: smart-home devices, cameras and other connected gadgets that run Android Things or Android-based systems.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 · 5 marks

What is the difference between android:layout_gravity and android:gravity attribute in linear layout? Create an android application that will convert distance entered into Kilometers into Meters using Table Layout.

Answer

layout_gravity versus gravity.

android:gravityandroid:layout_gravity
Positions the content inside the view itselfPositions the view inside its parent layout
Example: aligns the text inside a TextView or ButtonExample: aligns the TextView itself within the LinearLayout
Set on the view whose content is being aligned (or on a layout to align its children)Set on the child view, and read by the parent
android:gravity="center" centres the textandroid:layout_gravity="center" centres the view in its parent

In a vertical LinearLayout, layout_gravity only has an effect on the horizontal axis (and in a horizontal one, only on the vertical axis).

Kilometre to metre converter using TableLayout.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:padding="16dp" android:stretchColumns="1">

    <TableRow>
        <TextView android:text="Kilometers:" android:textSize="18sp"
            android:layout_width="wrap_content" android:layout_height="wrap_content"/>
        <EditText android:id="@+id/etKm" android:hint="Enter distance"
            android:inputType="numberDecimal"
            android:layout_width="wrap_content" android:layout_height="wrap_content"/>
    </TableRow>

    <TableRow>
        <Button android:id="@+id/btnConvert" android:text="Convert"
            android:layout_span="2"
            android:layout_width="match_parent" android:layout_height="wrap_content"/>
    </TableRow>

    <TableRow>
        <TextView android:text="Meters:" android:textSize="18sp"
            android:layout_width="wrap_content" android:layout_height="wrap_content"/>
        <TextView android:id="@+id/tvMeters" android:textSize="18sp"
            android:layout_width="wrap_content" android:layout_height="wrap_content"/>
    </TableRow>
</TableLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        EditText etKm = findViewById(R.id.etKm);
        TextView tvMeters = findViewById(R.id.tvMeters);

        findViewById(R.id.btnConvert).setOnClickListener(v -> {
            String s = etKm.getText().toString();
            if (s.isEmpty()) {
                etKm.setError("Enter a value");
                return;
            }
            double km = Double.parseDouble(s);
            tvMeters.setText(String.valueOf(km * 1000));
        });
    }
}

The conversion is meters=kilometers×1000\text{meters} = \text{kilometers} \times 1000, so an input of 2.5 gives 2500.0.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 · 5 marks

Why is a fragment needed in Android? Write Java code only to send data from one activity to another activity using an implicit intent.

Answer

Need for a fragment. A fragment is a reusable portion of the user interface with its own layout and lifecycle, hosted inside an activity. It is needed because:

  • Reusability: one fragment can be used in many activities.
  • Adaptive UI: on a phone one fragment is shown per screen, while on a tablet two or more fragments are shown side by side in one activity (list and detail).
  • Modularity: a complex screen is split into smaller parts that are easier to develop and test.
  • Dynamic UI: fragments can be added, replaced and removed at run time with the back stack, using FragmentManager.

Sending data to another activity using an implicit intent (an ACTION_SEND intent, handled by any app that can share text):

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        EditText etMessage = findViewById(R.id.etMessage);
        Button btnSend = findViewById(R.id.btnSend);

        btnSend.setOnClickListener(v -> {
            String message = etMessage.getText().toString();

            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_SUBJECT, "Message");
            intent.putExtra(Intent.EXTRA_TEXT, message);

            startActivity(Intent.createChooser(intent, "Send via"));
        });
    }
}

The receiving activity declares an intent filter in the manifest so that it can handle this implicit intent:

<activity android:name=".ReceiverActivity" android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.SEND" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="text/plain" />
    </intent-filter>
</activity>
public class ReceiverActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receiver);
        String text = getIntent().getStringExtra(Intent.EXTRA_TEXT);
        ((TextView) findViewById(R.id.tvReceived)).setText(text);
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 · 5 marks

What is a menu? Develop an android application to create a popup menu having menu items "Edit", "Copy", "Paste", "Redo", and "Undo".

Answer

Menu. A menu is a set of actions or options presented to the user in a list. Android supports three types: the options menu (app bar), the context menu (long press on a view) and the popup menu (a modal list anchored to a view). Menus are defined in XML under res/menu and inflated in code.

Menu resource res/menu/popup_menu.xml:

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/edit" android:title="Edit" />
    <item android:id="@+id/copy" android:title="Copy" />
    <item android:id="@+id/paste" android:title="Paste" />
    <item android:id="@+id/redo" android:title="Redo" />
    <item android:id="@+id/undo" android:title="Undo" />
</menu>

Layout activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:gravity="center" android:orientation="vertical">
    <Button android:id="@+id/btnShow"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:text="Show Popup Menu" />
</LinearLayout>

MainActivity.java:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btnShow = findViewById(R.id.btnShow);
        btnShow.setOnClickListener(v -> {
            PopupMenu popup = new PopupMenu(MainActivity.this, v);
            popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
            popup.setOnMenuItemClickListener(item -> {
                Toast.makeText(MainActivity.this,
                        "You selected " + item.getTitle(), Toast.LENGTH_SHORT).show();
                return true;
            });
            popup.show();
        });
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 · 5 marks

What is JSON? Develop an android application to display 10 different images of fruit in Grid View with two columns.

Answer

JSON. JSON (JavaScript Object Notation) is a lightweight, text-based, language-independent format for exchanging data as key/value pairs (objects in {}) and ordered lists (arrays in []). It is easy to read and parse, and is widely used between Android apps and web services, for example {"name":"Apple","price":120}.

Application: 10 fruit images in a GridView with two columns. Place ten images (apple.png, banana.png, ... ) in res/drawable.

activity_main.xml:

<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:numColumns="2"
    android:horizontalSpacing="8dp"
    android:verticalSpacing="8dp" />

MainActivity.java:

public class MainActivity extends AppCompatActivity {
    int[] fruits = {
        R.drawable.apple, R.drawable.banana, R.drawable.orange, R.drawable.mango,
        R.drawable.grapes, R.drawable.pineapple, R.drawable.papaya,
        R.drawable.cherry, R.drawable.watermelon, R.drawable.pear
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        GridView gridView = findViewById(R.id.gridView);
        gridView.setAdapter(new ImageAdapter(this, fruits));
    }

    static class ImageAdapter extends BaseAdapter {
        private final Context context;
        private final int[] images;

        ImageAdapter(Context context, int[] images) {
            this.context = context;
            this.images = images;
        }

        @Override public int getCount() { return images.length; }
        @Override public Object getItem(int position) { return images[position]; }
        @Override public long getItemId(int position) { return position; }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView iv;
            if (convertView == null) {
                iv = new ImageView(context);
                iv.setLayoutParams(new GridView.LayoutParams(400, 400));
                iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
            } else {
                iv = (ImageView) convertView;
            }
            iv.setImageResource(images[position]);
            return iv;
        }
    }
}

numColumns="2" makes the grid show two images in each row.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 · 5 marks

What do you mean by storyboard? Write a Swift program to find the largest and smallest number among three numbers using a ternary operator.

Answer

Storyboard. A storyboard is a visual representation of the user interface of an iOS app in Xcode (Main.storyboard). It shows the screens (view controllers) and the transitions (segues) between them, so layouts and navigation flow can be designed graphically, with Auto Layout, without writing code.

Swift program: largest and smallest of three numbers using the ternary operator

let a = 25
let b = 87
let c = 42

let largest = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c)
let smallest = (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c)

print("Largest number  = \(largest)")
print("Smallest number = \(smallest)")

Output:

Largest number  = 87
Smallest number = 25

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 · 10 marks

Provided that a MySQL database named "Bank" with a table named Customer has the following columns: (account_no, name, account_type, and amount). Develop an android application to connect to the database remotely and display the Customer details in a ListView for those whose deposit amount is greater than 5000.

Answer

Approach

An Android app cannot connect to MySQL directly in a safe way, so a server-side script (PHP) queries the database and returns JSON. The app requests it over HTTP and shows the result in a ListView.

Server: getCustomers.php

<?php
$conn = new mysqli("localhost", "root", "", "Bank");
$result = $conn->query("SELECT account_no, name, account_type, amount FROM Customer WHERE amount > 5000");
$rows = array();
while ($r = $result->fetch_assoc()) { $rows[] = $r; }
echo json_encode($rows);
$conn->close();
?>

Manifest

<uses-permission android:name="android.permission.INTERNET"/>

(and android:usesCleartextTraffic="true" on <application> if the URL is plain HTTP).

activity_main.xml: a ListView with id listView.

MainActivity.java (using Volley; add implementation 'com.android.volley:volley:1.2.1')

public class MainActivity extends AppCompatActivity {
    ListView listView;
    ArrayList<String> data = new ArrayList<>();
    String url = "http://10.0.2.2/bank/getCustomers.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = findViewById(R.id.listView);

        JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null,
            response -> {
                try {
                    for (int i = 0; i < response.length(); i++) {
                        JSONObject o = response.getJSONObject(i);
                        data.add("A/C No: " + o.getString("account_no")
                                + "\nName: " + o.getString("name")
                                + "\nType: " + o.getString("account_type")
                                + "\nAmount: Rs " + o.getString("amount"));
                    }
                    listView.setAdapter(new ArrayAdapter<>(MainActivity.this,
                            android.R.layout.simple_list_item_1, data));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            },
            error -> Toast.makeText(this, "Error: " + error.getMessage(),
                    Toast.LENGTH_LONG).show());

        Volley.newRequestQueue(this).add(request);
    }
}

The filter amount > 5000 is applied in the SQL query on the server, so only matching customers reach the app. 10.0.2.2 is the emulator's alias for the host machine's localhost.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 · 10 marks

Explain the procedure for generating a Google Maps API key for displaying Google Maps. Develop an android application to display a Google Map with a marker at TRIBHUVAN UNIVERSITY.

Answer

Procedure to generate a Google Maps API key

  1. Open the Google Cloud Console (console.cloud.google.com) and sign in with a Google account.
  2. Create a new project (or select an existing one) and enable billing for it.
  3. Go to APIs & Services > Library, search for Maps SDK for Android and click Enable.
  4. Go to APIs & Services > Credentials, click Create credentials > API key.
  5. Restrict the key: choose Android apps, then add the app's package name and the SHA-1 certificate fingerprint (obtained with keytool or Gradle signingReport).
  6. Copy the key and put it in AndroidManifest.xml inside <application>.

Application with a marker at Tribhuvan University

Gradle dependency: implementation 'com.google.android.gms:play-services-maps:18.2.0'

AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>
<application ...>
    <meta-data android:name="com.google.android.geo.API_KEY"
               android:value="YOUR_API_KEY"/>
    ...
</application>

activity_maps.xml

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent" android:layout_height="match_parent"/>

MapsActivity.java

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        SupportMapFragment mapFragment =
                (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        LatLng tu = new LatLng(27.6819, 85.2886);   // Tribhuvan University, Kirtipur
        googleMap.addMarker(new MarkerOptions().position(tu).title("TRIBHUVAN UNIVERSITY"));
        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(tu, 15f));
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 5 marks

What is mobile device? Explain different features of mobile device.

Answer

Mobile device

A mobile device is a small, portable, battery-powered computing device that can be carried and used anywhere, usually with wireless connectivity, e.g. smartphones, tablets and smartwatches.

Features of mobile devices

  • Portability: small size and light weight, so it can be used on the move.
  • Wireless connectivity: Wi-Fi, 4G/5G, Bluetooth, NFC and GPS give access to networks and location services.
  • Touch screen interface: input through touch, gestures and on-screen keyboard, plus voice.
  • Sensors: accelerometer, gyroscope, proximity, light, compass and fingerprint sensors enable context-aware apps.
  • Camera and multimedia: photo, video, audio recording and playback.
  • Limited resources: smaller CPU, memory, storage and screen than desktops, so apps must be efficient.
  • Battery powered: power management matters in app design.
  • Mobile operating system and apps: Android or iOS, with apps installed from app stores.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 5 marks

List and explain any five widgets used in android programming.

Answer

Widgets in Android

Widgets are the View subclasses that make up the user interface. Five common ones:

  1. TextView: displays non-editable text. Attributes such as text, textSize and textColor control its look.
  2. EditText: an editable text field that takes input from the user, e.g. names or passwords (inputType).
  3. Button: a push button that triggers an action through an OnClickListener.
  4. ImageView: displays an image or drawable resource using src and scaleType.
  5. CheckBox / RadioButton: a CheckBox lets the user select any number of options; RadioButtons (inside a RadioGroup) allow only one choice from several.

Others include Spinner, ListView, ProgressBar and Switch.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 5 marks

Differentiate RelativeLayout and ConstraintLayout with suitable example.

Answer

RelativeLayout vs ConstraintLayout

BasisRelativeLayoutConstraintLayout
PositioningViews are positioned relative to the parent or sibling views (layout_below, layout_toRightOf).Views are positioned by constraints on all sides to the parent, siblings or guidelines.
HierarchyComplex screens often need nested layouts, which slows rendering.Flat hierarchy even for complex UIs, so better performance.
FeaturesLimited alignment options.Chains, guidelines, barriers, ratios, bias and groups.
Design toolWeaker visual support.Fully supported by the Layout Editor drag and drop.
LibraryPart of the framework.AndroidX library (androidx.constraintlayout).

RelativeLayout example

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <EditText android:id="@+id/etName"
        android:layout_width="match_parent" android:layout_height="wrap_content"/>
    <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:layout_below="@id/etName" android:layout_alignParentRight="true"
        android:text="Submit"/>
</RelativeLayout>

ConstraintLayout example

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <EditText android:id="@+id/etName"
        android:layout_width="0dp" android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>
    <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:text="Submit"
        app:layout_constraintTop_toBottomOf="@id/etName"
        app:layout_constraintEnd_toEndOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 5 marks

Develop an android application to calculate perimeter of rectangle using LinearLayout.

Answer

Perimeter of a rectangle: P=2(l+b)P = 2(l + b)

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical" android:padding="16dp">
    <EditText android:id="@+id/etLength"
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:hint="Enter length" android:inputType="numberDecimal"/>
    <EditText android:id="@+id/etBreadth"
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:hint="Enter breadth" android:inputType="numberDecimal"/>
    <Button android:id="@+id/btnCalc"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:text="Calculate Perimeter"/>
    <TextView android:id="@+id/tvResult"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:textSize="20sp"/>
</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EditText etL = findViewById(R.id.etLength);
        EditText etB = findViewById(R.id.etBreadth);
        TextView tv = findViewById(R.id.tvResult);

        findViewById(R.id.btnCalc).setOnClickListener(v -> {
            if (etL.getText().toString().isEmpty() || etB.getText().toString().isEmpty()) {
                Toast.makeText(this, "Enter both values", Toast.LENGTH_SHORT).show();
                return;
            }
            double l = Double.parseDouble(etL.getText().toString());
            double b = Double.parseDouble(etB.getText().toString());
            tv.setText("Perimeter = " + 2 * (l + b));
        });
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 5 marks

Develop an android application to create two fragments and display it in activity.

Answer

Two fragments displayed in one activity

fragment_one.xml (and similarly fragment_two.xml with different text and colour)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:background="#BBDEFB" android:gravity="center">
    <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:text="This is Fragment One" android:textSize="20sp"/>
</LinearLayout>

FragmentOne.java

public class FragmentOne extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_one, container, false);
    }
}

FragmentTwo.java is identical, using R.layout.fragment_two.

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical">
    <FrameLayout android:id="@+id/container1"
        android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"/>
    <FrameLayout android:id="@+id/container2"
        android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"/>
</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                .replace(R.id.container1, new FragmentOne())
                .replace(R.id.container2, new FragmentTwo())
                .commit();
        }
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 5 marks

Explain the process of creating options menu in android app with suitable program.

Answer

Creating an options menu

The options menu appears in the app bar and holds actions relevant to the current screen. Steps:

  1. Create a menu resource file in res/menu.
  2. Inflate it by overriding onCreateOptionsMenu().
  3. Handle item clicks by overriding onOptionsItemSelected().

res/menu/main_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/action_settings" android:title="Settings"
          app:showAsAction="never"/>
    <item android:id="@+id/action_about" android:title="About"
          app:showAsAction="never"/>
    <item android:id="@+id/action_exit" android:title="Exit"
          app:showAsAction="never"/>
</menu>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            Toast.makeText(this, "Settings clicked", Toast.LENGTH_SHORT).show();
            return true;
        } else if (id == R.id.action_about) {
            Toast.makeText(this, "About clicked", Toast.LENGTH_SHORT).show();
            return true;
        } else if (id == R.id.action_exit) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 5 marks

Define ViewController. Write a Swift program to calculate factorial of a number using function.

Answer

ViewController

A UIViewController is the core class in iOS (UIKit) that manages a screen of the app. It controls a view hierarchy, responds to user actions, updates the view with data and handles lifecycle events such as viewDidLoad(), viewWillAppear() and viewDidDisappear(). It acts as the "C" in the MVC pattern, linking the model and the views.

Swift program: factorial using a function

func factorial(_ n: Int) -> Int {
    if n <= 1 { return 1 }
    var result = 1
    for i in 2...n {
        result *= i
    }
    return result
}

let number = 5
print("Factorial of \(number) is \(factorial(number))")

Output:

Factorial of 5 is 120

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 10 marks

List and explain any three features of RecyclerView. Develop an android application to display any five programming languages in GridView.

Answer

Three features of RecyclerView

  1. View recycling: it reuses item views that scroll off screen instead of creating new ones, giving smooth scrolling and low memory use for large lists.
  2. ViewHolder pattern: it forces the use of a ViewHolder, which caches view references so findViewById() is not called repeatedly.
  3. Flexible layout managers and animations: LinearLayoutManager, GridLayoutManager and StaggeredGridLayoutManager give list, grid or staggered layouts, and item add/remove animations and item decorations are built in.

Application: five programming languages in a grid

activity_main.xml

<androidx.recyclerview.widget.RecyclerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/recyclerView"
    android:layout_width="match_parent" android:layout_height="match_parent"/>

item_language.xml

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tvLang"
    android:layout_width="match_parent" android:layout_height="100dp"
    android:gravity="center" android:textSize="18sp"
    android:background="#E0E0E0" android:layout_margin="4dp"/>

LangAdapter.java

public class LangAdapter extends RecyclerView.Adapter<LangAdapter.VH> {
    private final String[] langs;
    public LangAdapter(String[] langs) { this.langs = langs; }

    static class VH extends RecyclerView.ViewHolder {
        TextView tv;
        VH(View v) { super(v); tv = v.findViewById(R.id.tvLang); }
    }

    @NonNull @Override
    public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_language, parent, false);
        return new VH(v);
    }

    @Override
    public void onBindViewHolder(@NonNull VH holder, int position) {
        holder.tv.setText(langs[position]);
    }

    @Override public int getItemCount() { return langs.length; }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String[] langs = {"Java", "Python", "C++", "Kotlin", "JavaScript"};
        RecyclerView rv = findViewById(R.id.recyclerView);
        rv.setLayoutManager(new GridLayoutManager(this, 2));
        rv.setAdapter(new LangAdapter(langs));
    }
}

The question asks for GridView; a GridView with an ArrayAdapter<String> and numColumns="2" would work equally, but RecyclerView with GridLayoutManager is the modern equivalent.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 10 marks

Explain different types of API. Develop an android application to pass name and age of customer from one activity to another.

Answer

Types of API

An API (Application Programming Interface) is a set of rules and functions that lets one software component use the services of another.

  • Open (Public) API: available to any developer with little or no restriction, e.g. Google Maps or OpenWeather API.
  • Partner API: shared only with specific business partners under agreement, usually with authentication.
  • Internal (Private) API: used only inside an organization to connect its own systems.
  • Composite API: combines several API calls into one request, useful when one task needs data from multiple services.

By protocol or style, APIs are also classified as REST, SOAP, GraphQL and RPC. In Android, the platform's own APIs (framework, Google Play services) are also used.

Passing name and age between activities

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EditText etName = findViewById(R.id.etName);
        EditText etAge = findViewById(R.id.etAge);

        findViewById(R.id.btnSend).setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, SecondActivity.class);
            intent.putExtra("name", etName.getText().toString());
            intent.putExtra("age", Integer.parseInt(etAge.getText().toString()));
            startActivity(intent);
        });
    }
}

activity_main.xml contains EditText etName, EditText etAge (inputType="number") and Button btnSend.

SecondActivity.java

public class SecondActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        String name = getIntent().getStringExtra("name");
        int age = getIntent().getIntExtra("age", 0);
        ((TextView) findViewById(R.id.tvInfo))
                .setText("Name: " + name + "\nAge: " + age);
    }
}

SecondActivity must be declared in AndroidManifest.xml with <activity android:name=".SecondActivity"/>.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 10 marks

Provided that a SQLite database named "BookStore" with a table named Book with the following columns (book_id as Integer, name as Text and author as Text). Develop an android application to connect to the database and insert three book records and display the book information.

Answer

SQLite BookStore application

DBHelper.java

public class DBHelper extends SQLiteOpenHelper {
    public DBHelper(Context context) { super(context, "BookStore", null, 1); }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE Book (book_id INTEGER PRIMARY KEY, name TEXT, author TEXT)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
        db.execSQL("DROP TABLE IF EXISTS Book");
        onCreate(db);
    }

    public void insertBook(int id, String name, String author) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("book_id", id);
        cv.put("name", name);
        cv.put("author", author);
        db.insert("Book", null, cv);
    }

    public Cursor getBooks() {
        return getReadableDatabase().rawQuery("SELECT * FROM Book", null);
    }
}

activity_main.xml: a TextView with id tvOutput (inside a ScrollView if desired).

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView tv = findViewById(R.id.tvOutput);

        DBHelper db = new DBHelper(this);
        db.getWritableDatabase().delete("Book", null, null); // avoid duplicate key on re-run
        db.insertBook(1, "Let Us C", "Yashavant Kanetkar");
        db.insertBook(2, "Java: The Complete Reference", "Herbert Schildt");
        db.insertBook(3, "Muna Madan", "Laxmi Prasad Devkota");

        StringBuilder sb = new StringBuilder();
        Cursor c = db.getBooks();
        while (c.moveToNext()) {
            sb.append("ID: ").append(c.getInt(0))
              .append("\nName: ").append(c.getString(1))
              .append("\nAuthor: ").append(c.getString(2))
              .append("\n\n");
        }
        c.close();
        tv.setText(sb.toString());
    }
}

SQLiteOpenHelper creates the database on first use, insert() adds the three rows, and the Cursor returned by rawQuery() is iterated to display each book.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 · 1+4 marks

What is role of drawable folder in Android? Write down steps for deploying android application in emulator.

Answer

Role of the drawable folder

The res/drawable folder stores graphic resources used by the app, such as PNG/JPG images, vector drawables and XML-defined shapes, selectors and gradients. They are referenced in XML as @drawable/name and in Java as R.drawable.name. Android picks the correct version from density-specific folders (drawable-hdpi, drawable-xhdpi, etc.) for the device screen.

Steps to deploy an app on the emulator

  1. Open the project in Android Studio.
  2. Open Tools > Device Manager and click Create Device.
  3. Choose a hardware profile (e.g. Pixel), select a system image (API level) and download it if needed, then finish to create the AVD.
  4. Start the AVD with the play button and wait for it to boot.
  5. Select the AVD in the device drop-down in the toolbar.
  6. Click Run (green triangle) or press Shift+F10. Gradle builds the APK, installs it on the emulator and launches the app.
  7. Check output and errors in Logcat.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 · 2+3 marks

What are events in android? Explain the purpose of Views and View Group

Answer

Events in Android

An event is an action by the user or system that the app can respond to, such as a click, long click, touch, key press or focus change. They are handled using event listeners (e.g. OnClickListener, OnLongClickListener, OnTouchListener), which contain callback methods like onClick(View v). A listener is registered on a view with methods such as setOnClickListener().

Views and ViewGroups

  • View: the basic building block of the UI. It occupies a rectangular area of the screen and draws itself and handles events. Examples are TextView, Button, EditText and ImageView.
  • ViewGroup: an invisible container that is a subclass of View and holds other views (and ViewGroups) as children, defining how they are arranged. Examples are LinearLayout, RelativeLayout, ConstraintLayout and FrameLayout.

Together they form the view hierarchy: ViewGroups are the parent nodes and Views are the leaves of the UI tree.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 · 1+4 marks

Why RadioButton is usually used inside a RadioGroup? Create an android application to display selected RadioButton for gender (Male/Female/Others) using Toast message.

Answer

RadioButton inside a RadioGroup

A RadioButton allows only one choice from a set. By itself, each RadioButton toggles independently, so several could be selected. A RadioGroup groups them and enforces mutual exclusion: selecting one automatically deselects the others, and it provides a single listener and getCheckedRadioButtonId() to read the choice.

Application

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical" android:padding="16dp">
    <RadioGroup android:id="@+id/rgGender"
        android:layout_width="wrap_content" android:layout_height="wrap_content">
        <RadioButton android:id="@+id/rbMale"   android:text="Male"
            android:layout_width="wrap_content" android:layout_height="wrap_content"/>
        <RadioButton android:id="@+id/rbFemale" android:text="Female"
            android:layout_width="wrap_content" android:layout_height="wrap_content"/>
        <RadioButton android:id="@+id/rbOthers" android:text="Others"
            android:layout_width="wrap_content" android:layout_height="wrap_content"/>
    </RadioGroup>
    <Button android:id="@+id/btnShow" android:text="Show"
        android:layout_width="wrap_content" android:layout_height="wrap_content"/>
</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RadioGroup rg = findViewById(R.id.rgGender);

        findViewById(R.id.btnShow).setOnClickListener(v -> {
            int id = rg.getCheckedRadioButtonId();
            if (id == -1) {
                Toast.makeText(this, "Please select gender", Toast.LENGTH_SHORT).show();
            } else {
                RadioButton rb = findViewById(id);
                Toast.makeText(this, "Selected: " + rb.getText(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 · 1+4 marks

When fragment is used instead of activity in android? Write a java code to illustrate fragment lifecycle in android.

Answer

When a fragment is used instead of an activity

A fragment is preferred when:

  • the same UI part must be reused in several screens;
  • the app must adapt to different screen sizes (e.g. list and detail side by side on tablets, separate screens on phones);
  • the UI uses tabs, a ViewPager or a navigation drawer, where several panels live in a single activity;
  • parts of the screen must be replaced dynamically while keeping the activity alive, which is lighter than starting new activities.

Fragment lifecycle demonstration

Lifecycle order: onAttach > onCreate > onCreateView > onViewCreated > onStart > onResume > onPause > onStop > onDestroyView > onDestroy > onDetach.

public class DemoFragment extends Fragment {
    private static final String TAG = "FragmentLifecycle";

    @Override public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        Log.d(TAG, "onAttach");
    }
    @Override public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate");
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView");
        return inflater.inflate(R.layout.fragment_demo, container, false);
    }
    @Override public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.d(TAG, "onViewCreated");
    }
    @Override public void onStart()   { super.onStart();   Log.d(TAG, "onStart"); }
    @Override public void onResume()  { super.onResume();  Log.d(TAG, "onResume"); }
    @Override public void onPause()   { super.onPause();   Log.d(TAG, "onPause"); }
    @Override public void onStop()    { super.onStop();    Log.d(TAG, "onStop"); }
    @Override public void onDestroyView() { super.onDestroyView(); Log.d(TAG, "onDestroyView"); }
    @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy"); }
    @Override public void onDetach()  { super.onDetach();  Log.d(TAG, "onDetach"); }
}

The host activity adds it with getSupportFragmentManager().beginTransaction().add(R.id.container, new DemoFragment()).commit();, and Logcat then shows the callbacks in order.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 · 1+4 marks

What is sub-activity? Develop an android application that displays AlertDialog to input radius of circle from user, compute area and circumference of circle, and show the result in Toast Message.

Answer

Sub-activity

A sub-activity is an activity started by another (parent) activity with startActivityForResult() (or the Activity Result API), so that it can return a result to the parent through setResult() and finish(). The parent receives it in onActivityResult(). It is used for tasks such as picking a contact or entering data on a separate screen.

Application: circle area and circumference using AlertDialog

A=πr2,C=2πrA = \pi r^2, \qquad C = 2\pi r

activity_main.xml: a Button with id btnInput and text "Enter Radius".

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.btnInput).setOnClickListener(v -> {
            EditText input = new EditText(this);
            input.setHint("Radius");
            input.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);

            new AlertDialog.Builder(this)
                .setTitle("Enter radius of circle")
                .setView(input)
                .setPositiveButton("Calculate", (dialog, which) -> {
                    String s = input.getText().toString();
                    if (s.isEmpty()) {
                        Toast.makeText(this, "Radius required", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    double r = Double.parseDouble(s);
                    double area = Math.PI * r * r;
                    double circ = 2 * Math.PI * r;
                    Toast.makeText(this,
                        String.format("Area = %.2f\nCircumference = %.2f", area, circ),
                        Toast.LENGTH_LONG).show();
                })
                .setNegativeButton("Cancel", null)
                .show();
        });
    }
}

For example, r=7r = 7 gives area 153.94153.94 and circumference 43.9843.98.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 · 1+4 marks

What is difference between XML and JSON? Write a java code to decode JSON data and display it in console.

Answer

XML vs JSON

BasisXMLJSON
Full formExtensible Markup LanguageJavaScript Object Notation
StructureTags with opening and closing elements and attributesKey-value pairs and arrays
SizeVerbose, larger payloadsCompact, smaller payloads
Readability / parsingNeeds an XML parser (DOM/SAX); slowerEasy to parse, maps directly to objects; faster
Data typesEverything is textSupports string, number, boolean, null, array, object
Comments / namespacesSupportedNot supported
UseDocuments, config, SOAPREST APIs, mobile apps

Decoding JSON in Java (using org.json)

import org.json.JSONArray;
import org.json.JSONObject;

public class JsonDecode {
    public static void main(String[] args) throws Exception {
        String json = "{\"name\":\"Ram\",\"age\":21,\"skills\":[\"Java\",\"Android\"],"
                    + "\"address\":{\"city\":\"Kathmandu\",\"country\":\"Nepal\"}}";

        JSONObject obj = new JSONObject(json);
        System.out.println("Name: " + obj.getString("name"));
        System.out.println("Age: " + obj.getInt("age"));

        JSONArray skills = obj.getJSONArray("skills");
        for (int i = 0; i < skills.length(); i++) {
            System.out.println("Skill " + (i + 1) + ": " + skills.getString(i));
        }

        JSONObject addr = obj.getJSONObject("address");
        System.out.println("City: " + addr.getString("city"));
        System.out.println("Country: " + addr.getString("country"));
    }
}

Output:

Name: Ram
Age: 21
Skill 1: Java
Skill 2: Android
City: Kathmandu
Country: Nepal

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 · 1+4 marks

What do you mean by view controller? Write a swift program to find diagonal sum of 3X3 matrix.

Answer

View controller

A view controller (UIViewController) is the iOS class that manages one screen of the app. It owns a root view and its subviews, loads and updates them with data, responds to user interaction (through outlets and actions) and handles lifecycle callbacks such as viewDidLoad(). It coordinates between the model and the views in the MVC pattern.

Swift program: diagonal sum of a 3x3 matrix

For a matrix AA, the main diagonal sum is ∑i=02Aii\sum_{i=0}^{2} A_{ii} and the secondary diagonal sum is ∑i=02Ai,2−i\sum_{i=0}^{2} A_{i,2-i}.

let matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

var mainSum = 0
var secondarySum = 0

for i in 0..<3 {
    mainSum += matrix[i][i]
    secondarySum += matrix[i][2 - i]
}

print("Main diagonal sum = \(mainSum)")
print("Secondary diagonal sum = \(secondarySum)")

Output: main diagonal 1+5+9=151+5+9 = 15, secondary diagonal 3+5+7=153+5+7 = 15.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 · 2+8 marks

What are benefits of intents in android? Develop an android application to implement phone directory using RecyclerView that shows contact name, phone number and profile image.

Answer

Benefits of intents

  • They let one component start another (activity, service, broadcast receiver) in a loosely coupled way.
  • They carry data between components through extras (putExtra() / getStringExtra()).
  • Implicit intents let the app use other apps' features (dial, send e-mail, open a web page, share, camera) without writing that functionality.
  • They enable system-wide messaging through broadcasts and reuse of components across apps.
  • They allow returning results from a launched activity.

Phone directory with RecyclerView

Add contact images (p1.png, p2.png, ...) to res/drawable.

Contact.java

public class Contact {
    String name, phone;
    int image;
    public Contact(String name, String phone, int image) {
        this.name = name; this.phone = phone; this.image = image;
    }
}

item_contact.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="wrap_content"
    android:orientation="horizontal" android:padding="8dp" android:gravity="center_vertical">
    <ImageView android:id="@+id/imgProfile"
        android:layout_width="60dp" android:layout_height="60dp"/>
    <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:orientation="vertical" android:layout_marginStart="12dp">
        <TextView android:id="@+id/tvName"  android:textSize="18sp" android:textStyle="bold"
            android:layout_width="wrap_content" android:layout_height="wrap_content"/>
        <TextView android:id="@+id/tvPhone"
            android:layout_width="wrap_content" android:layout_height="wrap_content"/>
    </LinearLayout>
</LinearLayout>

activity_main.xml

<androidx.recyclerview.widget.RecyclerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rvContacts"
    android:layout_width="match_parent" android:layout_height="match_parent"/>

ContactAdapter.java

public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.VH> {
    private final List<Contact> list;
    public ContactAdapter(List<Contact> list) { this.list = list; }

    static class VH extends RecyclerView.ViewHolder {
        ImageView img; TextView name, phone;
        VH(View v) {
            super(v);
            img = v.findViewById(R.id.imgProfile);
            name = v.findViewById(R.id.tvName);
            phone = v.findViewById(R.id.tvPhone);
        }
    }

    @NonNull @Override
    public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new VH(LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_contact, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull VH h, int position) {
        Contact c = list.get(position);
        h.img.setImageResource(c.image);
        h.name.setText(c.name);
        h.phone.setText(c.phone);
        h.itemView.setOnClickListener(v -> {
            Intent i = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + c.phone));
            v.getContext().startActivity(i);
        });
    }

    @Override public int getItemCount() { return list.size(); }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        List<Contact> contacts = new ArrayList<>();
        contacts.add(new Contact("Ram Sharma", "9841000001", R.drawable.p1));
        contacts.add(new Contact("Sita Thapa", "9841000002", R.drawable.p2));
        contacts.add(new Contact("Hari Karki", "9841000003", R.drawable.p3));

        RecyclerView rv = findViewById(R.id.rvContacts);
        rv.setLayoutManager(new LinearLayoutManager(this));
        rv.setAdapter(new ContactAdapter(contacts));
    }
}

Tapping a contact fires an implicit ACTION_DIAL intent, so the intent benefit is used directly.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 · 2+8 marks

What are the parameters of the insert() method in Android SQLiteDatabase? Develop an android application to modify and remove the details of Employee from SQLite table Employee (ID, Name, Department, and Salary) based on given Employee ID.

Answer

(a) Parameters of insert()

long insert(String table, String nullColumnHack, ContentValues values)
  • table is the name of the table into which the row is inserted.
  • nullColumnHack is optional (usually null). SQL does not allow inserting a completely empty row, so if values is empty, this column name is used and set to NULL to make a valid statement.
  • values is a ContentValues object holding column name and value pairs for the new row.
  • The return value is the row ID of the new row, or -1 if an error occurred.

(b) Application to modify and remove an Employee by ID

DBHelper.java

import android.content.*;
import android.database.sqlite.*;

public class DBHelper extends SQLiteOpenHelper {
    public DBHelper(Context c) { super(c, "company.db", null, 1); }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE Employee(ID INTEGER PRIMARY KEY, Name TEXT, Department TEXT, Salary REAL)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int o, int n) {
        db.execSQL("DROP TABLE IF EXISTS Employee");
        onCreate(db);
    }

    public boolean updateEmployee(int id, String name, String dept, double salary) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("Name", name);
        cv.put("Department", dept);
        cv.put("Salary", salary);
        return db.update("Employee", cv, "ID=?", new String[]{String.valueOf(id)}) > 0;
    }

    public boolean deleteEmployee(int id) {
        SQLiteDatabase db = getWritableDatabase();
        return db.delete("Employee", "ID=?", new String[]{String.valueOf(id)}) > 0;
    }
}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical" android:padding="16dp">
    <EditText android:id="@+id/etId" android:hint="Employee ID"
        android:inputType="number" android:layout_width="match_parent" android:layout_height="wrap_content"/>
    <EditText android:id="@+id/etName" android:hint="Name"
        android:layout_width="match_parent" android:layout_height="wrap_content"/>
    <EditText android:id="@+id/etDept" android:hint="Department"
        android:layout_width="match_parent" android:layout_height="wrap_content"/>
    <EditText android:id="@+id/etSalary" android:hint="Salary" android:inputType="numberDecimal"
        android:layout_width="match_parent" android:layout_height="wrap_content"/>
    <Button android:id="@+id/btnUpdate" android:text="Modify"
        android:layout_width="match_parent" android:layout_height="wrap_content"/>
    <Button android:id="@+id/btnDelete" android:text="Remove"
        android:layout_width="match_parent" android:layout_height="wrap_content"/>
</LinearLayout>

MainActivity.java

import android.os.Bundle;
import android.view.View;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    EditText etId, etName, etDept, etSalary;
    DBHelper helper;

    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.activity_main);
        helper = new DBHelper(this);
        etId = findViewById(R.id.etId);
        etName = findViewById(R.id.etName);
        etDept = findViewById(R.id.etDept);
        etSalary = findViewById(R.id.etSalary);

        findViewById(R.id.btnUpdate).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (etId.getText().toString().isEmpty()) {
                    Toast.makeText(MainActivity.this, "Enter Employee ID", Toast.LENGTH_SHORT).show();
                    return;
                }
                int id = Integer.parseInt(etId.getText().toString());
                double sal = etSalary.getText().toString().isEmpty() ? 0
                        : Double.parseDouble(etSalary.getText().toString());
                boolean ok = helper.updateEmployee(id, etName.getText().toString(),
                        etDept.getText().toString(), sal);
                Toast.makeText(MainActivity.this, ok ? "Employee updated" : "No employee with this ID",
                        Toast.LENGTH_SHORT).show();
            }
        });

        findViewById(R.id.btnDelete).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (etId.getText().toString().isEmpty()) {
                    Toast.makeText(MainActivity.this, "Enter Employee ID", Toast.LENGTH_SHORT).show();
                    return;
                }
                int id = Integer.parseInt(etId.getText().toString());
                boolean ok = helper.deleteEmployee(id);
                Toast.makeText(MainActivity.this, ok ? "Employee removed" : "No employee with this ID",
                        Toast.LENGTH_SHORT).show();
            }
        });
    }
}

update() and delete() return the number of rows affected, so a value above 0 confirms that an employee with the given ID existed. The ? placeholders with whereArgs prevent SQL injection.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 · 10 marks

a) Write a java program in Android to send username and password to remote server using Volley POST request and display the server response in Toast message?
b) Develop an android application to display the user's current location(write only .java and manifest file)

Answer

(a) Volley POST request

Add the dependency implementation 'com.android.volley:volley:1.2.1' and the permission <uses-permission android:name="android.permission.INTERNET"/>.

import android.os.Bundle;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.*;
import com.android.volley.toolbox.*;
import java.util.*;

public class LoginActivity extends AppCompatActivity {
    EditText etUser, etPass;
    final String URL = "https://example.com/api/login.php";

    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.activity_login);
        etUser = findViewById(R.id.etUser);
        etPass = findViewById(R.id.etPass);
        findViewById(R.id.btnLogin).setOnClickListener(v -> sendData());
    }

    private void sendData() {
        final String user = etUser.getText().toString();
        final String pass = etPass.getText().toString();
        RequestQueue queue = Volley.newRequestQueue(this);

        StringRequest request = new StringRequest(Request.Method.POST, URL,
            new Response.Listener<String>() {
                @Override public void onResponse(String response) {
                    Toast.makeText(LoginActivity.this, response, Toast.LENGTH_LONG).show();
                }
            },
            new Response.ErrorListener() {
                @Override public void onErrorResponse(VolleyError error) {
                    Toast.makeText(LoginActivity.this, "Error: " + error.getMessage(),
                            Toast.LENGTH_LONG).show();
                }
            }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                params.put("username", user);
                params.put("password", pass);
                return params;
            }
        };
        queue.add(request);
    }
}

getParams() supplies the form fields sent in the POST body. The response string returned by the server is shown in a Toast.

(b) Display the user's current location

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.location">
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <application android:label="Location App" android:theme="@style/Theme.AppCompat.Light">
        <activity android:name=".MainActivity" android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

MainActivity.java

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.*;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

public class MainActivity extends AppCompatActivity implements LocationListener {
    TextView tv;
    LocationManager lm;

    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        tv = new TextView(this);
        tv.setTextSize(18);
        tv.setPadding(24, 24, 24, 24);
        setContentView(tv);
        lm = (LocationManager) getSystemService(LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        } else {
            start();
        }
    }

    @SuppressWarnings("MissingPermission")
    private void start() {
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 1, this);
    }

    @Override
    public void onRequestPermissionsResult(int code, String[] perms, int[] res) {
        super.onRequestPermissionsResult(code, perms, res);
        if (res.length > 0 && res[0] == PackageManager.PERMISSION_GRANTED) start();
        else tv.setText("Location permission denied");
    }

    @Override
    public void onLocationChanged(Location loc) {
        tv.setText("Latitude: " + loc.getLatitude() + "\nLongitude: " + loc.getLongitude());
    }

    @Override protected void onDestroy() { super.onDestroy(); lm.removeUpdates(this); }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

Questions from TU BCA 2021 Sixth Semester Applied Economics (TU board exam, 2021), TU BCA 2022 Sixth Semester Applied Economics (TU board exam, 2022), TU BCA 2023 Sixth Semester Applied Economics (TU board exam, 2023), TU BCA 2024 Sixth Semester Applied Economics (TU board exam, 2024), TU BCA 2025 Sixth Semester Applied Economics (TU board exam, 2025), TU BCA 2026 Sixth Semester Applied Economics (TU board exam, 2026), TU BCA 2021 Sixth Semester Distributed System (TU board exam, 2021), TU BCA 2022 Sixth Semester Distributed System (TU board exam, 2022), TU BCA 2023 Sixth Semester Distributed System (TU board exam, 2023), TU BCA 2024 Sixth Semester Distributed System (TU board exam, 2024), TU BCA 2025 Sixth Semester Distributed System (TU board exam, 2025), TU BCA 2026 Sixth Semester Distributed System (TU board exam, 2026), TU BCA 2021 Sixth Semester Advanced Java Programming (TU board exam, 2021), TU BCA 2022 Sixth Semester Advanced Java Programming (TU board exam, 2022), TU BCA 2023 Sixth Semester Advanced Java Programming (TU board exam, 2023), TU BCA 2024 Sixth Semester Advanced Java Programming (TU board exam, 2024), TU BCA 2025 Sixth Semester Advanced Java Programming (TU board exam, 2025), TU BCA 2026 Sixth Semester Advanced Java Programming (TU board exam, 2026), TU BCA 2021 Sixth Semester Mobile Programming (TU board exam, 2021), TU BCA 2022 Sixth Semester Mobile Programming (TU board exam, 2022), TU BCA 2023 Sixth Semester Mobile Programming (TU board exam, 2023), TU BCA 2024 Sixth Semester Mobile Programming (TU board exam, 2024), TU BCA 2025 Sixth Semester Mobile Programming (TU board exam, 2025), TU BCA 2026 Sixth Semester Mobile Programming (TU board exam, 2026), TU BCA 2021 Sixth Semester Network Programming (TU board exam, 2021), TU BCA 2022 Sixth Semester Network Programming (TU board exam, 2022), TU BCA 2023 Sixth Semester Network Programming (TU board exam, 2023), TU BCA 2024 Sixth Semester Network Programming (TU board exam, 2024) and TU BCA 2025 Sixth Semester Network Programming (TU board exam, 2025). Answers are written for this site; check them against your class notes.