0% found this document useful (0 votes)
65 views5 pages

Android SQLite SELECT Query Guide

This document provides a step-by-step guide on how to implement a SELECT query in Android SQLite using a simple application. It includes instructions for creating a new project, setting up the layout with EditText and ListView, and writing the necessary Java code for data insertion and retrieval. The application allows users to enter names and salaries, save them to a SQLite database, and refresh the ListView to display the stored data.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views5 pages

Android SQLite SELECT Query Guide

This document provides a step-by-step guide on how to implement a SELECT query in Android SQLite using a simple application. It includes instructions for creating a new project, setting up the layout with EditText and ListView, and writing the necessary Java code for data insertion and retrieval. The application allows users to enter names and salaries, save them to a SQLite database, and refresh the ListView to display the stored data.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

LAB 06

rd
3 ING-SEC-
May 2025

LAB 6: Use SELECT Query in


Android SQLite
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill
This example demonstrate about How to use SELECT Query in Android sqlite.

all required details to create a new project.


Step 2 − Add the following code to res/layout/activity_main.xml.

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


<LinearLayout xmlns:android =
"[Link]
xmlns:tools = "[Link]
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity"
android:orientation = "vertical">
<EditText
android:id = "@+id/name"
android:layout_width = "match_parent"
android:hint = "Enter Name"
android:layout_height = "wrap_content" />
<EditText
android:id = "@+id/salary"
android:layout_width = "match_parent"
android:inputType = "numberDecimal"
android:hint = "Enter Salary"
android:layout_height = "wrap_content" />
<LinearLayout
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"><Button
android:id = "@+id/save"
android:text = "Save"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content" />
<Button
android:id = "@+id/refresh"
android:text = "Refresh"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content" />
<ListView
android:id = "@+id/listView"
android:layout_width = "match_parent"
android:layout_height = "wrap_content">
</ListView>
</LinearLayout>

[Link]
LAB 06
rd
3 ING-SEC-
In the above code, we have taken name and salary as Edit text, when May 2025
user click on save button it will store the data into sqlite data base and
update on listview.

Step 3 − Add the following code to src/[Link]

package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
Button save, refresh;
EditText name, salary;
private ListView listView;
@Override
protected void onCreate(Bundle readdInstanceState) {
[Link](readdInstanceState);
setContentView([Link].activity_main);
final DatabaseHelper helper = new DatabaseHelper(this);
final ArrayList array_list = [Link]();
name = findViewById([Link]);
salary = findViewById([Link]);
listView = findViewById([Link]);
final ArrayAdapter arrayAdapter = new ArrayAdapter([Link],
[Link].simple_list_item_1, array_list);
[Link](arrayAdapter);
findViewById([Link]).setOnClickListener(new
[Link]() {
@Override
public void onClick(View v) {
array_list.clear();
array_list.addAll([Link]());
[Link]();
[Link]();
[Link]();
}
[Link]
LAB 06
rd
3 ING-SEC-
May 2025

findViewById([Link]).setOnClickListener(new [Link]() {
@Override
public void onClick(View v) {
if (![Link]().toString().isEmpty() && ![Link]().toString().isEmpty()) {
if ([Link]([Link]().toString(), [Link]().toString())) {
[Link]([Link], "Inserted", Toast.LENGTH_LONG).show();
} else {
[Link]([Link], "NOT Inserted", Toast.LENGTH_LONG).show();
}
} else {
[Link]("Enter NAME");
[Link]("Enter Salary");
}
}
});
}

Step 4 − Add the following code to src/ [Link]

package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
class DatabaseHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "salaryDatabase3";


public static final String CONTACTS_TABLE_NAME = "SalaryDetails";
public DatabaseHelper(Context context) {
super(context,DATABASE_NAME,null,1);
}

[Link]
LAB 06
rd
3 ING-SEC-
May 2025

@Override
public void onCreate(SQLiteDatabase db) {
try {
[Link](
"create table "+ CONTACTS_TABLE_NAME +"(id INTEGER PRIMARY KEY, name
text,salary text )"
);
} catch (SQLiteException e) {
try {
throw new IOException(e);
} catch (IOException e1) {
[Link]();
}
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
[Link]("DROP TABLE IF EXISTS "+CONTACTS_TABLE_NAME);
onCreate(db);
}
public boolean insert(String s, String s1) {
SQLiteDatabase db = [Link]();
ContentValues contentValues = new ContentValues();
[Link]("name", s);
[Link]("salary", s1);
[Link](CONTACTS_TABLE_NAME, null, contentValues);
return true;
}
public ArrayList getAllCotacts() {
SQLiteDatabase db = [Link]();
ArrayList<String> array_list = new ArrayList<String>();
Cursor res = [Link]( "select * from "+CONTACTS_TABLE_NAME, null );
[Link]();
while([Link]() = = false) {
array_list.add([Link]([Link]("name")));
[Link](); }
return array_list; }}

[Link]
LAB 06
rd
3 ING-SEC-
Step 5 : try to run your application May 2025
your mobile device will display your default screen

Now enter some values in edit text and click on save button

To verify the above result click on refresh button to update list view

[Link]

Common questions

Powered by AI

Upon user interaction, the application defines two major UI actions: 'save' and 'refresh'. The 'save' button triggers a database insert operation if the entered name and salary fields are not empty, utilizing the insert() method from DatabaseHelper to add new records to the SalaryDetails table. Feedback is provided through Toast messages, indicating success or failure of the operation. The 'refresh' button updates the ListView to display the most current data by clearing and repopulating the ArrayList using the getAllContacts() method, followed by notifying the ArrayAdapter of the data change to refresh the user interface .

The application employs an onUpgrade() method within the SQLiteOpenHelper subclass to manage schema changes. This method is triggered during application upgrades when a new version of the database is detected. It includes logic to drop the existing table using the SQL command "DROP TABLE IF EXISTS", followed by a call to onCreate() to rebuild the tables with potentially updated schemas. This method ensures backward compatibility and structural adjustments, allowing the database to accommodate updated application features while preserving the data integrity of pre-existing data structures .

SQLiteOpenHelper's versioning is critical for managing database schema evolution over time. The version number determines whether the onUpgrade() method is invoked to handle schema changes. If the existing database version is older than the current application version, onUpgrade() drops the existing tables and recreates them, accommodating schema alterations without manual data migration. While this maintains consistency across application updates, it risks data loss due to table resets if unsupported by migration strategies. To mitigate this, developers usually implement data preservation techniques or explicit conversion scripts within onUpgrade() to ensure smooth transitions across versions .

The application employs a basic data validation strategy by checking for empty input fields before allowing insertion into the database. Specifically, it verifies that both the name and salary edit texts are not empty, displaying appropriate error messages if they are. This ensures that incomplete data entries are not inserted, which maintains minimum data integrity within the database. However, beyond non-empty checks, no further validations are conducted for data format or type accuracy (e.g., ensuring 'salary' is numeric), indicating a minimalist validation approach which could be enhanced for better robustness .

Potential improvements could include adding input constraints on the EditText fields to restrict salary entries to numerical values using inputType="number", enhancing data integrity directly upon entry. Moreover, introducing progress indicators when performing database operations could improve user experience by providing feedback during potentially longer tasks. Furthermore, implementing data input validation checks for edge cases or data format issues could prevent erroneous data entries. Adding features like swipe-to-refresh on the ListView and visual cues for data updates may also enhance interactivity and provide a more intuitive user interface .

The Cursor plays a crucial role in data retrieval, acting as a pointer that iterates over the result set obtained from a database query. In the application's getAllCotacts() method, a Cursor object executes the raw query to select all entries from the SalaryDetails table. It then iterates through the results, moving row by row to extract data stored under specific column indices like 'name'. The extracted data is then added to an ArrayList, which serves as the data source for the ListView via the ArrayAdapter, ultimately enabling the data's display .

The use of raw SQL queries, as seen in getAllContacts(), poses several limitations. They can lead to SQL injection vulnerabilities if not properly managed, since queries are constructed as plain strings. Raw SQL also lacks type safety, making debugging and refactoring challenging due to potential syntax errors or column mismatches. The approach often results in more complex and less readable code compared to using Android's ContentValues or ORM frameworks such as Room, which provide higher abstraction levels, built-in type safety, and can automatically handle complex object mapping and migrations .

Error handling within the SQLiteOpenHelper subclass is primarily implemented through try-catch blocks around the SQL execution statements. During database creation in the onCreate() method, any SQLiteException thrown is caught, and an IOException is thrown instead, albeit it is only printed via stack trace in this implementation. This allows the operation to report exceptions that may arise during database schema creation, thereby aiding debugging and ensuring that the cause of errors is traceable. No specific rollback or user notification strategy is evident, suggesting a basic level of error handling reliance on log output .

The integration facilitates data display by connecting the ListView component to an ArrayAdapter, which acts as a bridge between the ListView and the ArrayList containing data from the SQLite database. Upon user interaction, such as clicking the refresh button, the ArrayList is updated with the latest data retrieved from the database using the helper method getAllContacts(). The ArrayAdapter then updates the ListView to reflect the current state of data dynamically, enabling real-time display of data changes in the user interface .

The main steps for setting up an SQLite database in an Android application include creating a new project in Android Studio and defining the user interface in the layout XML file. The DatabaseHelper Java class is then implemented to define the database schema, which includes specifying the database name and developing the schema creation logic in the onCreate() and onUpgrade() methods. The schema creation involves executing SQL commands to create tables with the necessary columns, such as 'name' and 'salary', for storing data .

You might also like