Skip to content
| Marketplace
Sign in
Visual Studio Code>Other>Codify NotionNew to Visual Studio Code? Get it now.
Codify Notion

Codify Notion

Code Master

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

Codify Notion Extension README

Codify Notion

Instant Command Execution — Perform common development actions without manually navigating menus.

Smart Snippets & Templates — Auto-insert frequently used code patterns to save typing time.

Workflow Automation — Reduce repetitive tasks such as formatting, file creation, and cleanup actions.

Command Palette Integration — Access all features via Ctrl + Shift + P without leaving the keyboard.

Lightweight & Fast — Zero unnecessary dependencies, optimized for performance.

Beginner-Friendly — Clean and intuitive usage—no complex setup required.

Customizable Behavior — Modify shortcuts and command behavior through settings.

Requirements

Key Highlights

  • Faster workflow with automated commands.
  • Helpful code snippets.
  • Easy to access via Command Palette.

🔧 How to Use

Open Command Palette (Ctrl + Shift + P) and search Codo Motor to run available actions.

Version

v0.0.2 — Updated README and minor improvements.

License

MIT License

Features

Bulk Operations

Rename, format, and apply cleanup across multiple files at once—especially useful for large refactors.

Git Utility Commands

Perform essential git actions (commit, stash, restore, branch, pull, push) directly inside VS Code commands.

Error-Resistant Workflow

Avoid common mistakes by using built-in formatting, comment inserts, TODO markers, and structure validation.

Zero Bloat Approach

No background services, analytics, or heavy dependencies—keeps VS Code fast instead of bloated like some extensions.

Cross-Language Compatibility

Designed to support JavaScript, TypeScript, Python, Java, C#, and more (with Extensable Code)

** PRA 1 — SIMPLE CALCULATOR**


UI — activity_main.xml

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

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

        <TextView
            android:id="@+id/result_tv"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:text="0"
            android:textSize="26sp"
            android:gravity="end|center_vertical"
            android:padding="8dp"/>

        <TextView
            android:id="@+id/expression_tv"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:textSize="18sp"
            android:gravity="end|center_vertical"
            android:padding="8dp"
            android:layout_marginBottom="12dp"/>

        <GridLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:columnCount="4"
            android:rowCount="6"
            android:useDefaultMargins="true">

            <Button android:id="@+id/btn_ac" android:text="AC"/>
            <Button android:id="@+id/btn_openbracket" android:text="("/>
            <Button android:id="@+id/btn_closebracket" android:text=")"/>
            <Button android:id="@+id/btn_C" android:text="C"/>

            <Button android:id="@+id/btn_7" android:text="7"/>
            <Button android:id="@+id/btn_8" android:text="8"/>
            <Button android:id="@+id/btn_9" android:text="9"/>
            <Button android:id="@+id/btn_divide" android:text="/"/>

            <Button android:id="@+id/btn_4" android:text="4"/>
            <Button android:id="@+id/btn_5" android:text="5"/>
            <Button android:id="@+id/btn_6" android:text="6"/>
            <Button android:id="@+id/btn_multiply" android:text="*"/>

            <Button android:id="@+id/btn_1" android:text="1"/>
            <Button android:id="@+id/btn_2" android:text="2"/>
            <Button android:id="@+id/btn_3" android:text="3"/>
            <Button android:id="@+id/btn_minus" android:text="-"/>

            <Button android:id="@+id/btn_0" android:text="0"/>
            <Button android:id="@+id/btn_decimal" android:text="."/>
            <Button android:id="@+id/btn_equals" android:text="="/>
            <Button android:id="@+id/btn_add" android:text="+"/>

        </GridLayout>
    </LinearLayout>
</ScrollView>


JAVA — MainActivity.java

(Your same logic, cleaned & made human-like)

package com.example.practical1mc;

import androidx.appcompat.app.AppCompatActivity;

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

import com.google.android.material.button.MaterialButton;

import java.util.Stack;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    TextView expression_tv, result_tv;

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

        expression_tv = findViewById(R.id.expression_tv);
        result_tv = findViewById(R.id.result_tv);

        int[] ids = {
                R.id.btn_0, R.id.btn_1, R.id.btn_2, R.id.btn_3, R.id.btn_4,
                R.id.btn_5, R.id.btn_6, R.id.btn_7, R.id.btn_8, R.id.btn_9,
                R.id.btn_add, R.id.btn_minus, R.id.btn_multiply, R.id.btn_divide,
                R.id.btn_decimal, R.id.btn_equals,
                R.id.btn_ac, R.id.btn_C, R.id.btn_openbracket, R.id.btn_closebracket
        };

        for (int id : ids) findViewById(id).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        MaterialButton b = (MaterialButton) view;
        String text = b.getText().toString();
        String exp = expression_tv.getText().toString();

        switch (text) {
            case "AC":
                expression_tv.setText("");
                result_tv.setText("0");
                return;

            case "C":
                if (!exp.isEmpty()) exp = exp.substring(0, exp.length() - 1);
                break;

            case "=":
                result_tv.setText(evaluateExpression(exp));
                return;

            default:
                exp += text;
        }

        expression_tv.setText(exp);

        String output = evaluateExpression(exp);
        if (!output.equals("Error")) result_tv.setText(output);
    }

    private String evaluateExpression(String exp) {
        try {
            return String.valueOf(evaluate(exp));
        } catch (Exception e) {
            return "Error";
        }
    }

    private double evaluate(String expression) {
        Stack<Double> numbers = new Stack<>();
        Stack<Character> ops = new Stack<>();

        for (int i = 0; i < expression.length(); i++) {

            char c = expression.charAt(i);

            if (Character.isDigit(c) || c == '.') {
                StringBuilder num = new StringBuilder();
                while (i < expression.length() &&
                        (Character.isDigit(expression.charAt(i)) || expression.charAt(i) == '.')) {
                    num.append(expression.charAt(i++));
                }
                i--;
                numbers.push(Double.parseDouble(num.toString()));
            }

            else if (c == '(')
                ops.push(c);

            else if (c == ')') {
                while (ops.peek() != '(')
                    numbers.push(apply(ops.pop(), numbers.pop(), numbers.pop()));
                ops.pop();
            }

            else if (isOperator(c)) {
                while (!ops.isEmpty() && precedence(ops.peek()) >= precedence(c)) {
                    numbers.push(apply(ops.pop(), numbers.pop(), numbers.pop()));
                }
                ops.push(c);
            }
        }

        while (!ops.isEmpty()) {
            numbers.push(apply(ops.pop(), numbers.pop(), numbers.pop()));
        }

        return numbers.pop();
    }

    private boolean isOperator(char c) {
        return c == '+' || c == '-' || c == '*' || c == '/';
    }

    private int precedence(char op) {
        if (op == '+' || op == '-') return 1;
        if (op == '*' || op == '/') return 2;
        return 0;
    }

    private double apply(char op, double b, double a) {
        switch (op) {
            case '+': return a + b;
            case '-': return a - b;
            case '*': return a * b;
            case '/': 
                if (b == 0) return 0;
                return a / b;
        }
        return 0;
    }
}


PRA 2 — Currency Converter


UI — activity_main.xml

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

    <Spinner
        android:id="@+id/fromCurrency"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Spinner
        android:id="@+id/toCurrency"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp" />

    <EditText
        android:id="@+id/amountInput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Amount"
        android:inputType="numberDecimal"
        android:layout_marginTop="12dp" />

    <Button
        android:id="@+id/convertBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Convert"
        android:layout_marginTop="12dp" />

    <TextView
        android:id="@+id/resultView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Result will appear here"
        android:textSize="18sp"
        android:layout_marginTop="16dp" />

</LinearLayout>

JAVA — MainActivity.java

package com.example.currencyconverter;

import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity {

    Spinner fromCurrency, toCurrency;
    EditText amountInput;
    TextView resultView;
    Button convertBtn;

    String[] list = {"INR", "USD", "EUR", "JPY"};

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

        fromCurrency = findViewById(R.id.fromCurrency);
        toCurrency = findViewById(R.id.toCurrency);
        amountInput = findViewById(R.id.amountInput);
        resultView = findViewById(R.id.resultView);
        convertBtn = findViewById(R.id.convertBtn);

        ArrayAdapter<String> ad = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item, list);
        ad.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        fromCurrency.setAdapter(ad);
        toCurrency.setAdapter(ad);

        convertBtn.setOnClickListener(v -> convert());
    }

    private void convert() {
        String input = amountInput.getText().toString();
        if (input.isEmpty()) {
            resultView.setText("Enter amount first");
            return;
        }

        double amt = Double.parseDouble(input);

        double result = 0;
        String from = fromCurrency.getSelectedItem().toString();
        String to = toCurrency.getSelectedItem().toString();

        // Simple hardcoded conversions
        if (from.equals(to)) result = amt;
        else if (from.equals("INR") && to.equals("USD")) result = amt * 0.012;
        else if (from.equals("USD") && to.equals("INR")) result = amt * 83;
        else if (from.equals("EUR") && to.equals("INR")) result = amt * 90;
        else if (from.equals("INR") && to.equals("EUR")) result = amt * 0.011;
        else result = amt; // fallback

        resultView.setText("Converted: " + result);
    }
}

Instructions

• internet not required • no permissions needed


PRAC 3 — Registration Form using Explicit Intent


UI — activity_main.xml

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

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

        <EditText
            android:id="@+id/name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Full Name" />

        <EditText
            android:id="@+id/dobs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Date of Birth" />

        <TextView
            android:text="Gender"
            android:layout_marginTop="10dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <RadioGroup
            android:id="@+id/gender"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <RadioButton
                android:id="@+id/radio_male"
                android:text="Male"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <RadioButton
                android:id="@+id/radio_female"
                android:text="Female"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </RadioGroup>

        <TextView
            android:text="Rate your skills"
            android:layout_marginTop="12dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <RatingBar
            android:id="@+id/rating"
            android:numStars="5"
            android:stepSize="1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:text="Languages Known"
            android:layout_marginTop="12dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <CheckBox
            android:id="@+id/check_english"
            android:text="English"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <CheckBox
            android:id="@+id/check_hindi"
            android:text="Hindi"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/submit"
            android:text="Submit"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp" />

    </LinearLayout>
</ScrollView>


UI — activity_display.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="18dp">

    <TextView
        android:id="@+id/showName"
        android:textSize="18sp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/showGender"
        android:layout_marginTop="10dp"
        android:textSize="18sp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/showDob"
        android:layout_marginTop="10dp"
        android:textSize="18sp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/showLang"
        android:layout_marginTop="10dp"
        android:textSize="18sp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/showRating"
        android:layout_marginTop="10dp"
        android:textSize="18sp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

JAVA — MainActivity.java

package com.example.registrationform;

import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity {

    EditText name, dobs;
    RadioGroup gender;
    RatingBar skills;
    CheckBox english, hindi;
    Button submit;

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

        name = findViewById(R.id.name);
        dobs = findViewById(R.id.dobs);
        gender = findViewById(R.id.gender);
        skills = findViewById(R.id.rating);
        english = findViewById(R.id.check_english);
        hindi = findViewById(R.id.check_hindi);
        submit = findViewById(R.id.submit);

        submit.setOnClickListener(v -> {

            String nm = name.getText().toString();
            String dob = dobs.getText().toString();

            int id = gender.getCheckedRadioButtonId();
            String g = ((RadioButton)findViewById(id)).getText().toString();

            float rate = skills.getRating();

            String langs = "";
            if (english.isChecked()) langs += "English ";
            if (hindi.isChecked()) langs += "Hindi ";

            Intent i = new Intent(MainActivity.this, DisplayActivity.class);
            i.putExtra("n", nm);
            i.putExtra("d", dob);
            i.putExtra("g", g);
            i.putExtra("l", langs);
            i.putExtra("r", rate);
            startActivity(i);
        });
    }
}

JAVA — DisplayActivity.java

package com.example.registrationform;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

public class DisplayActivity extends AppCompatActivity {

    TextView name, gender, dob, lang, rating;

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

        name = findViewById(R.id.showName);
        gender = findViewById(R.id.showGender);
        dob = findViewById(R.id.showDob);
        lang = findViewById(R.id.showLang);
        rating = findViewById(R.id.showRating);

        name.setText("Name: " + getIntent().getStringExtra("n"));
        gender.setText("Gender: " + getIntent().getStringExtra("g"));
        dob.setText("DOB: " + getIntent().getStringExtra("d"));
        lang.setText("Languages: " + getIntent().getStringExtra("l"));
        rating.setText("Rating: " + getIntent().getFloatExtra("r", 0));
    }
}



Dont forget to add this in AndroidManifest.xml
<activity android:name=".DisplayActivity" />

PRAC 4 — Implicit Intent (Open URL, SMS, Share Text, Dial) + Receiver App


Sender App — com.alone_x.implicitintent

UI — activity_main.xml

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

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

        <EditText
            android:id="@+id/urledittext"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter website URL" />

        <Button
            android:id="@+id/browsebutton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Open Website"
            android:layout_marginTop="8dp" />

        <EditText
            android:id="@+id/editTextPhone"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Phone for SMS"
            android:inputType="phone"
            android:layout_marginTop="14dp" />

        <EditText
            android:id="@+id/editSmsText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="SMS message"
            android:inputType="textMultiLine" />

        <Button
            android:id="@+id/smssendbutton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Send SMS Intent"
            android:layout_marginTop="8dp" />

        <EditText
            android:id="@+id/editTexttoApp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Text to share"
            android:layout_marginTop="14dp" />

        <Button
            android:id="@+id/gobutton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Share to other apps"
            android:layout_marginTop="8dp" />

        <EditText
            android:id="@+id/editCallPhone2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Phone to dial"
            android:inputType="phone"
            android:layout_marginTop="14dp" />

        <Button
            android:id="@+id/callbutton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Dial Number"
            android:layout_marginTop="8dp" />

    </LinearLayout>
</ScrollView>

JAVA — MainActivity.java (Sender)

package com.alone_x.implicitintent;

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;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    EditText url, phone, smsMessage, appText, callNo;
    Button urlbutton, smsbutton, gobutton, callbutton;

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

        url = findViewById(R.id.urledittext);
        phone = findViewById(R.id.editTextPhone);
        smsMessage = findViewById(R.id.editSmsText);
        appText = findViewById(R.id.editTexttoApp);
        callNo = findViewById(R.id.editCallPhone2);

        urlbutton = findViewById(R.id.browsebutton);
        smsbutton = findViewById(R.id.smssendbutton);
        gobutton = findViewById(R.id.gobutton);
        callbutton = findViewById(R.id.callbutton);

        urlbutton.setOnClickListener(v -> {
            Uri uri = Uri.parse(url.getText().toString());
            Intent i = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(i);
        });

        smsbutton.setOnClickListener(v -> {
            Uri uri = Uri.parse("smsto:" + phone.getText().toString());
            Intent i = new Intent(Intent.ACTION_SENDTO, uri);
            i.putExtra("sms_body", smsMessage.getText().toString());
            startActivity(i);
        });

        gobutton.setOnClickListener(v -> {
            Intent i = new Intent(Intent.ACTION_SEND);
            i.setType("text/plain");
            i.putExtra(Intent.EXTRA_TEXT, appText.getText().toString());
            startActivity(i);
        });

        callbutton.setOnClickListener(v -> {
            Uri uri = Uri.parse("tel:" + callNo.getText().toString());
            Intent i = new Intent(Intent.ACTION_DIAL, uri);
            startActivity(i);
        });
    }
}

Receiver App — com.alonex.receiver

UI — activity_main.xml

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

    <TextView
        android:id="@+id/tv1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Incoming text will show here"
        android:textSize="18sp" />
</FrameLayout>

JAVA — MainActivity.java (Receiver)

package com.alonex.receiver;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    TextView tv;

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

        tv = findViewById(R.id.tv1);
        Intent i = getIntent();
        String msg = i.getStringExtra(Intent.EXTRA_TEXT);
        if (msg != null) {
            tv.setText(msg);
        }
    }
}

Gradle (incase)

    implementation("androidx.appcompat:appcompat:1.6.1")
    implementation("com.google.android.material:material:1.9.0")

Manifest snippet (Receiver app)

Inside <activity ...>:

<intent-filter>
    <action android:name="android.intent.action.SEND" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:mimeType="text/plain" />
</intent-filter>

PRACT 5 — Sign-In Page using SharedPreferences


UI — activity_main.xml

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

    <EditText
        android:id="@+id/username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Username" />

    <EditText
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Password"
        android:inputType="textPassword"
        android:layout_marginTop="10dp" />

    <CheckBox
        android:id="@+id/checker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Remember me"
        android:layout_marginTop="8dp" />

    <Button
        android:id="@+id/login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Login"
        android:layout_marginTop="14dp" />

</LinearLayout>

JAVA — MainActivity.java

package com.example.practical5mc;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.*;

public class MainActivity extends AppCompatActivity {

    EditText username, password;
    Button btn;
    CheckBox check;
    int attempts = 3;
    SharedPreferences sp;

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

        username = findViewById(R.id.username);
        password = findViewById(R.id.password);
        btn = findViewById(R.id.login);
        check = findViewById(R.id.checker);

        sp = getSharedPreferences("spfile", MODE_PRIVATE);

        String savedUser = sp.getString("username", "");
        String savedPass = sp.getString("password", "");

        if (!savedUser.isEmpty() && !savedPass.isEmpty()) {
            username.setText(savedUser);
            password.setText(savedPass);
            check.setChecked(true);
        }

        btn.setOnClickListener(v -> {
            String u = username.getText().toString().trim();
            String p = password.getText().toString().trim();

            if (u.equals("admin") && p.equals("1234")) {

                if (check.isChecked()) {
                    SharedPreferences.Editor ed = sp.edit();
                    ed.putString("username", u);
                    ed.putString("password", p);
                    ed.apply();
                } else {
                    sp.edit().clear().apply();
                }

                startActivity(new Intent(MainActivity.this, Second.class));
                finish();
            } else {
                attempts--;
                showAttempts();

                if (attempts == 0) {
                    btn.setEnabled(false);
                    Toast.makeText(this, "Login disabled", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void showAttempts() {
        AlertDialog.Builder b = new AlertDialog.Builder(this);
        b.setTitle("Attempts Left");
        b.setMessage("You have " + attempts + " attempts left.");
        b.setPositiveButton("OK", (d, which) -> d.dismiss());
        b.show();
    }
}

JAVA — Second.java

package com.example.practical5mc;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

public class Second extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TextView tv = new TextView(this);
        tv.setText("Logged in successfully!");
        tv.setTextSize(24f);

        setContentView(tv);
    }
}
add this:
   <activity android:name=".Second"/>

PRAC 6 — Android Notification


UI — activity_main.xml

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

    <Button
        android:id="@+id/notifs"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Notification"
        android:layout_gravity="center" />

</FrameLayout>

JAVA — MainActivity.java

package com.example.practical6mc;

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

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    Button notification;
    NotificationManager nm;
    String CHANNEL_ID = "CHANNEL1";

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

        notification = findViewById(R.id.notifs);

        nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel ch = new NotificationChannel(
                    CHANNEL_ID,
                    "SIESCOMS",
                    NotificationManager.IMPORTANCE_HIGH
            );
            nm.createNotificationChannel(ch);
        }

        notification.setOnClickListener(v -> showNotif());
    }

    private void showNotif() {
        Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("https://siescoms.edu.in"));
        PendingIntent pi = PendingIntent.getActivity(
                this, 0, i, PendingIntent.FLAG_IMMUTABLE);

        NotificationCompat.Builder b = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setContentTitle("Simple Notification")
                .setContentText("Tap to open website")
                .setContentIntent(pi)
                .setAutoCancel(true);

        nm.notify(1, b.build());
    }
}

Instruction: put an icon called notif.png in res/drawable/.

Manifest:

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

PRAC 7 — Internal & External Storage


UI — activity_main.xml

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

    <MultiAutoCompleteTextView
        android:id="@+id/multi"
        android:layout_width="match_parent"
        android:layout_height="160dp"
        android:hint="Enter text here" />

    <Button
        android:id="@+id/btnstore"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Save Internal"
        android:layout_marginTop="8dp" />

    <Button
        android:id="@+id/btnretrieve"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Read Internal"
        android:layout_marginTop="6dp" />

    <Button
        android:id="@+id/btnextstore"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Save External"
        android:layout_marginTop="6dp" />

    <Button
        android:id="@+id/btnextread"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Read External"
        android:layout_marginTop="6dp" />

</LinearLayout>

UI — activity_display.xml

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

    <TextView
        android:id="@+id/tv1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="File content will appear here" />

</FrameLayout>

JAVA — MainActivity.java

package com.example.InternalExternalStorage;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Button;
import android.widget.MultiAutoCompleteTextView;
import android.widget.Toast;

import java.io.*;

public class MainActivity extends AppCompatActivity {

    Button btnstore, btnretrieve, btnextread, btnextstore;
    MultiAutoCompleteTextView ed1;
    File myFile;
    String folder = "dir1";

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

        btnstore = findViewById(R.id.btnstore);
        btnretrieve = findViewById(R.id.btnretrieve);
        btnextread = findViewById(R.id.btnextread);
        btnextstore = findViewById(R.id.btnextstore);
        ed1 = findViewById(R.id.multi);

        btnstore.setOnClickListener(v -> saveToInternal(ed1.getText().toString()));
        btnretrieve.setOnClickListener(v -> readFromInternal());
        btnextstore.setOnClickListener(v -> saveToExternal(ed1.getText().toString()));
        btnextread.setOnClickListener(v -> readFromExternal());
    }

    private void saveToInternal(String data) {
        try {
            FileOutputStream fos = openFileOutput("demo.txt", MODE_PRIVATE);
            OutputStreamWriter w = new OutputStreamWriter(fos);
            w.write(data);
            w.close();
            Toast.makeText(this, "Saved to internal", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void readFromInternal() {
        StringBuilder buffer = new StringBuilder();
        try {
            FileInputStream fis = openFileInput("demo.txt");
            InputStreamReader r = new InputStreamReader(fis);
            char[] cbuf = new char[256];
            int count;
            while ((count = r.read(cbuf)) > 0) {
                buffer.append(cbuf, 0, count);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Intent i = new Intent(this, MainDisplay.class);
        i.putExtra("value", buffer.toString());
        startActivity(i);
    }

    private void saveToExternal(String data) {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            myFile = new File(getExternalFilesDir(folder), "demo.txt");
            try {
                FileOutputStream fos = new FileOutputStream(myFile);
                fos.write(data.getBytes());
                fos.close();
                Toast.makeText(this, "Saved to external", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void readFromExternal() {
        StringBuilder buffer = new StringBuilder();
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            myFile = new File(getExternalFilesDir(folder), "demo.txt");
            try {
                FileInputStream fis = new FileInputStream(myFile);
                BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                String line;
                while ((line = br.readLine()) != null) {
                    buffer.append(line).append("\n");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Intent i = new Intent(this, MainDisplay.class);
        i.putExtra("value", buffer.toString());
        startActivity(i);
    }
}

JAVA — MainDisplay.java

package com.example.InternalExternalStorage;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

public class MainDisplay extends AppCompatActivity {

    TextView tv;

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

        tv = findViewById(R.id.tv1);
        String val = getIntent().getStringExtra("value");
        tv.setText(val);
    }
}

PRAC 8 — SQLite Database CRUD Operations


UI — activity_main.xml

(Main screen with input fields + CRUD buttons)

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

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

        <EditText
            android:id="@+id/rno"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Roll No"
            android:inputType="number" />

        <EditText
            android:id="@+id/name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Name"
            android:layout_marginTop="8dp" />

        <EditText
            android:id="@+id/gender"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Gender"
            android:layout_marginTop="8dp" />

        <EditText
            android:id="@+id/score1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Score 1"
            android:inputType="number"
            android:layout_marginTop="8dp" />

        <EditText
            android:id="@+id/score2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Score 2"
            android:inputType="number"
            android:layout_marginTop="8dp" />

        <Button android:id="@+id/add" android:text="Insert"
            android:layout_width="match_parent" android:layout_height="wrap_content"
            android:layout_marginTop="14dp"/>

        <Button android:id="@+id/view" android:text="View All"
            android:layout_width="match_parent" android:layout_height="wrap_content"
            android:layout_marginTop="8dp"/>

        <Button android:id="@+id/search" android:text="Search"
            android:layout_width="match_parent" android:layout_height="wrap_content"
            android:layout_marginTop="8dp"/>

        <Button android:id="@+id/update" android:text="Update"
            android:layout_width="match_parent" android:layout_height="wrap_content"
            android:layout_marginTop="8dp"/>

        <Button android:id="@+id/delete" android:text="Delete"
            android:layout_width="match_parent" android:layout_height="wrap_content"
            android:layout_marginTop="8dp"/>

    </LinearLayout>
</ScrollView>

UI — activity_viewdata.xml

(This will show the retrieved data)

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

    <TextView
        android:id="@+id/record"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="16sp" />

</ScrollView>

JAVA — DBHelper.java

package com.example.practical8mc;

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

public class DBHelper extends SQLiteOpenHelper {

    public DBHelper(Context c) {
        super(c, "studentdb", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE student(rno INTEGER PRIMARY KEY, name TEXT, gender TEXT, s1 INTEGER, s2 INTEGER)");
    }

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

    public void insert(int rno, String name, String gender, int s1, int s2) {
        SQLiteDatabase db = getWritableDatabase();
        db.execSQL("INSERT INTO student VALUES(?,?,?,?,?)",
                new Object[]{rno, name, gender, s1, s2});
    }

    public Cursor viewAll() {
        SQLiteDatabase db = getReadableDatabase();
        return db.rawQuery("SELECT * FROM student", null);
    }

    public Cursor search(int rno) {
        SQLiteDatabase db = getReadableDatabase();
        return db.rawQuery("SELECT * FROM student WHERE rno=?", new String[]{String.valueOf(rno)});
    }

    public void update(int rno, String name, String gender, int s1, int s2) {
        SQLiteDatabase db = getWritableDatabase();
        db.execSQL("UPDATE student SET name=?, gender=?, s1=?, s2=? WHERE rno=?",
                new Object[]{name, gender, s1, s2, rno});
    }

    public void delete(int rno) {
        SQLiteDatabase db = getWritableDatabase();
        db.execSQL("DELETE FROM student WHERE rno=?", new Object[]{String.valueOf(rno)});
    }
}

JAVA — MainActivity.java

package com.example.practical8mc;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.*;

public class MainActivity extends AppCompatActivity {

    EditText rno, name, gender, s1, s2;
    Button add, view, search, update, delete;
    DBHelper db;

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

        rno = findViewById(R.id.rno);
        name = findViewById(R.id.name);
        gender = findViewById(R.id.gender);
        s1 = findViewById(R.id.score1);
        s2 = findViewById(R.id.score2);
        
        add = findViewById(R.id.add);
        view = findViewById(R.id.view);
        search = findViewById(R.id.search);
        update = findViewById(R.id.update);
        delete = findViewById(R.id.delete);

        db = new DBHelper(this);

        add.setOnClickListener(v -> {
            db.insert(
                Integer.parseInt(rno.getText().toString()),
                name.getText().toString(),
                gender.getText().toString(),
                Integer.parseInt(s1.getText().toString()),
                Integer.parseInt(s2.getText().toString())
            );
            Toast.makeText(this, "Inserted", Toast.LENGTH_SHORT).show();
        });

        view.setOnClickListener(v -> openData(db.viewAll()));

        search.setOnClickListener(v -> {
            int roll = Integer.parseInt(rno.getText().toString());
            openData(db.search(roll));
        });

        update.setOnClickListener(v -> {
            db.update(
                    Integer.parseInt(rno.getText().toString()),
                    name.getText().toString(),
                    gender.getText().toString(),
                    Integer.parseInt(s1.getText().toString()),
                    Integer.parseInt(s2.getText().toString())
            );
            Toast.makeText(this, "Updated", Toast.LENGTH_SHORT).show();
        });

        delete.setOnClickListener(v -> {
            db.delete(Integer.parseInt(rno.getText().toString()));
            Toast.makeText(this, "Deleted", Toast.LENGTH_SHORT).show();
        });
    }

    private void openData(Cursor c) {
        StringBuilder sb = new StringBuilder();
        while (c.moveToNext()) {
            sb.append("Rno: ").append(c.getInt(0)).append("\n")
              .append("Name: ").append(c.getString(1)).append("\n")
              .append("Gender: ").append(c.getString(2)).append("\n")
              .append("Score1: ").append(c.getInt(3)).append("\n")
              .append("Score2: ").append(c.getInt(4)).append("\n\n");
        }

        Intent i = new Intent(this, ViewData.class);
        i.putExtra("data", sb.toString());
        startActivity(i);
    }
}

JAVA — ViewData.java

package com.example.practical8mc;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

public class ViewData extends AppCompatActivity {

    TextView rec;

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

        rec = findViewById(R.id.record);
        rec.setText(getIntent().getStringExtra("data"));
    }
}
AndroidManifest: <activity android:name=".ViewData"/>

PRAC 9 — Firebase Realtime Database CRUD

(This version uses simple Firebase push, update, delete)


UI — activity_main.xml

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

    <LinearLayout
        android:id="@+id/mainLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <!-- Employee Number -->
        <EditText
            android:id="@+id/eno"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Employee No"
            android:inputType="number"
            android:layout_marginBottom="8dp"/>

        <!-- Name -->
        <EditText
            android:id="@+id/name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Name"
            android:inputType="textPersonName"
            android:layout_marginBottom="8dp"/>

        <!-- Salary -->
        <EditText
            android:id="@+id/salary"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Salary"
            android:inputType="numberDecimal"
            android:layout_marginBottom="8dp"/>

        <!-- Department -->
        <EditText
            android:id="@+id/dept"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Department"
            android:inputType="text"
            android:layout_marginBottom="12dp"/>

        <!-- Action Buttons -->
        <Button
            android:id="@+id/add"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Add"
            android:layout_marginBottom="8dp"/>

        <Button
            android:id="@+id/view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="View"
            android:layout_marginBottom="8dp"/>

        <Button
            android:id="@+id/update"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Update"
            android:layout_marginBottom="8dp"/>

        <Button
            android:id="@+id/delete"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Delete"
            android:layout_marginBottom="12dp"/>

        <!-- ListView -->
        <ListView
            android:id="@+id/listAll"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:divider="@android:color/darker_gray"
            android:dividerHeight="1dp"
            android:layout_marginTop="16dp"/>
    </LinearLayout>
</ScrollView>


JAVA — MainActivity.java

package com.example.practical9mc;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.*;
import com.google.firebase.database.*;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    EditText eno, name, salary, dept;
    Button add, view, update, delete;
    ListView list;
    ArrayList<String> arr;
    ArrayAdapter<String> ad;
    DatabaseReference db;

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

        eno = findViewById(R.id.eno);
        name = findViewById(R.id.name);
        salary = findViewById(R.id.salary);
        dept = findViewById(R.id.dept);

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

        list = findViewById(R.id.listAll);
        arr = new ArrayList<>();
        ad = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arr);
        list.setAdapter(ad);

        db = FirebaseDatabase.getInstance().getReference("employees");

        add.setOnClickListener(v -> {
            String id = eno.getText().toString();
            Employee obj = new Employee(
                    id,
                    name.getText().toString(),
                    salary.getText().toString(),
                    dept.getText().toString()
            );
            db.child(id).setValue(obj);
            Toast.makeText(this, "Added", Toast.LENGTH_SHORT).show();
        });

        view.setOnClickListener(v -> db.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot d) {
                arr.clear();
                for (DataSnapshot s : d.getChildren()) {
                    Employee e = s.getValue(Employee.class);
                    arr.add(e.toString());
                }
                ad.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(DatabaseError e) {}
        }));

        update.setOnClickListener(v -> {
            String id = eno.getText().toString();
            db.child(id).child("name").setValue(name.getText().toString());
            db.child(id).child("salary").setValue(salary.getText().toString());
            db.child(id).child("dept").setValue(dept.getText().toString());
            Toast.makeText(this, "Updated", Toast.LENGTH_SHORT).show();
        });

        delete.setOnClickListener(v -> {
            String id = eno.getText().toString();
            db.child(id).removeValue();
            Toast.makeText(this, "Deleted", Toast.LENGTH_SHORT).show();
        });
    }
}

JAVA — Employee.java

package com.example.practical9mc;

public class Employee {

    String eno, name, salary, dept;

    public Employee() {}

    public Employee(String eno, String name, String salary, String dept) {
        this.eno = eno;
        this.name = name;
        this.salary = salary;
        this.dept = dept;
    }

    public String toString() {
        return "E.No: " + eno + "\nName: " + name + "\nSalary: " + salary + "\nDept: " + dept;
    }
}

PRAC 10 — Image Animation (Translate, Scale, Rotate, Fade)


UI — activity_main.xml

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

    <ImageView
        android:id="@+id/image"
        android:layout_width="220dp"
        android:layout_height="220dp"
        android:src="@drawable/image"
        android:layout_centerHorizontal="true" />

    <LinearLayout
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="16dp"
        android:gravity="center"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button android:id="@+id/translate" android:text="Translate"/>
        <Button android:id="@+id/scale" android:text="Scale" android:layout_marginLeft="4dp"/>
        <Button android:id="@+id/rotate" android:text="Rotate" android:layout_marginLeft="4dp"/>
        <Button android:id="@+id/fade" android:text="Fade" android:layout_marginLeft="4dp"/>
    </LinearLayout>
</RelativeLayout>

JAVA — MainActivity.java

package com.example.practical10mc;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.animation.*;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

    ImageView img;
    Button translate, scale, rotate, fade;

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

        img = findViewById(R.id.image);
        translate = findViewById(R.id.translate);
        scale = findViewById(R.id.scale);
        rotate = findViewById(R.id.rotate);
        fade = findViewById(R.id.fade);

        translate.setOnClickListener(v -> {
            Animation a = new TranslateAnimation(0, 300, 0, 0);
            a.setDuration(800);
            img.startAnimation(a);
        });

        scale.setOnClickListener(v -> {
            Animation a = new ScaleAnimation(1, 1.6f, 1, 1.6f);
            a.setDuration(800);
            img.startAnimation(a);
        });

        rotate.setOnClickListener(v -> {
            Animation a = new RotateAnimation(0, 360,
                    Animation.RELATIVE_TO_SELF, 0.5f,
                    Animation.RELATIVE_TO_SELF, 0.5f);
            a.setDuration(800);
            img.startAnimation(a);
        });

        fade.setOnClickListener(v -> {
            Animation a = new AlphaAnimation(1, 0);
            a.setDuration(800);
            img.startAnimation(a);
        });
    }
}

PRAC 11 — Audio & Video Playback


UI — activity_main.xml

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

    <Button
        android:id="@+id/btnPlay"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Play Audio" />

    <Button
        android:id="@+id/btnPause"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Pause Audio" />

    <Button
        android:id="@+id/btnStop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Stop Audio" />

    <Button
        android:id="@+id/btnVideo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Play Video" />

    <VideoView
        android:id="@+id/videoView"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:layout_marginTop="20dp" />

</LinearLayout>

JAVA — MainActivity.java

package com.example.audio_video;

import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Button;
import android.widget.VideoView;
import android.widget.MediaController;

public class MainActivity extends AppCompatActivity {

    Button play, pause, stop, video;
    MediaPlayer mp;
    VideoView videoView;
    MediaController mediaController;

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

        play = findViewById(R.id.btnPlay);
        pause = findViewById(R.id.btnPause);
        stop = findViewById(R.id.btnStop);
        video = findViewById(R.id.btnVideo);
        videoView = findViewById(R.id.videoView);

        // Load audio file
        mp = MediaPlayer.create(this, R.raw.clip_12);

        // === AUDIO BUTTONS ===
        play.setOnClickListener(v -> mp.start());

        pause.setOnClickListener(v -> {
            if (mp.isPlaying()) {
                mp.pause();
            }
        });

        stop.setOnClickListener(v -> {
            if (mp.isPlaying()) {
                mp.stop();
                mp = MediaPlayer.create(this, R.raw.clip_12); // reload after stop
            }
        });

        // === VIDEO PLAYER WITH CONTROLS ===
        mediaController = new MediaController(this);
        mediaController.setAnchorView(videoView);

        video.setOnClickListener(v -> {
            String path = "android.resource://" + getPackageName() + "/" + R.raw.clip_12;
            Uri uri = Uri.parse(path);

            videoView.setVideoURI(uri);
            videoView.setMediaController(mediaController);
            videoView.start();
        });
    }
}

PRAC 12 — Current Location


UI — 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:padding="20dp"
    android:orientation="vertical">

    <TextView
        android:id="@+id/txtlocation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Your Location Will Appear Here"
        android:textSize="18sp"
        android:padding="16dp" />

    <Button
        android:id="@+id/btnlocation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get Location"
        android:layout_marginTop="20dp" />

</LinearLayout>

JAVA — MainActivity.java

package com.example.location;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity implements LocationListener {

    private LocationManager lm;
    Button btnlocation;
    TextView txtlocation;

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

        txtlocation = findViewById(R.id.txtlocation);
        btnlocation = findViewById(R.id.btnlocation);

        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 100);
        }

        btnlocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getLocation();
            }
        });
    }

    private void getLocation() {
        lm = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 100, MainActivity.this);
    }

    @Override
    public void onLocationChanged(@NonNull Location location) {
        Toast.makeText(getApplicationContext(),location.getLongitude()
                +  " " +location.getLatitude(),Toast.LENGTH_LONG).show();
        Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
        try {
            List <Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
            String address = addresses.get(0).getAddressLine(0);
            txtlocation.setText(address);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Manifest Permissions

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


PRAC 13 — REST API (Volley + OkHttp + Retrofit)

One UI is shared for all.


Mocki json format:

{
  "userId": 1,
  "id": 101,
  "title": "Finish Android project setup",
  "completed": false
}

Using the API: https://mocki.io/v1/c887be0f-54f8-4f26-a237-2364c10fc704


UI — activity_main.xml

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

    <!-- Volley Button -->
    <Button
        android:id="@+id/volleyBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Fetch using Volley"
        android:layout_marginBottom="8dp"/>

    <!-- Retrofit Button -->
    <Button
        android:id="@+id/retrofitBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Fetch using Retrofit"
        android:layout_marginBottom="8dp"/>

    <!-- OkHttp Button -->
    <Button
        android:id="@+id/okhttpBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Fetch using OkHttp"
        android:layout_marginBottom="16dp"/>

    <!-- Response Text -->
    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="API Response will appear here…"
        android:textSize="16sp"
        android:textColor="@android:color/black"
        android:padding="12dp"
        android:background="@android:color/darker_gray"/>
</LinearLayout>


MODEL — Todo.java

package com.example.mprog9;

public class Todo {
    public int userId;
    public int id;
    public String title;
    public boolean completed;
}

INTERFACE — Api.java

package com.example.mprog9;

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

public interface Api {

    @GET("c887be0f-54f8-4f26-a237-2364c10fc704")
    Call<Todo> getTodo();
}

MAIN SCREEN — MainActivity.java

(Handles: Volley, Button to RetrofitActivity, Button to OkHttpActivity)

package com.example.mprog9;

import androidx.appcompat.app.AppCompatActivity;

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

import com.android.volley.Request;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

public class MainActivity extends AppCompatActivity {

    TextView tv;
    Button volleyBtn, retrofitBtn, okhttpBtn;

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

        volleyBtn = findViewById(R.id.volleyBtn);
        retrofitBtn = findViewById(R.id.retrofitBtn);
        okhttpBtn = findViewById(R.id.okhttpBtn);
        tv = findViewById(R.id.tv);

        // VOLLEY
        volleyBtn.setOnClickListener(v -> {
            String url = "https://mocki.io/v1/c887be0f-54f8-4f26-a237-2364c10fc704";

            StringRequest sr = new StringRequest(Request.Method.GET, url,
                    response -> tv.setText(response),
                    error -> tv.setText("Error: " + error.toString()));

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

        // RETROFIT
        retrofitBtn.setOnClickListener(v ->
                startActivity(new Intent(MainActivity.this, RetrofitActivity.class))
        );

        // OKHTTP
        okhttpBtn.setOnClickListener(v ->
                startActivity(new Intent(MainActivity.this, OkHttpActivity.class))
        );
    }
}

RETROFIT — RetrofitActivity.java

package com.example.mprog9;

import androidx.appcompat.app.AppCompatActivity;

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

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

public class RetrofitActivity extends AppCompatActivity {

    TextView tv;
    Button btn;

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

        btn = findViewById(R.id.retrofitBtn);
        tv = findViewById(R.id.tv);

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

    private void fetchData() {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://mocki.io/v1/")   // must end with /
                .addConverterFactory(GsonConverterFactory.create())
                .build();

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

        api.getTodo().enqueue(new Callback<Todo>() {
            @Override
            public void onResponse(Call<Todo> call, Response<Todo> response) {
                if (response.body() != null) {
                    tv.setText("Title: " + response.body().title);
                    tv.append("\nCompleted: " + response.body().completed);
                }
            }

            @Override
            public void onFailure(Call<Todo> call, Throwable t) {
                tv.setText("Error occurred!");
            }
        });
    }
}

OKHTTP — OkHttpActivity.java

package com.example.mprog9;

import androidx.appcompat.app.AppCompatActivity;

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

import java.io.IOException;

import okhttp3.*;

public class OkHttpActivity extends AppCompatActivity {

    TextView tv;
    Button btn;

    OkHttpClient client = new OkHttpClient();

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

        btn = findViewById(R.id.okhttpBtn);
        tv = findViewById(R.id.tv);

        btn.setOnClickListener(v -> fetchUsingOkHttp());
    }

    private void fetchUsingOkHttp() {

        Request request = new Request.Builder()
                .url("https://mocki.io/v1/c887be0f-54f8-4f26-a237-2364c10fc704")
                .build();

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

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

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

Manifest Permission

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

Gradle Dependencies

implementation 'com.android.volley:volley:1.2.1'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.okhttp3:okhttp:4.10.0'

PRAC 14 — BMI Calculator (Flutter)

Using basic buttons, setState, and evaluation logic WITHOUT external packages.


UI + LOGIC — main.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;

  void calculateBMI() {
    final heightText = heightController.text.trim();
    final weightText = weightController.text.trim();

    if (heightText.isEmpty || weightText.isEmpty) {
      _showError("Please enter both height and weight.");
      return;
    }

    final double? height = double.tryParse(heightText);
    final double? weight = double.tryParse(weightText);

    if (height == null || weight == null || height <= 0 || weight <= 0) {
      _showError("Enter valid positive numbers.");
      return;
    }

    setState(() {
      bmiResult = weight / (height * height);
    });
  }

  void _showError(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message), backgroundColor: Colors.red),
    );
  }

  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 = null;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.green,
        title: const Text(
          'BMI Calculator',
          style: TextStyle(color: Colors.white),
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        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: 10),
            TextButton(
              onPressed: clearResult,
              child: const Text("Clear"),
            ),
            const SizedBox(height: 30),
            if (bmiResult != null)
              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: 26,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    Text(
                      'You are ${_getCategory(bmiResult!)}',
                      style: const TextStyle(fontSize: 20),
                    ),
                  ],
                ),
              ),
          ],
        ),
      ),
    );
  }
}

Instructions

Run in VS Code or Android Studio. Add dependency to pubspec.yaml:

math_expressions: ^2.4.0

PRAC 15 — Registration Form (Flutter)


UI + LOGIC — 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 submitForm() {
    if (nameController.text.trim().isEmpty) {
      _showError("Name cannot be empty");
      return;
    }

    if (gender == null) {
      _showError("Please select a gender");
      return;
    }

    if (!langEnglish && !langHindi && !langMarathi) {
      _showError("Select at least one language");
      return;
    }

    if (selectedCity == null) {
      _showError("Select a city");
      return;
    }

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

    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => Details(
          name: nameController.text,
          gender: gender!,
          languages: languages,
          selectedCity: selectedCity!,
        ),
      ),
    );
  }

  void _showError(String msg) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(msg), backgroundColor: Colors.red),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.green,
        title: const Text("Registration Form", style: TextStyle(color: Colors.white)),
      ),
      body: Container(
        color: darkBackground ? Colors.green[50] : Colors.white,
        padding: const EdgeInsets.all(16),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              // Name input
              TextField(
                controller: nameController,
                decoration: const InputDecoration(
                  labelText: "Enter Name",
                  border: OutlineInputBorder(),
                ),
              ),
              const SizedBox(height: 16),

              // Gender
              const Text("Select 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),

              // Language
              const Text("Select Languages:"),
              CheckboxListTile(
                title: const Text("English"),
                value: langEnglish,
                onChanged: (value) => setState(() => langEnglish = value!),
              ),
              CheckboxListTile(
                title: const Text("Hindi"),
                value: langHindi,
                onChanged: (value) => setState(() => langHindi = value!),
              ),
              CheckboxListTile(
                title: const Text("Marathi"),
                value: langMarathi,
                onChanged: (value) => setState(() => langMarathi = value!),
              ),

              const SizedBox(height: 16),

              // Dropdown
              DropdownButtonFormField(
                decoration: const InputDecoration(border: OutlineInputBorder()),
                hint: const Text("Select City"),
                value: selectedCity,
                items: cities
                    .map((city) => DropdownMenuItem(value: city, child: Text(city)))
                    .toList(),
                onChanged: (value) => setState(() => selectedCity = value),
              ),

              const SizedBox(height: 16),

              // Switch
              SwitchListTile(
                title: const Text("Dark Background"),
                value: darkBackground,
                onChanged: (value) => setState(() => darkBackground = value),
              ),

              const SizedBox(height: 24),

              ElevatedButton(
                onPressed: submitForm,
                style: ElevatedButton.styleFrom(backgroundColor: Colors.green),
                child: const Text("Submit"),
              )
            ],
          ),
        ),
      ),
    );
  }
}

##   **UI + LOGIC — `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(
        backgroundColor: Colors.blue,
        title: const Text("Details"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text("Name: $name", style: const TextStyle(fontSize: 18)),
            Text("Gender: $gender", style: const TextStyle(fontSize: 18)),
            Text("Languages: ${languages.join(", ")}", style: const TextStyle(fontSize: 18)),
            Text("City: $selectedCity", style: const TextStyle(fontSize: 18)),
          ],
        ),
      ),
    );
  }
}

Instructions

No packages needed. This validates static username/password.


PRAC 16 – Flutter SQLite CRUD Application

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.8
  sqflite: ^2.3.0
  path_provider: ^2.1.1
  path: ^1.8.3

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,
      title: 'Student DB (SQLite)',
      theme: ThemeData(
        primarySwatch: Colors.teal,
      ),
      home: const MyHomePage(),
    );
  }
}
---

Main UI + Logic (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 TextEditingController _nameController = TextEditingController();
  final TextEditingController _idController = TextEditingController();

  String _message = "";
  List<Map<String, dynamic>> _records = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Student Database (SQLite)"),
        backgroundColor: Colors.teal,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              TextField(
                controller: _nameController,
                decoration: const InputDecoration(
                  labelText: "Enter Student Name",
                  border: OutlineInputBorder(),
                ),
              ),
              const SizedBox(height: 10),

              TextField(
                controller: _idController,
                keyboardType: TextInputType.number,
                decoration: const InputDecoration(
                  labelText: "Enter ID (for Update/Delete)",
                  border: OutlineInputBorder(),
                ),
              ),
              const SizedBox(height: 20),

              ElevatedButton(
                onPressed: () async {
                  await DatabaseHelper.instance.insert({
                    DatabaseHelper.columnName: _nameController.text,
                  });
                  setState(() {
                    _message = "Record Inserted";
                  });
                  _nameController.clear();
                },
                child: const Text("Insert Record"),
              ),
              const SizedBox(height: 10),

              ElevatedButton(
                onPressed: () async {
                  List<Map<String, dynamic>> rows =
                      await DatabaseHelper.instance.showAll();
                  setState(() {
                    _records = rows;
                    _message = "Records Fetched";
                  });
                },
                child: const Text("Show Records"),
              ),
              const SizedBox(height: 10),

              ElevatedButton(
                onPressed: () async {
                  await DatabaseHelper.instance.update({
                    DatabaseHelper.columnId: int.parse(_idController.text),
                    DatabaseHelper.columnName: _nameController.text,
                  });
                  setState(() {
                    _message = "Record Updated";
                  });
                  _idController.clear();
                  _nameController.clear();
                },
                child: const Text("Update Record"),
              ),
              const SizedBox(height: 10),

              ElevatedButton(
                onPressed: () async {
                  await DatabaseHelper.instance
                      .delete(int.parse(_idController.text));
                  setState(() {
                    _message = "Record Deleted";
                  });
                  _idController.clear();
                },
                child: const Text("Delete Record"),
              ),
              const SizedBox(height: 20),

              Center(
                child: Text(
                  _message,
                  style: const TextStyle(
                    fontSize: 16,
                    color: Colors.blue,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              const SizedBox(height: 20),

              if (_records.isNotEmpty)
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      "Student Records:",
                      style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 8),

                    ..._records.map(
                      (record) => Padding(
                        padding: const EdgeInsets.symmetric(vertical: 5),
                        child: Text(
                          "ID: ${record['_id']} | Name: ${record['name']}",
                          style: const TextStyle(fontSize: 16),
                        ),
                      ),
                    )
                  ],
                ),
            ],
          ),
        ),
      ),
    );
  }
}

Database File (database_helper.dart)

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

class DatabaseHelper {
  static final _dbName = "student.db";
  static final _dbVersion = 1;
  static final _tableName = "student";

  static final columnId = "_id";
  static final 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 dir = await getApplicationDocumentsDirectory();
    String path = join(dir.path, _dbName);

    return await openDatabase(path,
        version: _dbVersion, onCreate: _onCreate);
  }

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

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

  Future<List<Map<String, dynamic>>> showAll() async {
    Database? db = await instance.database;
    return await db!.query(_tableName);
  }

  Future<int> update(Map<String, dynamic> row) async {
    Database? db = await instance.database;
    int id = row[columnId];

    return await db!.update(
      _tableName,
      row,
      where: "$columnId = ?",
      whereArgs: [id],
    );
  }

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



PRACTICAL 17 — Fetch API Data (HTTP GET Request)

Using the built-in http package.


UI + LOGIC — main.dart

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

void main() {
  runApp(MaterialApp(
    debugShowCheckedModeBanner: false,
    home: EmployeeListScreen(),
  ));
}

class EmployeeListScreen extends StatefulWidget {
  @override
  _EmployeeListScreenState createState() => _EmployeeListScreenState();
}

class _EmployeeListScreenState extends State<EmployeeListScreen> {
  List<Employee> empList = [];
  bool loading = false;

  fetchEmployees() async {
    setState(() {
      loading = true;
    });

    String url = "https://mocki.io/v1/a81e7b8d-e519-42d8-890a-ffb28e41bbec";

    final response = await http.get(Uri.parse(url));

    if (response.statusCode == 200) {
      List data = jsonDecode(response.body);

      empList = data.map((e) => Employee.fromJson(e)).toList();

      setState(() {
        loading = false;
      });
    } else {
      setState(() {
        loading = false;
      });
      print("Error fetching data");
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Employee Details (REST API)"),
      ),
      body: loading
          ? Center(child: CircularProgressIndicator())
          : ListView.builder(
        itemCount: empList.length,
        itemBuilder: (context, index) {
          Employee e = empList[index];

          return Card(
            elevation: 4,
            margin: EdgeInsets.all(10),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
            child: Padding(
              padding: EdgeInsets.all(14),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text("Employee ID: ${e.empid}",
                      style: TextStyle(
                          fontWeight: FontWeight.bold, fontSize: 18)),
                  SizedBox(height: 5),
                  Text("Name: ${e.empname}",
                      style: TextStyle(fontSize: 16)),
                  SizedBox(height: 5),
                  Text("Department: ${e.dept}",
                      style: TextStyle(fontSize: 16)),
                  SizedBox(height: 5),
                  Text("Salary: ₹${e.salary}",
                      style: TextStyle(
                          fontSize: 16, color: Colors.green[700])),
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}

employee.dart

class Employee {
  final int empid;
  final String empname;
  final int salary;
  final String dept;

  Employee({
    required this.empid,
    required this.empname,
    required this.salary,
    required this.dept,
  });

  factory Employee.fromJson(Map<String, dynamic> j) {
    return Employee(
      empid: j["empid"],
      empname: j["empname"],
      salary: j["salary"],
      dept: j["dept"],
    );
  }
}

Instructions

Add the http package in pubspec.yaml:

http: ^1.1.0

mocki link: https://mocki.io/v1/a81e7b8d-e519-42d8-890a-ffb28e41bbec

[
  {
    "empid": 101,
    "empname": "Alice Johnson",
    "salary": 55000,
    "dept": "HR"
  },
  {
    "empid": 102,
    "empname": "Bob Smith",
    "salary": 62000,
    "dept": "Finance"
  },
  {
    "empid": 103,
    "empname": "Charlie Davis",
    "salary": 48000,
    "dept": "IT"
  },
  {
    "empid": 104,
    "empname": "Diana Lee",
    "salary": 70000,
    "dept": "Marketing"
  },
  {
    "empid": 105,
    "empname": "Ethan Brown",
    "salary": 53000,
    "dept": "Operations"
  },
  {
    "empid": 106,
    "empname": "Fiona White",
    "salary": 60000,
    "dept": "Sales"
  }
]
  • Contact us
  • Jobs
  • Privacy
  • Manage cookies
  • Terms of use
  • Trademarks
© 2025 Microsoft