Skip to content
| Marketplace
Sign in
Visual Studio Code>Other>alanturingNew to Visual Studio Code? Get it now.
alanturing

alanturing

alanturing

| (0) | Free
17 - 23
Installation
Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter.
Copied to clipboard
More Info

Practical 17 — Create a student record system with the following fields: Roll number, Name, Age, Email, and Contact number. Use the Volley library to retrieve the records from the server (Use Json Array request)

Gradle dependency (add to app/build.gradle)

dependencies {
    implementation 'com.android.volley:volley:1.2.1'
    implementation 'androidx.appcompat:appcompat:1.7.1'
    implementation 'com.google.android.material:material:1.13.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.2.1'
    // other dependencies...
}

AndroidManifest.xml (ensure INTERNET permission)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.volley">

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

    <application
        android:allowBackup="true"
        android:label="@string/app_name"
        android:theme="@style/Theme.Volley">
        <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

package com.example.volley;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

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

public class MainActivity extends AppCompatActivity {

    Button btnString, btnJson;
    TextView txtdata;

    // example endpoints from your practical
    String links = "https://www.w3schools.com/xml/note.xml";
    String Jsonlinks = "https://mocki.io/v1/7d6d5cdb-04bf-4df6-8e0c-5e0a70069eb4";

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

         txtdata = findViewById(R.id.textView);
         btnString = findViewById(R.id.btnString);
         btnJson = findViewById(R.id.btnJson);

         RequestQueue queue = Volley.newRequestQueue(getApplicationContext());

         btnString.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 StringRequest stringRequest = new StringRequest(Request.Method.GET, links,
                         new Response.Listener<String>() {
                             @Override
                             public void onResponse(String response) {
                                 txtdata.setText(response);
                             }
                         }, new Response.ErrorListener() {
                     @Override
                     public void onErrorResponse(VolleyError error) {
                         error.printStackTrace();
                         txtdata.setText("Error: " + error.getMessage());
                     }
                 });
                 queue.add(stringRequest);
             }
         });

         btnJson.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET,
                         Jsonlinks, null,
                         new Response.Listener<JSONArray>() {
                             @Override
                             public void onResponse(JSONArray response) {
                                 StringBuilder buffer = new StringBuilder();
                                 for (int i = 0; i < response.length(); i++) {
                                     try {
                                         JSONObject obj = response.getJSONObject(i);
                                         buffer.append("Roll no.: ").append(obj.getInt("roll")).append("\n")
                                                 .append("Name: ").append(obj.getString("name")).append("\n")
                                                 .append("Email: ").append(obj.optString("email", "N/A")).append("\n\n");
                                     } catch (JSONException e) {
                                         e.printStackTrace();
                                     }
                                 }
                                 txtdata.setText(buffer.toString());
                             }
                         },
                         new Response.ErrorListener() {
                             @Override
                             public void onErrorResponse(VolleyError error) {
                                 error.printStackTrace();
                                 txtdata.setText("Error: " + error.getMessage());
                             }
                         }
                 );
                 queue.add(jsonArrayRequest);
             }
         });
    }
}

activity_main.xml

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

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/btnString"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Fetch XML String" />

        <Button
            android:id="@+id/btnJson"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Fetch JSON Array"
            android:layout_marginTop="12dp" />

        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Fetched data will appear here"
            android:padding="12dp"
            android:textSize="16sp"
            android:layout_marginTop="16dp"/>

    </LinearLayout>
</ScrollView>

Practical 18 - Create a student record system with the following fields: Roll number, Name, Age, Email, and Contact number. Use the OkHttp library to retrieve the records from the server.

app → manifests → AndroidManifest.xml

Add THIS line before < application >:

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

app/build.gradle.kts

Inside dependencies add:

implementation("com.squareup.okhttp3:okhttp:4.12.0")

res → layout → activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="20dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btnString"
        android:text="Fetch XML"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btnJson"
        android:text="Fetch JSON"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp" />

    <TextView
        android:id="@+id/textView"
        android:text=""
        android:textSize="16sp"
        android:padding="16dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

java/com.example.okhttp/MainActivity.java

package com.example.practical18;


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

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

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

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "OKHTTP_RAW";
    Button btnString, btnJson;
    TextView txtdata;

    // XML example (works)
    String links = "https://www.w3schools.com/xml/note.xml";

    // Try this stable JSON array endpoint for testing:
    // It returns a JSON array of users.
    // If this works, your app is fine and the problem is your mock URL.
    String Jsonlinks = "https://jsonplaceholder.typicode.com/users";

    OkHttpClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtdata = findViewById(R.id.textView);
        btnString = findViewById(R.id.btnString);
        btnJson = findViewById(R.id.btnJson);
        client = new OkHttpClient();

        // Fetch XML String Output
        btnString.setOnClickListener(v -> {
            Request req = new Request.Builder().url(links).build();
            client.newCall(req).enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    Log.e(TAG, "XML request failed", e);
                    runOnUiThread(() -> txtdata.setText("XML request failed: " + e.getMessage()));
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    String data = response.body() != null ? response.body().string() : "";
                    Log.d(TAG, "XML response code=" + response.code() + " body=" + data);
                    runOnUiThread(() -> txtdata.setText(data));
                }
            });
        });

        // Fetch JSON Student Records (robust handling)
        btnJson.setOnClickListener(v -> {
            Request jsonReq = new Request.Builder().url(Jsonlinks).build();
            client.newCall(jsonReq).enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    Log.e(TAG, "JSON request failed", e);
                    runOnUiThread(() -> txtdata.setText("JSON request failed: " + e.getMessage()));
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    String body = response.body() != null ? response.body().string() : "";
                    String contentType = response.header("Content-Type", "unknown");
                    Log.d(TAG, "code=" + response.code() + " contentType=" + contentType + " body=" + body);

                    // Show raw body first so you can see what's returned
                    runOnUiThread(() -> txtdata.setText(body));

                    if (!response.isSuccessful()) {
                        runOnUiThread(() -> txtdata.setText("Server error: " + response.code()));
                        return;
                    }

                    String trimmed = body.trim();
                    if (trimmed.isEmpty()) {
                        runOnUiThread(() -> txtdata.setText("Empty response"));
                        return;
                    }

                    // If the server returned HTML (starts with <), show helpful message
                    if (trimmed.startsWith("<")) {
                        runOnUiThread(() -> txtdata.setText("Expected JSON but got HTML/markup. Open the URL in browser to inspect.\n\nFirst 200 chars:\n" + trimmed.substring(0, Math.min(200, trimmed.length()))));
                        return;
                    }

                    // Now try to parse JSON (array or object)
                    try {
                        StringBuilder buffer = new StringBuilder();

                        if (trimmed.startsWith("[")) {
                            // JSON array
                            JSONArray jsonArray = new JSONArray(trimmed);
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject studentObj = jsonArray.getJSONObject(i);
                                // Use optX to avoid exceptions if keys missing
                                buffer.append("Roll/ID: ").append(studentObj.optInt("id")).append("\n")
                                        .append("Name: ").append(studentObj.optString("name")).append("\n")
                                        .append("Email: ").append(studentObj.optString("email")).append("\n\n");
                            }
                        } else if (trimmed.startsWith("{")) {
                            // JSON object: maybe { "students": [...] } or a single object
                            JSONObject jsonObject = new JSONObject(trimmed);
                            if (jsonObject.has("students")) {
                                JSONArray arr = jsonObject.getJSONArray("students");
                                for (int i = 0; i < arr.length(); i++) {
                                    JSONObject studentObj = arr.getJSONObject(i);
                                    buffer.append("Roll no.: ").append(studentObj.optInt("roll")).append("\n")
                                            .append("Name: ").append(studentObj.optString("name")).append("\n")
                                            .append("Email: ").append(studentObj.optString("email")).append("\n\n");
                                }
                            } else if (jsonObject.has("data") && jsonObject.get("data") instanceof JSONArray) {
                                JSONArray arr = jsonObject.getJSONArray("data");
                                for (int i = 0; i < arr.length(); i++) {
                                    JSONObject studentObj = arr.getJSONObject(i);
                                    buffer.append("Roll no.: ").append(studentObj.optInt("roll")).append("\n")
                                            .append("Name: ").append(studentObj.optString("name")).append("\n")
                                            .append("Email: ").append(studentObj.optString("email")).append("\n\n");
                                }
                            } else {
                                // treat jsonObject as a single student-like object
                                buffer.append("Roll no.: ").append(jsonObject.optInt("roll")).append("\n")
                                        .append("Name: ").append(jsonObject.optString("name")).append("\n")
                                        .append("Email: ").append(jsonObject.optString("email")).append("\n\n");
                            }
                        } else {
                            runOnUiThread(() -> txtdata.setText("Response is not JSON/HTML. First chars: " + trimmed.substring(0, Math.min(100, trimmed.length()))));
                            return;
                        }

                        final String out = buffer.toString();
                        runOnUiThread(() -> {
                            if (out.isEmpty()) {
                                txtdata.setText("Parsed JSON but no recognizable fields found. Raw:\n" + trimmed);
                            } else {
                                txtdata.setText(out);
                            }
                        });

                    } catch (JSONException e) {
                        Log.e(TAG, "JSON parse error", e);
                        runOnUiThread(() -> txtdata.setText("JSON parse error: " + e.getMessage() + "\n\nRaw response:\n" + (trimmed.length() > 200 ? trimmed.substring(0, 200) : trimmed)));
                    }
                }
            });
        });
    }
}

Practical 19: Create a Json record system with the following fields: Id, User id, Title, Body. Use the Retrofit library to retrieve the records from the server.

Open app/src/main/AndroidManifest.xml and add above :

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

Open app/build.gradle (module) and inside dependencies {} add:

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

activity_main.xml

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

    <Button
        android:id="@+id/btnfetch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Fetch Posts" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="12dp">

        <TextView
            android:id="@+id/txtview"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="14sp"
            android:padding="8dp" />
    </ScrollView>

</LinearLayout>

model.java

package com.example.myapplication;

public class model {
    private int userId;
    private int id;
    private String title;
    private String body;

    public int getUserId() { return userId; }
    public void setUserId(int userId) { this.userId = userId; }

    public int getId() { return id; }
    public void setId(int id) { this.id = id; }

    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }

    public String getBody() { return body; }
    public void setBody(String body) { this.body = body; }
}

myapi.java

package com.example.myapplication;

import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;

public interface myapi {
    @GET("posts")
    Call<List<model>> getmodels();
}

MainActivity.java

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    TextView txtview;
    Button btnfetch;
    String baseUrl = "https://jsonplaceholder.typicode.com/";

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

        txtview = findViewById(R.id.txtview);
        btnfetch = findViewById(R.id.btnfetch);

        btnfetch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                txtview.setText(""); // clear previous output

                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl(baseUrl)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();

                myapi api = retrofit.create(myapi.class);
                Call<List<model>> call = api.getmodels();
                call.enqueue(new Callback<List<model>>() {
                    @Override
                    public void onResponse(Call<List<model>> call, Response<List<model>> response) {
                        if (!response.isSuccessful()) {
                            txtview.setText("Server returned: " + response.code());
                            return;
                        }

                        List<model> data = response.body();
                        if (data == null) {
                            txtview.setText("Response body is null");
                            return;
                        }

                        StringBuilder sb = new StringBuilder();
                        for (model m : data) {
                            sb.append("id: ").append(m.getId()).append("\n");
                            sb.append("user_id: ").append(m.getUserId()).append("\n");
                            sb.append("Title: ").append(m.getTitle()).append("\n");
                            sb.append("Body: ").append(m.getBody()).append("\n\n");
                        }
                        txtview.setText(sb.toString());
                    }

                    @Override
                    public void onFailure(Call<List<model>> call, Throwable t) {
                        txtview.setText("Request failed: " + t.getMessage());
                        Toast.makeText(MainActivity.this, "Network error", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }
}

Practical 20: Create Flutter application to demonstrate BMI calculator

New Project → Flutter → Project name bmi_app.

Project structure

bmi_app/
 ├─ lib/
 │   ├─ main.dart
 │   └─ BMICalculator.dart   <-- your widget 
 ├─ pubspec.yaml
 └─ android/  ios/  (platform folders)

BMICalculator.dart

// lib/BMICalculator.dart
import 'package:flutter/material.dart';

class BMICalculator extends StatefulWidget {
  const BMICalculator({super.key});

  @override
  State<BMICalculator> createState() => _BMICalculatorState();
}

class _BMICalculatorState extends State<BMICalculator> {
  final TextEditingController heightController = TextEditingController();
  final TextEditingController weightController = TextEditingController();
  double bmiResult = 0.0;

  void calculateBMI() {
    setState(() {
      try {
        final double height = double.parse(heightController.text);
        final double weight = double.parse(weightController.text);

        if (height <= 0 || weight <= 0) {
          throw Exception('Height and weight must be positive numbers');
        }

        bmiResult = weight / (height * height);
      } catch (e) {
        bmiResult = 0.0;
      }
    });
  }

  String _getCategory(double bmi) {
    if (bmi < 18.5) return 'Underweight 😲';
    if (bmi <= 24.9) return 'Normal Weight 😉';
    if (bmi <= 29.9) return 'Overweight 🤒';
    return 'Obese 💀';
  }

  void clearResult() {
    setState(() {
      heightController.clear();
      weightController.clear();
      bmiResult = 0.0;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.green,
        title: const Text(
          'BMI Calculator',
          style: TextStyle(color: Colors.white),
        ),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextField(
                controller: heightController,
                keyboardType: TextInputType.number,
                decoration: const InputDecoration(
                  labelText: 'Height (m)',
                  border: OutlineInputBorder(),
                ),
              ),
              const SizedBox(height: 20),
              TextField(
                controller: weightController,
                keyboardType: TextInputType.number,
                decoration: const InputDecoration(
                  labelText: 'Weight (kg)',
                  border: OutlineInputBorder(),
                ),
              ),
              const SizedBox(height: 30),
              ElevatedButton(
                onPressed: calculateBMI,
                child: const Text('Calculate BMI'),
              ),
              const SizedBox(height: 12),
              ElevatedButton(
                onPressed: clearResult,
                child: const Text('Clear'),
              ),
              const SizedBox(height: 30),
              bmiResult > 0
                  ? Container(
                      width: double.infinity,
                      padding: const EdgeInsets.all(20),
                      decoration: BoxDecoration(
                        color: Colors.greenAccent,
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: Column(
                        children: [
                          Text(
                            'BMI: ${bmiResult.toStringAsFixed(1)}',
                            style: const TextStyle(
                              fontSize: 24,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          Text(
                            'You are ${_getCategory(bmiResult)}',
                            style: const TextStyle(fontSize: 20),
                          ),
                        ],
                      ),
                    )
                  : const SizedBox.shrink(),
            ],
          ),
        ),
      ),
    );
  }
}

main.dart

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

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'BMI App',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: const BMICalculator(),
    );
  }
}

Start an emulator (AVD) or connect device.

In terminal:

flutter run

Practical 21 — Registration Form (Flutter)

Project Structure

registration_form/
│
├── lib/
│   ├── main.dart
│   ├── RegistrationForm.dart
│   └── DetailsPage.dart
│
├── pubspec.yaml
│
├── android/        (Auto generated)
├── ios/            (Auto generated)
├── test/
└── build/

lib/main.dart

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

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: const RegistrationForm(),
    );
  }
}

lib/RegistrationForm.dart

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

class RegistrationForm extends StatefulWidget {
  const RegistrationForm({super.key});

  @override
  State<RegistrationForm> createState() => _RegistrationFormState();
}

class _RegistrationFormState extends State<RegistrationForm> {
  final TextEditingController nameController = TextEditingController();
  String? gender;
  bool langEnglish = false;
  bool langHindi = false;
  bool langMarathi = false;

  final List<String> cities = ["Mumbai", "Delhi", "Pune"];
  String? selectedCity;

  bool darkBackground = false;

  void onSubmit() {
    List<String> langList = [];
    if (langEnglish) langList.add("English");
    if (langHindi) langList.add("Hindi");
    if (langMarathi) langList.add("Marathi");

    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => Details(
          name: nameController.text,
          gender: gender ?? "Not selected",
          languages: langList,
          selectedCity: selectedCity,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Registration Form"), backgroundColor: Colors.green),
      body: Container(
        color: darkBackground ? Colors.green[50] : Colors.white,
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                TextField(
                  controller: nameController,
                  decoration: const InputDecoration(
                    labelText: "Enter name:",
                    border: OutlineInputBorder(),
                  ),
                ),
                const SizedBox(height: 16),
                const Text("Select your gender:"),
                RadioListTile(
                  title: const Text("Male"),
                  value: "Male",
                  groupValue: gender,
                  onChanged: (value) => setState(() => gender = value),
                ),
                RadioListTile(
                  title: const Text("Female"),
                  value: "Female",
                  groupValue: gender,
                  onChanged: (value) => setState(() => gender = value),
                ),
                const SizedBox(height: 16),
                const Text("Select the languages:"),
                CheckboxListTile(
                  title: const Text("English"),
                  value: langEnglish,
                  onChanged: (val) => setState(() => langEnglish = val ?? false),
                ),
                CheckboxListTile(
                  title: const Text("Hindi"),
                  value: langHindi,
                  onChanged: (val) => setState(() => langHindi = val ?? false),
                ),
                CheckboxListTile(
                  title: const Text("Marathi"),
                  value: langMarathi,
                  onChanged: (val) => setState(() => langMarathi = val ?? false),
                ),
                const SizedBox(height: 16),
                DropdownButton(
                  isExpanded: true,
                  value: selectedCity,
                  hint: const Text("Select city"),
                  items: cities.map((e) => DropdownMenuItem(value: e, child: Text(e))).toList(),
                  onChanged: (value) => setState(() => selectedCity = value),
                ),
                SwitchListTile(
                  title: const Text("Dark Background"),
                  value: darkBackground,
                  onChanged: (val) => setState(() => darkBackground = val),
                ),
                const SizedBox(height: 24),
                ElevatedButton(onPressed: onSubmit, child: const Text("Submit")),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

lib/DetailsPage.dart

import 'package:flutter/material.dart';

class Details extends StatelessWidget {
  final String name;
  final String gender;
  final List<String> languages;
  final String? selectedCity;

  const Details({
    super.key,
    required this.name,
    required this.gender,
    required this.languages,
    required this.selectedCity,
  });

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Details"), backgroundColor: Colors.blue),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text("Name: $name"),
            Text("Gender: $gender"),
            Text("Languages: ${languages.isEmpty ? "None" : languages.join(", ")}"),
            Text("City: ${selectedCity ?? "Not selected"}"),
          ],
        ),
      ),
    );
  }
}

lib/DetailsPage.dart

import 'package:flutter/material.dart';

class Details extends StatelessWidget {
  final String name;
  final String gender;
  final List<String> languages;
  final String? selectedCity;

  const Details({
    super.key,
    required this.name,
    required this.gender,
    required this.languages,
    required this.selectedCity,
  });

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Details"), backgroundColor: Colors.blue),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text("Name: $name"),
            Text("Gender: $gender"),
            Text("Languages: ${languages.isEmpty ? "None" : languages.join(", ")}"),
            Text("City: ${selectedCity ?? "Not selected"}"),
          ],
        ),
      ),
    );
  }
}

PRACTICAL 22 — SQLite CRUD (Flutter + Sqflite)

PROJECT STRUCTURE

sqflite_crud/
│
├── lib/
│   ├── main.dart
│   ├── Homepage.dart
│   └── database_helper.dart
│
├── pubspec.yaml
│
├── android/
├── ios/
└── build/

pubspec.yaml (dependencies section)

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.8
  sqflite: ^2.2.0
  path_provider: ^2.0.15
  path: ^1.8.3

lib/main.dart

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

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: const MyHomePage(),
    );
  }
}

lib/database_helper.dart

import 'dart:async';
import 'dart:io';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';

class DatabaseHelper {
  static const _databaseName = "MyDatabase.db";
  static const _databaseVersion = 1;

  static const table = 'my_table';
  static const columnId = '_id';
  static const columnName = 'name';

  DatabaseHelper._privateConstructor();
  static final DatabaseHelper instance = DatabaseHelper._privateConstructor();

  static Database? _database;

  Future<Database> get database async {
    _database ??= await _initDatabase();
    return _database!;
  }

  Future<Database> _initDatabase() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, _databaseName);
    return await openDatabase(path,
        version: _databaseVersion, onCreate: _onCreate);
  }

  Future _onCreate(Database db, int version) async {
    await db.execute('''
      CREATE TABLE $table (
        $columnId INTEGER PRIMARY KEY,
        $columnName TEXT NOT NULL
      )
    ''');
  }

  Future<int> insert(Map<String, dynamic> row) async {
    Database db = await database;
    return await db.insert(table, row);
  }

  Future<List<Map<String, dynamic>>> queryAllRows() async {
    Database db = await database;
    return await db.query(table);
  }

  Future<int> update(Map<String, dynamic> row) async {
    Database db = await database;
    int id = row[columnId];
    return await db.update(table, row, where: '$columnId = ?', whereArgs: [id]);
  }

  Future<int> delete(int id) async {
    Database db = await database;
    return await db.delete(table, where: '$columnId = ?', whereArgs: [id]);
  }
}

lib/Homepage.dart

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

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _idController = TextEditingController();
  final _nameController = TextEditingController();

  String _message = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('SQLite Demo')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(controller: _idController, decoration: const InputDecoration(labelText: "ID")),
            TextField(controller: _nameController, decoration: const InputDecoration(labelText: "Name")),
            const SizedBox(height: 20),

            ElevatedButton(
              onPressed: () async {
                final id = int.tryParse(_idController.text.trim());
                final name = _nameController.text.trim();

                if (id == null || name.isEmpty) {
                  setState(() => _message = "Enter valid ID & Name");
                  return;
                }

                await DatabaseHelper.instance.insert({
                  DatabaseHelper.columnId: id,
                  DatabaseHelper.columnName: name,
                });

                _idController.clear();
                _nameController.clear();

                setState(() => _message = "Inserted Successfully");
              },
              child: const Text("Insert"),
            ),

            ElevatedButton(
              onPressed: () async {
                final rows = await DatabaseHelper.instance.queryAllRows();
                setState(() => _message = rows.toString());
              },
              child: const Text("Show"),
            ),

            ElevatedButton(
              onPressed: () async {
                final id = int.tryParse(_idController.text.trim());
                final name = _nameController.text.trim();
                if (id == null || name.isEmpty) {
                  setState(() => _message = "Enter valid ID & Name");
                  return;
                }
                await DatabaseHelper.instance.update({
                  DatabaseHelper.columnId: id,
                  DatabaseHelper.columnName: name,
                });
                setState(() => _message = "Updated Successfully");
              },
              child: const Text("Update"),
            ),

            ElevatedButton(
              onPressed: () async {
                final id = int.tryParse(_idController.text.trim());
                if (id == null) {
                  setState(() => _message = "Enter valid ID");
                  return;
                }
                await DatabaseHelper.instance.delete(id);
                setState(() => _message = "Deleted Successfully");
              },
              child: const Text("Delete"),
            ),

            const SizedBox(height: 20),
            Text(_message, style: const TextStyle(fontSize: 16)),
          ],
        ),
      ),
    );
  }
}

PRACTICAL 23 — REST API (Flutter + HTTP GET)

PROJECT STRUCTURE

rest_api_app/
│
├── lib/
│   ├── main.dart
│   ├── HomePage.dart
│   ├── User.dart
│   └── Remote_service.dart
│
├── pubspec.yaml
├── android/
├── ios/
└── build/

pubspec.yaml (dependencies)

dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.6

lib/main.dart

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

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: MyHomePage(),
    );
  }
}

lib/User.dart

import 'dart:convert';

List<User> userFromJson(String str) =>
    List<User>.from(json.decode(str).map((x) => User.fromJson(x)));

class User {
  int rno;
  String name;

  User({required this.rno, required this.name});

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      rno: json["rno"],
      name: json["name"],
    );
  }
}

lib/User.dart

import 'dart:convert';

List<User> userFromJson(String str) =>
    List<User>.from(json.decode(str).map((x) => User.fromJson(x)));

class User {
  int rno;
  String name;

  User({required this.rno, required this.name});

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      rno: json["rno"],
      name: json["name"],
    );
  }
}

lib/Remote_service.dart

import 'package:http/http.dart' as http;
import 'User.dart';

class RemoteService {
  Future<List<User>> getUsers() async {
    final uri = Uri.parse("https://mocki.io/v1/5e56d735-4e27-4afa-b82a-a4c384c42523");

    final response = await http.get(uri);

    if (response.statusCode == 200) {
      return userFromJson(response.body);
    } else {
      return []; // handle safely
    }
  }
}

lib/HomePage.dart

import 'package:flutter/material.dart';
import 'User.dart';
import 'Remote_service.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<User>? users;
  bool isLoaded = false;

  @override
  void initState() {
    super.initState();
    fetchData();
  }

  fetchData() async {
    users = await RemoteService().getUsers();
    setState(() {
      isLoaded = true;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("REST API Demo")),
      body: isLoaded
          ? (users == null || users!.isEmpty
              ? const Center(child: Text("No data found"))
              : ListView.builder(
                  itemCount: users!.length,
                  itemBuilder: (context, index) {
                    return ListTile(
                      title: Text(users![index].name),
                      subtitle: Text("Rno: ${users![index].rno}"),
                    );
                  }))
          : const Center(child: CircularProgressIndicator()),
    );
  }
}
  • Contact us
  • Jobs
  • Privacy
  • Manage cookies
  • Terms of use
  • Trademarks
© 2026 Microsoft