Skip to content
| Marketplace
Sign in
Visual Studio Code>Other>Sparrow ToolkitNew to Visual Studio Code? Get it now.
Sparrow Toolkit

Sparrow Toolkit

mrkraken

|
2 installs
| (0) | Free
An offline VS Code extension containing important practical notes.
Installation
Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter.
Copied to clipboard
More Info

✅ ASSIGNMENT 1 — Design a Registration / Survey Form Using UI Controls

(Source: Your Assignment 11 file)

Aim

Create an Android UI with basic controls like EditText, RadioButton, CheckBox, Spinner, and Button.


Steps

  1. Open Android Studio → Create Empty Activity App
  2. Open activity_main.xml (Design View)
  3. Drag required components (see UI Section)
  4. Open MainActivity.java
  5. Paste the full Java code (unchanged)
  6. Run the app on Emulator / USB Device

Java Code (unchanged)

package com.example.registrationform;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
public class MainActivity extends AppCompatActivity {

    EditText name, email;
    RadioButton male, female;
    CheckBox cricket, football, hockey;
    Spinner city;
    Button submit;

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

        name = findViewById(R.id.name);
        email = findViewById(R.id.email);
        male = findViewById(R.id.male);
        female = findViewById(R.id.female);
        cricket = findViewById(R.id.cricket);
        football = findViewById(R.id.football);
        hockey = findViewById(R.id.hockey);
        city = findViewById(R.id.city);
        submit = findViewById(R.id.submit);

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String data = name.getText().toString() + "\n"
                        + email.getText().toString() + "\n";

                if (male.isChecked()) data += "Male\n";
                if (female.isChecked()) data += "Female\n";

                if (cricket.isChecked()) data += "Cricket\n";
                if (football.isChecked()) data += "Football\n";
                if (hockey.isChecked()) data += "Hockey\n";

                data += city.getSelectedItem().toString();

                Toast.makeText(MainActivity.this, data, Toast.LENGTH_LONG).show();
            }
        });
    }
}

UI Description (How the Screen Should Look)

A scrollable form containing:

  • Name → EditText

  • Email → EditText

  • Gender → Two RadioButtons inside RadioGroup (Male, Female)

  • Hobbies → Three CheckBoxes (Cricket, Football, Hockey)

  • City → Spinner (Dropdown)

    • Items: Mumbai, Pune, Delhi, Bangalore
  • Submit Button

Layout arrangement:

Name (EditText)
Email (EditText)
Gender:
   ( ) Male   ( ) Female
Hobbies:
   [ ] Cricket  [ ] Football  [ ] Hockey
City (Spinner)
[Submit Button]

Required Components

  • EditText (2)
  • RadioGroup (1) with RadioButton (2)
  • CheckBox (3)
  • Spinner (1)
  • Button (1)
  • Parent layout: LinearLayout (Vertical)

Notes

  • Use LinearLayout for easy vertical arrangement
  • Spinner needs a simple ArrayAdapter

--------------------------------------------------------------

✅ ASSIGNMENT 2 — Implement Explicit & Implicit Intents

(Source: Your Assignment 12 file)

Aim

Use Explicit Intent (open another activity) and Implicit Intent (dial, message, browser, mail).


Steps

  1. Create Android App → Add two activities (MainActivity.java, SecondActivity.java)
  2. Design UI with required buttons
  3. Paste Java code in both activities
  4. Add necessary permissions (CALL, SMS) if needed
  5. Run the app

Java Code (unchanged)

package com.example.intents;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    Button next, dial, sms, url, email;

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

        next = findViewById(R.id.next);
        dial = findViewById(R.id.dial);
        sms = findViewById(R.id.sms);
        url = findViewById(R.id.url);
        email = findViewById(R.id.email);

        next.setOnClickListener(v -> {
            Intent i = new Intent(MainActivity.this, SecondActivity.class);
            startActivity(i);
        });

        dial.setOnClickListener(v -> {
            Intent i = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:9876543210"));
            startActivity(i);
        });

        sms.setOnClickListener(v -> {
            Intent i = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:9876543210"));
            i.putExtra("sms_body", "Hello!");
            startActivity(i);
        });

        url.setOnClickListener(v -> {
            Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("https://google.com"));
            startActivity(i);
        });

        email.setOnClickListener(v -> {
            Intent i = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:test@gmail.com"));
            i.putExtra(Intent.EXTRA_SUBJECT, "Subject Here");
            startActivity(i);
        });
    }
}

UI Description

Your screen should have five buttons:

[ Open Next Activity ]
[ Dial Number ]
[ Send SMS ]
[ Open URL ]
[ Send Email ]

Second screen (SecondActivity) can simply display a TextView: “Welcome to Second Activity”


Required Components

  • Button × 5
  • SecondActivity → TextView
  • Layout: LinearLayout (Vertical)

Notes

  • ACTION_DIAL does NOT require permission
  • ACTION_CALL requires CALL_PHONE permission
  • Use explicit intent to switch activities

--------------------------------------------------------------

✅ ASSIGNMENT 3 — Notification in Android

(Source: Assignment 13)

Aim

Create a Notification with a title and message using NotificationManager & NotificationChannel.


Steps

  1. Create new Android project
  2. Add one Button → “Show Notification”
  3. Paste Java code
  4. Run the app → Click button → Notification appears

Java Code (unchanged)

package com.example.notification;

import androidx.appcompat.app.AppCompatActivity;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.core.app.NotificationCompat;

public class MainActivity extends AppCompatActivity {

    Button notify;

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

        notify.setOnClickListener(v -> {
            NotificationManager manager =
                    (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel channel =
                        new NotificationChannel("mychannel", "MyChannel",
                                NotificationManager.IMPORTANCE_DEFAULT);
                manager.createNotificationChannel(channel);
            }

            NotificationCompat.Builder builder =
                    new NotificationCompat.Builder(MainActivity.this, "mychannel")
                            .setContentTitle("Sample Notification")
                            .setContentText("This is test message...")
                            .setSmallIcon(R.drawable.ic_launcher_foreground);

            manager.notify(1, builder.build());
        });
    }
}

UI Description

Simple UI:

[ Show Notification ]

Required Components

  • Button (1)
  • Layout: LinearLayout

Notes

  • Android 8.0+ requires NotificationChannel
  • Use a valid small icon

--------------------------------------------------------------

✅ ASSIGNMENT 4 — Shared Preferences Login System

(Source: Assignment 14)

Aim

Store username & password using SharedPreferences.


Steps

  1. Create app → UI with fields: Username, Password, Login, Display
  2. Copy Java code
  3. Run → Login → Display saved data

Java Code (unchanged)

package com.example.sharedpref;

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

public class MainActivity extends AppCompatActivity {

    EditText user, pass;
    Button save, show;
    SharedPreferences pref;

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

        user = findViewById(R.id.user);
        pass = findViewById(R.id.pass);
        save = findViewById(R.id.save);
        show = findViewById(R.id.show);
        pref = getSharedPreferences("data", MODE_PRIVATE);

        save.setOnClickListener(v -> {
            SharedPreferences.Editor edit = pref.edit();
            edit.putString("u", user.getText().toString());
            edit.putString("p", pass.getText().toString());
            edit.apply();
            Toast.makeText(this, "Saved!", Toast.LENGTH_SHORT).show();
        });

        show.setOnClickListener(v -> {
            String u = pref.getString("u", "");
            String p = pref.getString("p", "");
            Toast.makeText(this, u + "\n" + p, Toast.LENGTH_LONG).show();
        });
    }
}

UI Description

Simple login-like page:

Username (EditText)
Password (EditText)
[ Save ]
[ Show ]

Required Components

  • EditText × 2
  • Button × 2
  • LinearLayout (vertical)

Notes

  • SharedPreferences store data permanently until uninstalled
  • No database required

--------------------------------------------------------------

✅ ASSIGNMENT 5 — Internal & External File Storage

(Source: Assignment 15)

Aim

Perform Write and Read operations using FileInputStream and FileOutputStream.


Steps

  1. Create Android project
  2. Add EditText for input
  3. Add two Buttons: Save, Load
  4. Paste code
  5. Run the app

Java Code (unchanged)

package com.example.filestorage;

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

public class MainActivity extends AppCompatActivity {

    EditText data;
    Button save, load;

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

        data = findViewById(R.id.data);
        save = findViewById(R.id.save);
        load = findViewById(R.id.load);

        save.setOnClickListener(v -> {
            try {
                FileOutputStream fout = openFileOutput("myfile.txt", MODE_PRIVATE);
                fout.write(data.getText().toString().getBytes());
                fout.close();
                Toast.makeText(this, "Saved!", Toast.LENGTH_SHORT).show();
            } catch (Exception e) { }
        });

        load.setOnClickListener(v -> {
            try {
                FileInputStream fin = openFileInput("myfile.txt");
                int c;
                String temp = "";
                while ((c = fin.read()) != -1) {
                    temp += Character.toString((char) c);
                }
                fin.close();
                Toast.makeText(this, temp, Toast.LENGTH_LONG).show();
            } catch (Exception e) { }
        });
    }
}

UI Description

Enter Data (EditText)

[ Save ]
[ Load ]

Required Components

  • EditText (1)
  • Button (2)
  • LinearLayout (vertical)

Notes

  • File saved in app's internal storage
  • No runtime permissions needed for internal storage

✅ ASSIGNMENT 6 — CRUD Operations Using SQLite Database

(Source: Assignment 16 file)

Aim

Perform Insert, Update, Delete, and View operations using SQLite in Android Studio.


✔ Files Typically Required

Even though code is all you need for the exam, SQLite apps usually contain:

  • MainActivity.java
  • DBHelper.java (SQLiteOpenHelper class)

Your docx contains both files → I will include them intact.


Steps

  1. Create a new Android project
  2. Create UI with 3 EditTexts + 4 Buttons
  3. Create a new class → DBHelper.java
  4. Paste the DB helper code
  5. Paste MainActivity code
  6. Run app → Perform Insert/Update/Delete/View

Java Code (unchanged – DBHelper.java)

package com.example.sqlite;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {

    public DBHelper(Context context) {
        super(context, "Userdata.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create Table Userdetails(name TEXT primary key, contact TEXT, dob TEXT)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("drop Table if exists Userdetails");
    }

    public Boolean insertuserdata(String name, String contact, String dob) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("name", name);
        cv.put("contact", contact);
        cv.put("dob", dob);

        long result = db.insert("Userdetails", null, cv);

        return result != -1;
    }

    public Boolean updateuserdata(String name, String contact, String dob) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("contact", contact);
        cv.put("dob", dob);

        Cursor cursor = db.rawQuery("Select * from Userdetails where name=?", new String[]{name});
        if (cursor.getCount() > 0) {
            long result = db.update("Userdetails", cv, "name=?", new String[]{name});
            return result != -1;
        } else {
            return false;
        }
    }

    public Boolean deletedata(String name) {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery("Select * from Userdetails where name=?", new String[]{name});
        if (cursor.getCount() > 0) {
            long result = db.delete("Userdetails", "name=?", new String[]{name});
            return result != -1;
        } else {
            return false;
        }
    }

    public Cursor getdata() {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.rawQuery("Select * from Userdetails", null);
    }
}

Java Code (unchanged – MainActivity.java)

package com.example.sqlite;

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

public class MainActivity extends AppCompatActivity {

    EditText name, contact, dob;
    Button insert, update, delete, view;
    DBHelper DB;

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

        name = findViewById(R.id.name);
        contact = findViewById(R.id.contact);
        dob = findViewById(R.id.dob);
        insert = findViewById(R.id.insert);
        update = findViewById(R.id.update);
        delete = findViewById(R.id.delete);
        view = findViewById(R.id.view);

        DB = new DBHelper(this);

        insert.setOnClickListener(v -> {
            Boolean check = DB.insertuserdata(name.getText().toString(),
                    contact.getText().toString(), dob.getText().toString());
            Toast.makeText(this, check ? "Inserted" : "Not Inserted", Toast.LENGTH_SHORT).show();
        });

        update.setOnClickListener(v -> {
            Boolean check = DB.updateuserdata(name.getText().toString(),
                    contact.getText().toString(), dob.getText().toString());
            Toast.makeText(this, check ? "Updated" : "Not Updated", Toast.LENGTH_SHORT).show();
        });

        delete.setOnClickListener(v -> {
            Boolean check = DB.deletedata(name.getText().toString());
            Toast.makeText(this, check ? "Deleted" : "Not Deleted", Toast.LENGTH_SHORT).show();
        });

        view.setOnClickListener(v -> {
            Cursor cursor = DB.getdata();
            if (cursor.getCount() == 0) {
                Toast.makeText(this, "No Entries", Toast.LENGTH_SHORT).show();
                return;
            }
            StringBuilder buffer = new StringBuilder();
            while (cursor.moveToNext()) {
                buffer.append("Name: ").append(cursor.getString(0)).append("\n");
                buffer.append("Contact: ").append(cursor.getString(1)).append("\n");
                buffer.append("DOB: ").append(cursor.getString(2)).append("\n\n");
            }
            Toast.makeText(this, buffer.toString(), Toast.LENGTH_LONG).show();
        });
    }
}

UI Description

The app needs the following layout:

Name (EditText)
Contact (EditText)
DOB (EditText)

[ Insert ]
[ Update ]
[ Delete ]
[ View All ]

Each button should be below each other in vertical order.


Required Components

  • EditText × 3
  • Button × 4
  • LinearLayout (Vertical)

Notes

  • SQLiteOpenHelper auto-creates DB on first install
  • Primary key = name
  • If update/delete doesn't work, check if record exists

--------------------------------------------------------------

✅ ASSIGNMENT 7 — Firebase Realtime Database CRUD

(Source: Assignment 17)


Aim

Perform Insert, Update, Delete, View using Firebase Realtime Database.


Steps

  1. Create Android project
  2. Go to Firebase Console → Create project
  3. Add Android app → Package name
  4. Download google-services.json → paste into app/
  5. Add Firebase dependencies (from assignment)
  6. Design UI with Name, Contact, Age fields
  7. Paste Java code
  8. Run app → test CRUD operations

Java Code (unchanged – MainActivity.java)

package com.example.firebasedb;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.*;

import com.google.firebase.database.*;

public class MainActivity extends AppCompatActivity {

    EditText name, contact, age;
    Button insert, update, delete, view;

    FirebaseDatabase rootNode;
    DatabaseReference reference;

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

        name = findViewById(R.id.name);
        contact = findViewById(R.id.contact);
        age = findViewById(R.id.age);

        insert = findViewById(R.id.insert);
        update = findViewById(R.id.update);
        delete = findViewById(R.id.delete);
        view = findViewById(R.id.view);

        rootNode = FirebaseDatabase.getInstance();
        reference = rootNode.getReference("Users");

        insert.setOnClickListener(v -> {
            String n = name.getText().toString();
            String c = contact.getText().toString();
            String a = age.getText().toString();

            User user = new User(n, c, a);
            reference.child(n).setValue(user);

            Toast.makeText(this, "Inserted", Toast.LENGTH_SHORT).show();
        });

        update.setOnClickListener(v -> {
            String n = name.getText().toString();
            reference.child(n).child("contact")
                    .setValue(contact.getText().toString());
            reference.child(n).child("age")
                    .setValue(age.getText().toString());

            Toast.makeText(this, "Updated", Toast.LENGTH_SHORT).show();
        });

        delete.setOnClickListener(v -> {
            String n = name.getText().toString();
            reference.child(n).removeValue();

            Toast.makeText(this, "Deleted", Toast.LENGTH_SHORT).show();
        });

        view.setOnClickListener(v -> reference.get()
                .addOnSuccessListener(dataSnapshot -> {
                    StringBuilder buffer = new StringBuilder();
                    for (DataSnapshot ds : dataSnapshot.getChildren()) {
                        buffer.append(ds.getKey()).append("\n");
                    }
                    Toast.makeText(this, buffer.toString(), Toast.LENGTH_LONG).show();
                }));
    }

    public static class User {
        public String name, contact, age;

        public User() { }

        public User(String name, String contact, String age) {
            this.name = name;
            this.contact = contact;
            this.age = age;
        }
    }
}

UI Description

Name (EditText)
Contact (EditText)
Age (EditText)

[ Insert ]
[ Update ]
[ Delete ]
[ View ]

Same layout as SQLite example.


Required Components

  • EditText × 3
  • Button × 4
  • LinearLayout (vertical)

Notes

  • Internet must be ON

  • google-services.json is mandatory

  • Firebase rules should be set to:

    allow read, write: if true;
    

✅ ASSIGNMENT 8 — Simple Animation in Android

(Source: Assignment 18)

Aim

Create a simple animation using Android's AnimationUtils (Fade, Zoom, Rotate, Move).


Steps

  1. Create Android project
  2. Add an ImageView to UI
  3. Create an anim folder inside res/
  4. Add animation XML files (fade.xml, zoom.xml etc.)
  5. Paste MainActivity code
  6. Run the app

Java Code (unchanged)

package com.example.animation;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

    ImageView img;

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

        Animation animation = AnimationUtils.loadAnimation(this, R.anim.zoom);
        img.startAnimation(animation);
    }
}

UI Description

Centered ImageView
(Any image from drawable folder)

Position: center of screen.


Required Components

  • ImageView

  • res/anim/ folder with:

    • zoom.xml
    • fade.xml
    • rotate.xml
    • slide.xml (optional)

Notes

  • Keep image in drawable folder
  • You can switch animations by loading different XML files

--------------------------------------------------------------

✅ ASSIGNMENT 9 — Multimedia App (Image, Audio, Video)

(Source: Assignment 19)

Aim

Create an app that displays an image, plays audio, and plays a video.


Steps

  1. Create Android project

  2. Add:

    • ImageView
    • Buttons: Play Audio, Play Video
    • VideoView
  3. Add media files to res/raw folder

  4. Paste MainActivity code

  5. Run the app


Java Code (unchanged)

package com.example.multimedia;

import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.widget.*;

public class MainActivity extends AppCompatActivity {

    ImageView img;
    Button playAudio, playVideo;
    VideoView video;
    MediaPlayer mp;

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

        img = findViewById(R.id.img);
        playAudio = findViewById(R.id.playAudio);
        playVideo = findViewById(R.id.playVideo);
        video = findViewById(R.id.video);

        mp = MediaPlayer.create(this, R.raw.music);

        playAudio.setOnClickListener(v -> mp.start());

        playVideo.setOnClickListener(v -> {
            Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.video);
            video.setVideoURI(uri);
            video.start();
        });
    }
}

UI Description

[ ImageView (top) ]

[ Play Audio Button ]
[ Play Video Button ]

[ VideoView (bottom) ]

Required Components

  • ImageView (display image)

  • Button × 2

  • VideoView

  • Media files:

    • /res/raw/music.mp3
    • /res/raw/video.mp4

Notes

  • Use small-sized video for fast playback
  • Use MP3 format for audio

--------------------------------------------------------------

✅ ASSIGNMENT 10 — GPS / Location Program

(Source: Assignment 20)

Aim

Fetch the current GPS location (latitude, longitude) using LocationManager.


Steps

  1. Create Android project

  2. Add:

    • 2 TextViews (Latitude, Longitude)
    • 1 Button (Get Location)
  3. Add permissions to AndroidManifest.xml:

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    
  4. Enable runtime permission request

  5. Paste MainActivity code

  6. Run on real device (GPS needed)


Java Code (unchanged)

package com.example.gpslocation;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.*;

public class MainActivity extends AppCompatActivity implements LocationListener {

    TextView lat, lon;
    Button getLoc;
    LocationManager locationManager;

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

        lat = findViewById(R.id.lat);
        lon = findViewById(R.id.lon);
        getLoc = findViewById(R.id.getLoc);

        getLoc.setOnClickListener(v -> {

            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {

                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
                return;
            }

            locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                    5000, 5, this);
        });
    }

    @Override
    public void onLocationChanged(Location location) {
        lat.setText("Latitude: " + location.getLatitude());
        lon.setText("Longitude: " + location.getLongitude());
    }
}

UI Description

Latitude: _____________   (TextView)
Longitude: ____________   (TextView)

[ Get Location ]

Required Components

  • TextView × 2
  • Button × 1
  • LinearLayout

Notes

  • Works best on a physical Android device
  • Turn ON GPS
  • Request runtime permission for location

✅ ASSIGNMENT 11 — REST API Using OkHttp

(Source: Assignment 21)

Aim

Perform a GET request using OkHttp and display API response inside a TextView.


Steps

  1. Create Android project

  2. Add:

    • EditText (API URL)
    • Button (Fetch)
    • TextView (Output)
  3. Add internet permission:

    <uses-permission android:name="android.permission.INTERNET"/>
    
  4. Add OkHttp dependency to build.gradle (Module)

    implementation 'com.squareup.okhttp3:okhttp:4.10.0'
    
  5. Paste the given Java code

  6. Run → Press “Fetch” to load data


Java Code (unchanged)

package com.example.okhttpapi;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.*;
import okhttp3.*;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    EditText url;
    Button fetch;
    TextView output;

    OkHttpClient client = new OkHttpClient();

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

        url = findViewById(R.id.url);
        fetch = findViewById(R.id.fetch);
        output = findViewById(R.id.output);

        fetch.setOnClickListener(v -> fetchData(url.getText().toString()));
    }

    void fetchData(String u) {
        Request request = new Request.Builder()
                .url(u)
                .build();

        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> output.setText("Error: " + e.getMessage()));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                runOnUiThread(() -> output.setText(res));
            }
        });
    }
}

UI Description

Enter URL: [ EditText ]

[ Fetch ]

API Response:
[ Large TextView ]

Required Components

  • EditText × 1
  • Button × 1
  • TextView × 1
  • LinearLayout (vertical)

Notes

  • Internet permission is mandatory
  • Use GET API URLs like: https://jsonplaceholder.typicode.com/posts/1

--------------------------------------------------------------

✅ ASSIGNMENT 12 — REST API Using Volley

(Source: Assignment 22)

Aim

Perform GET request using Volley and display JSON response.


Steps

  1. Create Android project

  2. Add:

    • Button “Fetch Data”
    • TextView for result
  3. Add internet permission

  4. Add Volley dependency:

    implementation 'com.android.volley:volley:1.2.1'
    
  5. Paste Java code

  6. Run app → Press Fetch


Java Code (unchanged)

package com.example.volleyapi;

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

import com.android.volley.*;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {

    Button fetch;
    TextView output;

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

        fetch = findViewById(R.id.fetch);
        output = findViewById(R.id.output);

        fetch.setOnClickListener(v -> fetchData());
    }

    void fetchData() {

        String url = "https://jsonplaceholder.typicode.com/todos/1";

        JsonObjectRequest request = new JsonObjectRequest(
                Request.Method.GET, url, null,
                response -> output.setText(response.toString()),
                error -> output.setText("Error: " + error.toString())
        );

        RequestQueue queue = Volley.newRequestQueue(this);
        queue.add(request);
    }
}

UI Description

[ Fetch Data ]

Response:
[ TextView ]

Required Components

  • Button × 1
  • TextView × 1

Notes

  • Volley handles async threads internally
  • Very easy for exam — short code, fast execution

--------------------------------------------------------------

✅ ASSIGNMENT 13 — REST API Using Retrofit

(Source: Assignment 23)

Aim

Fetch data from API using Retrofit + Data Model + Interface.


Steps

  1. Create Android project

  2. Add:

    • Button (Load Data)
    • TextView (Result)
  3. Add Retrofit dependencies:

    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    
  4. Create API Interface file

  5. Create Model class

  6. Paste MainActivity code

  7. Run app


Java Code (unchanged — MainActivity.java)

package com.example.retrofitapi;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.*;

import retrofit2.*;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    Button load;
    TextView output;

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

        load = findViewById(R.id.load);
        output = findViewById(R.id.output);

        load.setOnClickListener(v -> fetchData());
    }

    void fetchData() {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://jsonplaceholder.typicode.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        Api api = retrofit.create(Api.class);

        Call<Post> call = api.getPost();

        call.enqueue(new Callback<Post>() {
            @Override
            public void onResponse(Call<Post> call, Response<Post> response) {
                Post p = response.body();
                output.setText(p.id + "\n" + p.title + "\n" + p.body);
            }

            @Override
            public void onFailure(Call<Post> call, Throwable t) {
                output.setText("Error: " + t.getMessage());
            }
        });
    }
}

Java Code (unchanged — Api.java)

package com.example.retrofitapi;

import retrofit2.Call;
import retrofit2.http.GET;

public interface Api {
    @GET("posts/1")
    Call<Post> getPost();
}

Java Code (unchanged — Post.java)

package com.example.retrofitapi;

public class Post {
    public int id;
    public String title;
    public String body;
}

UI Description

[ Load Data ]

Result:
[ TextView (multiline) ]

Required Components

  • Button × 1
  • TextView × 1

Notes

  • Retrofit is MOST PROFESSIONAL API method
  • Requires Interface + Model class
  • Very commonly asked in viva

⚡ Important Notes Before Starting Flutter Assignments

  • Use Android Studio → Flutter Project → New Flutter App
  • Make sure Flutter SDK path is set
  • Use main.dart only unless assignment requires multiple screens
  • Do NOT modify your given Dart code
  • UI description will explain where to place widgets

✅ ASSIGNMENT 14 — Stateful & Stateless Widgets

(Source: Assignment 24)

Aim

Create a Flutter app demonstrating StatelessWidget and StatefulWidget.


Steps

  1. Create Flutter project in Android Studio
  2. Replace main.dart with given code
  3. Run the app
  4. Observe static vs dynamic UI behavior

Dart Code (unchanged)

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: FirstScreen(),
    );
  }
}

class FirstScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Stateless Widget")),
      body: Center(
        child: Text("This is Stateless Widget"),
      ),
    );
  }
}

class SecondScreen extends StatefulWidget {
  @override
  _SecondScreenState createState() => _SecondScreenState();
}

class _SecondScreenState extends State<SecondScreen> {
  int counter = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Stateful Widget")),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text("Counter: $counter"),
            ElevatedButton(
              onPressed: () {
                setState(() {
                  counter++;
                });
              },
              child: Text("Increment"),
            )
          ],
        ),
      ),
    );
  }
}

UI Description

Screen 1 — StatelessWidget

AppBar: "Stateless Widget"
Centered Text: "This is Stateless Widget"

Screen 2 — StatefulWidget

AppBar: "Stateful Widget"

Counter: 0
[ Increment ]

Required Components

  • Text
  • ElevatedButton
  • Column
  • AppBar
  • Scaffold

Notes

  • Stateless → UI does NOT change
  • Stateful → UI changes using setState

--------------------------------------------------------------

✅ ASSIGNMENT 15 — Display a List in Flutter

(Source: Assignment 25)

Aim

Show a scrollable list of items using ListView.


Steps

  1. Open Flutter project
  2. Replace main.dart with given code
  3. Run the app → See list
  4. Modify as needed

Dart Code (unchanged)

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: MyList(),
  ));
}

class MyList extends StatelessWidget {
  var items = ["Apple", "Banana", "Mango", "Orange", "Pineapple"];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("ListView Example")),
      body: ListView.builder(
        itemCount: items.length,
        itemBuilder: (context, index) {
          return ListTile(
            leading: Icon(Icons.food_bank),
            title: Text(items[index]),
          );
        },
      ),
    );
  }
}

UI Description

AppBar: "ListView Example"

List (Scrollable):
   [🍎  Apple]
   [🍌  Banana]
   [🥭  Mango]
   [🍊  Orange]
   [🍍  Pineapple]

Required Components

  • ListView.builder
  • ListTile
  • Icon
  • AppBar

Notes

  • Perfect for basic Flutter list practical
  • Uses default Material Icons

--------------------------------------------------------------

✅ ASSIGNMENT 16 — Flutter Form (TextField, Checkbox, Switch, Dropdown, Button)

(Source: Assignment 26)

Aim

Create a full form UI with input fields and a submit button.


Steps

  1. Create a Flutter project
  2. Replace main.dart
  3. Run the app
  4. Enter form data and submit

Dart Code (unchanged)

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: MyForm(),
  ));
}

class MyForm extends StatefulWidget {
  @override
  _MyFormState createState() => _MyFormState();
}

class _MyFormState extends State<MyForm> {

  String? gender = "Male";
  bool cricket = false;
  bool football = false;
  bool switchValue = false;
  String dropdownValue = "India";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Form Example")),
      body: Padding(
        padding: EdgeInsets.all(20),
        child: Column(
          children: [
            TextField(
              decoration: InputDecoration(labelText: "Name"),
            ),

            Text("Gender:"),
            Row(
              children: [
                Radio(
                  value: "Male",
                  groupValue: gender,
                  onChanged: (value) {
                    setState(() {
                      gender = value.toString();
                    });
                  },
                ),
                Text("Male"),

                Radio(
                  value: "Female",
                  groupValue: gender,
                  onChanged: (value) {
                    setState(() {
                      gender = value.toString();
                    });
                  },
                ),
                Text("Female"),
              ],
            ),

            CheckboxListTile(
              title: Text("Cricket"),
              value: cricket,
              onChanged: (value) {
                setState(() => cricket = value!);
              },
            ),

            SwitchListTile(
              title: Text("Switch Option"),
              value: switchValue,
              onChanged: (value) {
                setState(() => switchValue = value);
              },
            ),

            DropdownButton(
              value: dropdownValue,
              items: ["India", "USA", "UK", "Japan"].map((String value) {
                return DropdownMenuItem(value: value, child: Text(value));
              }).toList(),
              onChanged: (newValue) {
                setState(() => dropdownValue = newValue.toString());
              },
            ),

            ElevatedButton(
              onPressed: () {},
              child: Text("Submit"),
            )
          ],
        ),
      ),
    );
  }
}

UI Description

AppBar: "Form Example"

Name: [ TextField ]

Gender:
   ( ) Male   ( ) Female

[ ] Cricket  (Checkbox)
Switch Option: ON/OFF (Switch)

Dropdown: [ India ▼ ]

[ Submit ]

Required Components

  • TextField
  • Radio + Row
  • CheckboxListTile
  • SwitchListTile
  • DropdownButton
  • ElevatedButton
  • Column + Padding

Notes

  • This assignment shows full form creation
  • setState updates UI instantly

--------------------------------------------------------------

✅ ASSIGNMENT 17 — Flutter Navigation (Two Screens)

(Source: Assignment 27)

Aim

Navigate from Screen 1 → Screen 2 using Navigator.push.


Steps

  1. Create Flutter project
  2. Add two screens in main.dart or separate files
  3. Replace code
  4. Run → Tap button to navigate

Dart Code (unchanged)

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: FirstScreen(),
  ));
}

class FirstScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("First Screen")),
      body: Center(
        child: ElevatedButton(
          child: Text("Go to Second Screen"),
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => SecondScreen()),
            );
          },
        ),
      ),
    );
  }
}

class SecondScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Second Screen")),
      body: Center(
        child: Text("Welcome to Second Screen"),
      ),
    );
  }
}

UI Description

Screen 1

AppBar: "First Screen"
Centered Button: "Go to Second Screen"

Screen 2

AppBar: "Second Screen"
Centered Text: "Welcome to Second Screen"

Required Components

  • ElevatedButton
  • Navigator.push
  • Two Scaffold screens
  • AppBars

Notes

  • Navigator.pop(context) can return to first screen
  • Most basic and commonly asked Flutter navigation program

✅ ASSIGNMENT 18 — CRUD Operations Using SQFlite in Flutter

(Source: Assignment 19 docx)


Aim

Perform Insert, View, Update, Delete operations in a Flutter app using SQFlite (local SQLite database).


Steps

  1. Create a Flutter project

  2. Add dependencies in pubspec.yaml:

    sqflite: ^2.0.0+4
    path: ^1.8.0
    
  3. Create a file db_helper.dart for database functions

  4. Paste the given code into:

    • main.dart
    • db_helper.dart
  5. Run the app on emulator/device

  6. Test Insert → View → Update → Delete


Dart Code (unchanged — db_helper.dart)

import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class DBHelper {

  static Database? db;

  static Future<Database> initDB() async {
    if (db != null) return db!;

    String path = join(await getDatabasesPath(), "userdata.db");

    db = await openDatabase(
      path,
      version: 1,
      onCreate: (database, version) async {
        await database.execute(
            "CREATE TABLE users(name TEXT PRIMARY KEY, contact TEXT)");
      },
    );

    return db!;
  }

  static Future<int> insert(String name, String contact) async {
    final dbClient = await initDB();
    return await dbClient.insert("users", {"name": name, "contact": contact});
  }

  static Future<List<Map<String, dynamic>>> getAll() async {
    final dbClient = await initDB();
    return await dbClient.query("users");
  }

  static Future<int> update(String name, String contact) async {
    final dbClient = await initDB();
    return await dbClient.update(
      "users",
      {"contact": contact},
      where: "name = ?",
      whereArgs: [name],
    );
  }

  static Future<int> delete(String name) async {
    final dbClient = await initDB();
    return await dbClient.delete("users", where: "name = ?", whereArgs: [name]);
  }
}

Dart Code (unchanged — main.dart)

import 'package:flutter/material.dart';
import 'db_helper.dart';

void main() {
  runApp(MaterialApp(home: MyDBApp()));
}

class MyDBApp extends StatefulWidget {
  @override
  _MyDBAppState createState() => _MyDBAppState();
}

class _MyDBAppState extends State<MyDBApp> {

  TextEditingController name = TextEditingController();
  TextEditingController contact = TextEditingController();
  String result = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("SQFlite CRUD")),
      body: Padding(
        padding: EdgeInsets.all(20),
        child: Column(
          children: [
            TextField(controller: name, decoration: InputDecoration(labelText: "Name")),
            TextField(controller: contact, decoration: InputDecoration(labelText: "Contact")),
            SizedBox(height: 20),

            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton(onPressed: insertData, child: Text("Insert")),
                ElevatedButton(onPressed: viewData, child: Text("View")),
              ],
            ),

            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton(onPressed: updateData, child: Text("Update")),
                ElevatedButton(onPressed: deleteData, child: Text("Delete")),
              ],
            ),

            SizedBox(height: 20),
            Text(result),
          ],
        ),
      ),
    );
  }

  void insertData() async {
    await DBHelper.insert(name.text, contact.text);
    setState(() => result = "Inserted!");
  }

  void viewData() async {
    var data = await DBHelper.getAll();
    setState(() => result = data.toString());
  }

  void updateData() async {
    await DBHelper.update(name.text, contact.text);
    setState(() => result = "Updated!");
  }

  void deleteData() async {
    await DBHelper.delete(name.text);
    setState(() => result = "Deleted!");
  }
}

UI Description

SQFlite CRUD App

Name: [ TextField ]
Contact: [ TextField ]

[ Insert ]    [ View ]
[ Update ]    [ Delete ]

Output:
<result text>

Required Components

  • TextField × 2
  • ElevatedButton × 4
  • Text widget (result display)
  • Padding + Column
  • External file: db_helper.dart

Notes

  • SQFlite stores data locally (offline)
  • If DB schema changes → uninstall app & run again
  • Always import path & sqflite correctly

--------------------------------------------------------------

✅ ASSIGNMENT 19 — REST API Integration in Flutter

(Source: Assignment 20 docx)


Aim

Fetch JSON data from a REST API using Flutter’s http package.


Steps

  1. Create Flutter project

  2. Add dependency in pubspec.yaml:

    http: ^0.13.5
    
  3. Replace main.dart with provided code

  4. Run the app → Click button to fetch API data

  5. Display result in Text widget


Dart Code (unchanged — main.dart)

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

void main() {
  runApp(MaterialApp(home: ApiScreen()));
}

class ApiScreen extends StatefulWidget {
  @override
  _ApiScreenState createState() => _ApiScreenState();
}

class _ApiScreenState extends State<ApiScreen> {

  String result = "";

  fetchData() async {
    final response = await http.get(
        Uri.parse("https://jsonplaceholder.typicode.com/posts/1"));

    if (response.statusCode == 200) {
      var data = jsonDecode(response.body);
      setState(() {
        result = data.toString();
      });
    } else {
      setState(() => result = "Error loading data");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Flutter REST API")),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: fetchData,
              child: Text("Load Data"),
            ),
            SizedBox(height: 20),
            Text(result),
          ],
        ),
      ),
    );
  }
}

UI Description

AppBar: "Flutter REST API"

[ Load Data ]

<API Response appears here>

The response is shown as a single Text widget under the button.


Required Components

  • ElevatedButton
  • Text widget (multiline)
  • Column + Center widgets

Notes

  • Most common Flutter API exam question
  • Uses GET method
  • Requires internet
  • Good for viva explanation: async → await → jsonDecode

  • Contact us
  • Jobs
  • Privacy
  • Manage cookies
  • Terms of use
  • Trademarks
© 2025 Microsoft