0% found this document useful (0 votes)
11 views3 pages

Android SQLite Database Example

The document contains an Android layout and Java code for a simple application that allows users to input student names into a SQLite database. It includes an EditText for input, two buttons for submitting and displaying records, and a TextView for showing the stored names. The application creates a database if it doesn't exist and handles user interactions to store and retrieve data.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views3 pages

Android SQLite Database Example

The document contains an Android layout and Java code for a simple application that allows users to input student names into a SQLite database. It includes an EditText for input, two buttons for submitting and displaying records, and a TextView for showing the stored names. The application creates a database if it doesn't exist and handles user interactions to store and retrieve data.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

<?xml version="1.0" encoding="utf-8"?

>
<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<EditText
android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="submit"
app:layout_constraintBottom_toTopOf="@+id/button3"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText2" />

<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="show"
app:layout_constraintBottom_toTopOf="@+id/textView1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText2"
app:layout_constraintVertical_bias="0.778" />

<TextView
android:id="@+id/textView1"
android:layout_width="259dp"
android:layout_height="212dp"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.585"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.911" />

</[Link]>

package [Link].sqlite_insert;
import [Link];
import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends Activity {


SQLiteDatabase Student_database;

@Override
public void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

final EditText eroll = (EditText)findViewById([Link].editText2);

Button bsubmit = (Button)findViewById([Link].button1);

Button bshow_details = (Button)findViewById([Link].button3);


final TextView tvstuddetails =
(TextView)findViewById([Link].textView1);

String s;

[Link](new OnClickListener() {

public void onClick(View arg0) {


Student_database = openOrCreateDatabase("student",
Context.MODE_PRIVATE,null);

//openOrCreateDatabase("student",null);
Student_database.execSQL("CREATE TABLE IF NOT EXISTS
stud(name VARCHAR(20));");
String s, s1;

s1 = [Link]().toString();

Student_database.execSQL("INSERT INTO stud VALUES('" + s1 +


"');");
[Link](getApplicationContext()," Record
successfully Stored",Toast.LENGTH_LONG).show();

Student_database.close();
}
});

bshow_details.setOnClickListener(new OnClickListener() {

public void onClick(View arg0) {

Student_database = openOrCreateDatabase("student",
Context.MODE_PRIVATE,null);
String s6;
int total = 0, n;

Cursor C3=Student_database.rawQuery("select * from


stud;",null);
[Link]();
if(![Link]())
{
do{
s6 = [Link](0);
[Link]("\n" + s6);

}while([Link]());
}

Student_database.close();

}
});

Common questions

Powered by AI

Raw SQL queries provide control and may yield performance benefits in lightweight applications through direct access and manipulation. However, they require meticulous handling to prevent SQL injection and can increase complexity and errors in large codebases due to lack of abstraction. ORM libraries like Room offer a structured, safer interface with compile-time verification and seamless data mapping, optimizing developer productivity and long-term maintenance .

The current implementation uses raw SQL queries for insertion and retrieval, which could be vulnerable to SQL injection if user input is not properly sanitized. Using 'insert', 'query', or 'execSQL' with parameterized statements could provide better security. Additionally, handling data in a more structured way using ContentValues for insertion and moving logic outside of 'onClick' methods could improve maintainability and performance by avoiding repetitive database open/close actions and chunking database operations together .

The MainActivity manages resources by opening the SQLite database within event listeners and closing it promptly after operations, which aligns with Android best practices to avoid resource leaks. Nonetheless, lifecycle-aware components like ViewModel could enhance this management by retaining UI data even across configuration changes, minimizing repeated database access and ultimately enhancing the performance .

Introducing Model-View-ViewModel (MVVM) architecture could decouple UI components from business logic, thus making the code more scalable and maintainable. This involves isolating database operations into a repository and using LiveData or ViewModel to observe changes, reducing MainActivity's complexity. Additionally, employing libraries like Room for database operations can encapsulate raw SQL logic, leaving concise and idiomatic operations .

SQLiteDatabase in this application is the backend structure for storing user data temporarily. It's managed within the MainActivity lifecycle through opening and closing within the onClick methods of buttons. 'openOrCreateDatabase' is used to initialize the database when a button is clicked, and 'execSQL' methods are used for creating tables and inserting data. Finally, 'close()' ensures that resources are released after operations, aligning with the activity's lifecycle and managing resources efficiently .

The TextView is constrained between the parent's top and bottom with 'app:layout_constraintTop_toTopOf="parent"' and 'app:layout_constraintBottom_toBottomOf="parent"'. Also, horizontal bias adjustments ('app:layout_constraintHorizontal_bias="0.585"') create asymmetry and control horizontal placement relative to the center, impacting responsiveness and organizing elements dynamically regardless of screen size .

A user can input text into the EditText field, likely representing a student name. After entering the data, they press the 'submit' button, triggering an insertion of the input into the database while a Toast message confirms the record was stored. Upon pressing the 'show' button, all previously stored entries are fetched and displayed on the TextView, constructing a feedback loop where users can interactively verify their inputs .

The MainActivity follows a monolithic design pattern which interweaves UI and logic in a single class. Methods for UI setup and interaction handling are tightly coupled, which could lead to challenges in scaling or testing individual components. A more modular approach separating UI management (e.g., ViewModel or Controller) from database operations could enhance maintainability and readability. However, the simplicity suits small apps or prototypes .

The ConstraintLayout enables the UI components such as EditText, Button, and TextView to be positioned relative to each other and the parent layout with constraints like 'app:layout_constraintStart_toStartOf="parent"'. The EditText allows user input, which can be submitted using button1. The button3 uses a click listener to display all entries stored in the SQLite database to the TextView. This interaction provides a seamless user experience where data is entered, processed, and displayed without leaving the main activity .

Toast messages in this app provide feedback following data storage actions, informing users of successful entries. This is crucial for confirming actions in applications without visual data display changes. However, they might be overlooked if actions occur rapidly. Using more persistent notifications or UI transitions could improve visibility and user understanding, especially in a larger scale or multi-step app .

You might also like