0% found this document useful (0 votes)
7 views

db prog

This document is a Java code for an Android application that allows users to input and save names and ages into a SQLite database. It includes a user interface with input fields and a button to save the data, as well as functionality to display the saved entries. The application creates a database if it doesn't exist and handles user input validation before saving the data.

Uploaded by

pareshloq
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

db prog

This document is a Java code for an Android application that allows users to input and save names and ages into a SQLite database. It includes a user interface with input fields and a button to save the data, as well as functionality to display the saved entries. The application creates a database if it doesn't exist and handles user input validation before saving the data.

Uploaded by

pareshloq
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

package com.example.

madcrashcourse;

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

public class MainActivity extends AppCompatActivity {

EditText nameInput, ageInput;


Button saveBtn;
TextView displayText;
SQLiteDatabase db;

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

nameInput = findViewById(R.id.nameInput);
ageInput = findViewById(R.id.ageInput);
saveBtn = findViewById(R.id.saveBtn);
displayText = findViewById(R.id.displayText);

// Create or open database


db = openOrCreateDatabase("MyDB", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS people(name VARCHAR, age INT)");

saveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = nameInput.getText().toString();
String age = ageInput.getText().toString();

if (!name.isEmpty() && !age.isEmpty()) {


db.execSQL("INSERT INTO people VALUES('" + name + "', " + age +
")");
showData();
nameInput.setText("");
ageInput.setText("");
} else {
Toast.makeText(MainActivity.this, "Please enter both name and
age.", Toast.LENGTH_SHORT).show();
}
}
});

showData();
}

void showData() {
Cursor c = db.rawQuery("SELECT * FROM people", null);
StringBuilder sb = new StringBuilder();

while (c.moveToNext()) {
sb.append("Name: ").append(c.getString(0))
.append(", Age: ").append(c.getInt(1)).append("\n");
}

displayText.setText(sb.toString());
c.close();
}
}

You might also like