Android_slip_13B

1. Create Database Helper Class (DBHelper.java):
    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;

    public class DBHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "StudentDB";
    private static final int DATABASE_VERSION = 1;

    // Table and column names
    private static final String TABLE_STUDENT = "Student";
    private static final String COLUMN_SID = "Sid";
    private static final String COLUMN_SNAME = "Sname";
    private static final String COLUMN_PHNO = "phno";

    // Create table query
    private static final String CREATE_TABLE_STUDENT = "CREATE TABLE " + TABLE_STUDENT + " ("
    + COLUMN_SID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
    + COLUMN_SNAME + " TEXT, "
    + COLUMN_PHNO + " TEXT)";

    public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    // Create tables
    db.execSQL(CREATE_TABLE_STUDENT);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop existing tables and recreate them if needed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_STUDENT);
    onCreate(db);
    }

    // Method to add a student
    public long addStudent(String name, String phoneNumber) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(COLUMN_SNAME, name);
    values.put(COLUMN_PHNO, phoneNumber);

    long rowId = db.insert(TABLE_STUDENT, null, values);
    db.close();
    return rowId;
    }

    // Method to get all students
    public Cursor getAllStudents() {
    SQLiteDatabase db = this.getReadableDatabase();
    return db.rawQuery("SELECT * FROM " + TABLE_STUDENT, null);
    }

    // Method to delete a student
    public void deleteStudent(long studentId) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_STUDENT, COLUMN_SID + "=?", new String[]{String.valueOf(studentId)});
    db.close();
    }
    }


2. Layout (activity_main.xml):
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

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

    <EditText
    android:id="@+id/editTextPhoneNumber"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    android:hint="Enter Phone Number"
    android:inputType="phone"/>

    <Button
    android:id="@+id/btnAddStudent"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="16dp"
    android:text="Add Student"/>

    <Button
    android:id="@+id/btnShowStudents"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="16dp"
    android:text="Show Students"/>

    <Button
    android:id="@+id/btnDeleteStudent"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="16dp"
    android:text="Delete Student"/>
    </LinearLayout>

3. MainActivity Class (MainActivity.java):
    import android.database.Cursor;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;

    import androidx.appcompat.app.AppCompatActivity;

    public class MainActivity extends AppCompatActivity {

    private EditText editTextName, editTextPhoneNumber;
    private Button btnAddStudent, btnShowStudents, btnDeleteStudent;
    private DBHelper dbHelper;

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

    editTextName = findViewById(R.id.editTextName);
    editTextPhoneNumber = findViewById(R.id.editTextPhoneNumber);
    btnAddStudent = findViewById(R.id.btnAddStudent);
    btnShowStudents = findViewById(R.id.btnShowStudents);
    btnDeleteStudent = findViewById(R.id.btnDeleteStudent);

    dbHelper = new DBHelper(this);

    btnAddStudent.setOnClickListener(new View.OnClickListener() {
    @Override
    public void o-nClick(View v) {
    addStudent();
    }
    });

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

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

    private void addStudent() {
    String name = editTextName.getText().toString().trim();
    String phoneNumber = editTextPhoneNumber.getText().toString().trim();

    if (!name.isEmpty() && !phoneNumber.isEmpty()) {
    long rowId = dbHelper.addStudent(name, phoneNumber);

    if (rowId != -1) {
    Toast.makeText(this, "Student added successfully!", Toast.LENGTH_SHORT).show();
    } else {
    Toast.makeText(this, "Error adding student", Toast.LENGTH_SHORT).show();
    }
    } else {
    Toast.makeText(this, "Please enter name and phone number", Toast.LENGTH_SHORT).show();
    }
    }

    private void showStudents() {
    Cursor cursor = dbHelper.getAllStudents();

    StringBuilder studentsInfo = new StringBuilder("Students:\n");
    while (cursor.moveToNext()) {
    int sid = cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_SID));
    String name = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_SNAME));
    String phoneNumber = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_PHNO));

    studentsInfo.append("ID: ").append(sid).append(", Name: ").append(name)
    .append(", Phone Number: ").append(phoneNumber).append("\n");
    }

    if (studentsInfo.length() > 0) {
    Toast.makeText(this, studentsInfo.toString(), Toast.LENGTH_LONG).show();
    } else {
    Toast.makeText(this, "No students found", Toast.LENGTH_SHORT).show();
    }
    }

    private void deleteStudent() {
    // For simplicity, this example deletes the first student. In a real app, you might want to select the student to delete.
    Cursor cursor = dbHelper.getAllStudents();
    if (cursor.moveToFirst()) {
    long studentId = cursor.getLong(cursor.getColumnIndex(DBHelper.COLUMN_SID));
    dbHelper.deleteStudent(studentId);
    Toast.makeText(this, "Student deleted successfully!", Toast.LENGTH_SHORT).show();
    } else {
    Toast.makeText(this, "No students to delete", Toast.LENGTH_SHORT).show();
    }
    }
    }

No comments:

Post a Comment