KEMBAR78
Step by Step Android Projects | PDF | Android (Operating System) | Java (Programming Language)
0% found this document useful (0 votes)
3 views54 pages

Step by Step Android Projects

Uploaded by

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

Step by Step Android Projects

Uploaded by

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

Step-by-Step Guide: Creating a Login Page in Android Studio

A Beginner’s Guide

Introduction

• What You Will Learn:

• Setting up Android Studio


• Creating a new project
• Designing a login interface
• Adding functionality to the login page

Setting Up Android Studio

• Step 1: Install Android Studio from developer.android.com.

• Select I have read and agree with the above terms and conditions. Then click to download
Android Studio.
• When opening Android Studio for the first time, AS will run the Android Studio Setup
Wizard.
Generally, keep Next and finally click Finish.
Next, the data will be downloaded from the network, please wait a moment.

If you have a good internet connection, it will be downloaded quickly.

Click Finish to complete the SDK installation.


• Step 2: Create A Demo Project and Run

• Step 3: Click New Project and choose the simplest traditional layout Empty Views
Activity.
• Step 3: Fill in the project details:
o Name: LoginApp
o Language: Java
o Minimum SDK: Leave the default

Then the source code will be opened and displayed. We wait for gradle to be downloaded and the
Android project to be loaded.

This step of Sync may take a long time, so please wait a moment.
After Sync is completed, click Run app to run it in the Emulator.

Android SDK Manager

If you need to manage Android SDK, such as installing new SDK Platforms and SDK Tools, you
can configure it by opening Settings -> Languages & Frameworks -> Android SDK.
Click OK to download tools

Setting Up the Layout

• Step 1: Open activity_main.xml.


• Step 2: Add components for the login screen:
o EditTexts for username and password.
o Button for login.
• Step 3: Arrange components using a LinearLayout or RelativeLayout.
XML Code for Layout

Sample Code:
Screenshot: Code Editor with XML layout

Adding Functionality

• Step 1: Open MainActivity.java or MainActivity.kt.


• Step 2: Write code to handle button clicks:
o Retrieve input from username and password fields.
o Validate inputs.
• Step 3: Display a message (Toast) for successful or unsuccessful login.
o Screenshot: Code Editor with event handling code.

Sample Code for Functionality

Java Code:

package com.gasco.gee.example.simplelogin;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private EditText editTextUsername, editTextPassword;


private Button btnLogin;

// Hardcoded credentials for demonstration


private final String validUsername = "admin";
private final String validPassword = "password123";

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

// Bind views
editTextUsername = findViewById(R.id.editTextTextEmailAddress);
editTextPassword = findViewById(R.id.editTextTextPassword);
btnLogin = findViewById(R.id.btnLogin);

// Set login button click listener


btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String enteredUsername = editTextUsername.getText().toString().trim();
String enteredPassword = editTextPassword.getText().toString().trim();

// Validate login
if (enteredUsername.isEmpty() || enteredPassword.isEmpty()) {
Toast.makeText(MainActivity.this, "Please enter both username and password.",
Toast.LENGTH_SHORT).show();
} else if (enteredUsername.equals(validUsername) && enteredPassword.equals(validPassword))
{
Toast.makeText(MainActivity.this, "Login Successful!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Invalid username or password.",
Toast.LENGTH_SHORT).show();
}
}
});
}
}

Testing Your App

• Step 1: Run your app by clicking the "Run" button.


Step-by-Step Guide: Creating a Simple Calculator in Android Studio

Introduction

• What You Will Learn:

• Designing a calculator layout


• Implementing basic arithmetic operations
• Testing the calculator app

Creating a New Project

• Step 1: Click on "New Project."

• Step 2: Choose "Empty View Activity" and click "Next."


• Step 3: Fill in the project details:
o Name: CalculatorApp
o Language: Java
o Minimum SDK: Leave the default

Click on Finish
Designing the Layout

• Step 1: Open activity_main.xml.


• Step 2: Add components:
o EditText for displaying the result.
o Two EditText For input of numbers
o Button for calculating the results
• Step 3: Use a LinearLayout for better arrangement of buttons.

XML Code for Layout

Sample Code:

<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/edtNumber1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter first number"
android:inputType="numberDecimal" />

<EditText
android:id="@+id/edtNumber2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter second number"
android:inputType="numberDecimal" />

<Button
android:id="@+id/btnCalculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Add Numbers" />

<EditText
android:id="@+id/edtResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Result"
android:inputType="none"
android:focusable="false" />
</LinearLayout>

Screenshot: Code Editor with XML layout.

Adding Functionality

• Step 1: Open MainActivity.java or MainActivity.kt.


• Step 2: Add click listeners for buttons.
o Retrieve input and store numbers and operations.
• Step 3: Perform arithmetic calculations on pressing "=".
Sample Code for Functionality

Java Code:

package com.example.additioncalculator;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

EditText edtNumber1, edtNumber2, edtResult;


Button btnCalculate;

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

// Initialize views
edtNumber1 = findViewById(R.id.edtNumber1);
edtNumber2 = findViewById(R.id.edtNumber2);
edtResult = findViewById(R.id.edtResult);
btnCalculate = findViewById(R.id.btnCalculate);

// Set onClick listener for button


btnCalculate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Get numbers from input fields
String num1Text = edtNumber1.getText().toString().trim();
String num2Text = edtNumber2.getText().toString().trim();

// Validate inputs
if (num1Text.isEmpty() || num2Text.isEmpty()) {
Toast.makeText(MainActivity.this, "Please enter both numbers",
Toast.LENGTH_SHORT).show();
return;
}

try {
// Perform addition
double num1 = Double.parseDouble(num1Text);
double num2 = Double.parseDouble(num2Text);
double result = num1 + num2;

// Display result
edtResult.setText(String.valueOf(result));
} catch (NumberFormatException e) {
Toast.makeText(MainActivity.this, "Invalid input", Toast.LENGTH_SHORT).show();
}
}
});
}
}

Screenshot: Full code in the editor.

Testing the Calculator

• Step 1: Run the app on an emulator or connected device.


o Screenshot: Calculator UI on a device.
• Step 2: Test various inputs and operations.
o Screenshot: Example calculations.
Step-by-Step Guide: Creating a Simple Star Rating App in Android Studio

Introduction

• What You Will Learn:

• Setting up Android Studio


• Designing a star rating interface
• Implementing functionality to capture user feedback
• Testing the app

Creating a New Project

• Step 1: Click "New Project."

• Step 2: Choose "Empty View Activity" and click "Next."


• Step 3: Fill in project details:
o Name: StarRatingApp
o Language: Java
o Minimum SDK: Leave default
Designing the Layout

• Step 1: Open activity_main.xml.


• Step 2: Add components:
o RatingBar for the stars.
o TextView to display user feedback.
o Optional: A Button to submit feedback.
• Step 3: Arrange components using LinearLayout or RelativeLayout.

XML Code for Layout

Sample Code:
Screenshot: Code Editor with XML layout.

Adding Functionality

• Step 1: Open MainActivity.java or MainActivity.kt.


• Step 2: Write code to handle RatingBar value changes and button click.
• Step 3: Display user-selected rating in a Toast or update TextView.
o Screenshot: Code Editor with event handling code.

Sample Code for Functionality

Java Code:
Screenshot: Full code in the editor.

Testing the App

• Step 1: Run the app on an emulator or connected device.


o Screenshot: Star Rating UI on a device.
• Step 2: Test by selecting ratings and submitting feedback.
o Screenshot: Rating and feedback in action.
Step-by-Step Guide: Creating a Simple ListView App in Android Studio

Introduction

• What You Will Learn:


o Setting up Android Studio
o Designing a layout with a ListView
o Populating the ListView with data
o Adding functionality to handle item clicks

Creating a New Project

• Step 1: Click "New Project."


o Screenshot: New Project Wizard.
• Step 2: Choose "Empty Activity" and click "Next."
o Screenshot: Activity Selection.
• Step 3: Fill in project details:
o Name: ListViewApp
o Language: Java or Kotlin
o Minimum SDK: API 21 (Lollipop)
o Screenshot: Project Configuration Screen.

Designing the Layout

• Step 1: Open activity_main.xml.


• Step 2: Add a ListView component.

Example XML Code:

Screenshot: Layout Editor showing the ListView.

Populating the ListView

• Step 1: Open MainActivity.java or MainActivity.kt.


• Step 2: Create an array of strings to display in the ListView.
• Step 3: Use an ArrayAdapter to bind the data to the ListView.
o Example Java Code:
Screenshot: Code Editor with the ArrayAdapter setup.

Adding Item Click Functionality

• Step 1: Add an OnItemClickListener to the ListView.

• Example Java Code:

Screenshot: Code Editor showing the click listener.

Testing the App

• Step 1: Run the app on an emulator or connected device.


o Screenshot: ListView displayed on the device.
• Step 2: Tap on items and observe the feedback (Toast message).
o Screenshot: Toast message after clicking an item.
Step-by-Step Guide: Building a Grading System in Android Studio
Create a New Project
• Open Android Studio and click "New Project".

• Select Empty View Activity and click Next.


• Fill in the project details:

• Name: GradingSystem
• Language: Java
• Minimum SDK: Leave default.

• Click Finish to create the project.

Design the Layout


• Open activity_main.xml.
• Replace the existing XML with the following code to design the grading system layout:

<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">

<!-- Input field for total mark -->


<EditText
android:id="@+id/edtTotalMark"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Total Mark"
android:inputType="number"
android:layout_marginBottom="16dp" />

<!-- Button to calculate grade -->


<Button
android:id="@+id/btnCalculateGrade"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Get Grade"
android:layout_marginBottom="16dp" />

<!-- TextView to display the grade -->


<TextView
android:id="@+id/tvGrade"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Grade will be displayed here"
android:textSize="18sp"
android:textColor="@android:color/black"
android:gravity="center"
android:layout_marginTop="16dp" />
</LinearLayout>

Add Java Code to Calculate Grade


• Open MainActivity.java.
• Add the following code to perform the grading logic:

package com.example.gradingsystem;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

EditText edtTotalMark;
Button btnCalculateGrade;
TextView tvGrade;

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

// Initialize views
edtTotalMark = findViewById(R.id.edtTotalMark);
btnCalculateGrade = findViewById(R.id.btnCalculateGrade);
tvGrade = findViewById(R.id.tvGrade);

// Set onClick listener for the button


btnCalculateGrade.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Get input from the EditText
String markInput = edtTotalMark.getText().toString().trim();

if (markInput.isEmpty()) {
Toast.makeText(MainActivity.this, "Please enter a total mark",
Toast.LENGTH_SHORT).show();
return;
}
try {
// Convert input to integer
int totalMark = Integer.parseInt(markInput);

// Determine grade
String grade;
if (totalMark >= 90) {
grade = "A";
} else if (totalMark >= 80) {
grade = "B";
} else if (totalMark >= 70) {
grade = "C";
} else if (totalMark >= 60) {
grade = "D";
} else {
grade = "F";
}

// Display grade
tvGrade.setText("Grade: " + grade);

} catch (NumberFormatException e) {
Toast.makeText(MainActivity.this, "Invalid input", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Test the App
• Run the app on an emulator or physical device.

• Enter a total mark (e.g., 85) in the input field.


• Click the "Get Grade" button.
• The grade will be displayed in the TextView (e.g., "Grade: B").
Step-by-Step Guide: Navigating Between Activities

Introduction

• What You Will Learn:

• Setting up SQLite in Android Studio


• Creating two activities
• Navigating Between the Activities

Creating a New Project

• Step 1: Click "New Project."

• Step 2: Choose "Empty View Activity" and click "Next."


• Step 3: Fill in project details:
o Name: SQLiteFormApp
o Language: Java or Kotlin
o Minimum SDK: API 21 (Lollipop)

Designing the Form Layout

• Step 1: Open activity_main.xml.


• Step 2: Add input fields (e.g., EditText) for data entry and a button to submit.
XML Codes for Page 1

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Page 1"
android:textSize="32sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<ImageButton
android:id="@+id/imageButton"
android:layout_width="match_parent"
android:layout_height="231dp"
app:srcCompat="@drawable/facebook" />

</LinearLayout>

JAVA Codes for Page 1

package com.gasco.gee.example.page1;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

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

img = findViewById(R.id.imageButton);
img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, Page2.class);
startActivity(i);
}
});
}
}

XML Codes for Page 2


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".Page2">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Page 2"
android:textSize="32sp"
android:textStyle="bold"
tools:layout_editor_absoluteX="165dp"
tools:layout_editor_absoluteY="292dp" />

<ImageView
android:id="@+id/imageView2"
android:layout_width="match_parent"
android:layout_height="125dp"
app:srcCompat="@drawable/back" />
</LinearLayout>
JAVA Codes for Page 2

package com.gasco.gee.example.page1;

import androidx.appcompat.app.AppCompatActivity;

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

public class Page2 extends AppCompatActivity {

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

img = findViewById(R.id.imageView2);
img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(Page2.this, MainActivity.class);
startActivity(i);
}
});
}
}

Testing the App

• Step 1: Run the app on an emulator or device.


Step-by-Step Guide: Creating a Simple Form with SQLite Database in Android
Studio

Introduction

• What You Will Learn:

• Setting up SQLite in Android Studio


• Creating a form to input data
• Saving data to an SQLite database
• Displaying, editing, and deleting data on another page

Creating a New Project

• Step 1: Click "New Project."

• Step 2: Choose "Empty View Activity" and click "Next."


• Step 3: Fill in project details:
o Name: SQLiteFormApp
o Language: Java or Kotlin
o Minimum SDK: API 21 (Lollipop)

Designing the Form Layout

• Step 1: Open activity_main.xml.


• Step 2: Add input fields (e.g., EditText) for data entry and a button to submit.
Example XML Code:

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
android:orientation="vertical"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="SQLLite Database Form"
android:textSize="24sp" />

<EditText
android:id="@+id/edtName"
android:layout_width="match_parent"
android:layout_height="41dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="NAME"
android:inputType="text" />

<EditText
android:id="@+id/edtAge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="AGE"
android:layout_marginTop="10dp"
android:inputType="numberDecimal" />

<EditText
android:id="@+id/edtPhoneNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:layout_marginTop="10dp"
android:hint="Phone Number"
android:inputType="phone" />

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

<Button
android:id="@+id/btnSubmit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center_horizontal"
android:text="Submit Data" />

<Button
android:id="@+id/btnViewData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="View All Saved Data" />

</LinearLayout>

Setting Up SQLite Database

• Step 1: Create a new class DatabaseHelper.java.


• Step 2: Extend SQLiteOpenHelper and override necessary methods.
o Example Java Code:

• package com.gasco.gee.example.sqliteformapp;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

public class DatabaseHelper extends SQLiteOpenHelper {


private static final String DATABASE_NAME = "user_data.db";
private static final int DATABASE_VERSION = 1;
public DatabaseHelper(@Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE users (id INTEGER PRIMARY
KEY AUTOINCREMENT, name TEXT, age INTEGER, phone_number TEXT, gender
TEXT)";
db.execSQL(createTable);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
db.execSQL("DROP TABLE IF EXISTS users");
onCreate(db);
}
}

Saving Data to SQLite

• Step 1: Add logic to MainActivity.java to save data.

• Example Java Code:


• package com.gasco.gee.example.sqliteformapp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


Spinner genderSpinner;
EditText edtName, edtAge, edtPhone;
Button btnSubmit, btnViewAll;
DatabaseHelper dbHelper = new DatabaseHelper(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Initialize Views
edtName = (EditText) findViewById(R.id.edtName);
edtAge = (EditText) findViewById(R.id.edtAge);
edtPhone = (EditText) findViewById(R.id.edtPhoneNumber);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnViewAll = (Button) findViewById(R.id.btnViewData);
genderSpinner = findViewById(R.id.spinnerGender);

// Populate Spinner
String[] genderOptions = {"Select Gender", "Male", "Female",
"Other"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_spinner_item, genderOptions);

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdow
n_item);
genderSpinner.setAdapter(adapter);

btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Get input data
String name = edtName.getText().toString();
String ageText = edtAge.getText().toString();
String phone = edtPhone.getText().toString();
String gender =
genderSpinner.getSelectedItem().toString();

// Validate input data


if (name.isEmpty() || ageText.isEmpty() ||
phone.isEmpty()) {
Toast.makeText(MainActivity.this, "Please fill all
fields", Toast.LENGTH_SHORT).show();
return;
}

int age = Integer.parseInt(ageText);

// Save data to SQLite database


SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", name);
values.put("age", age);
values.put("phone_number", phone);
values.put("gender", gender);

long rowId = db.insert("users", null, values);


if (rowId != -1) {
Toast.makeText(MainActivity.this, "Data Saved
Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Error Saving
Data", Toast.LENGTH_SHORT).show();
}
}
});

btnViewAll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new
Intent(MainActivity.this,ShowDataActivity.class);
startActivity(i);
}
});
}
}

Screenshot: Code Editor with save logic.


Displaying Data on Another Page

Layout Design

XML Codes

• Step 1: Create a new activity DisplayActivity.java and its layout.

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ShowDataActivity">

<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>

• Step 2: Use a ListView to display data.


o Example Java Code for fetching data:
• package com.gasco.gee.example.sqliteformapp;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class ShowDataActivity extends AppCompatActivity {

ListView listView;
DatabaseHelper dbHelper = new DatabaseHelper(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_data);
listView = findViewById(R.id.listview);

// Fetch and display data


displayData();
}

private void displayData() {


SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.query("users", null, null, null, null, null,
null);

ArrayList<String> dataList = new ArrayList<>();


final ArrayList<Integer> userIds = new ArrayList<>(); // To
keep track of IDs for deletion
while (cursor.moveToNext()) {
@SuppressLint("Range") int id =
cursor.getInt(cursor.getColumnIndex("id"));
@SuppressLint("Range") String name =
cursor.getString(cursor.getColumnIndex("name"));
@SuppressLint("Range") int age =
cursor.getInt(cursor.getColumnIndex("age"));
@SuppressLint("Range") String phone =
cursor.getString(cursor.getColumnIndex("phone_number"));
@SuppressLint("Range") String gender =
cursor.getString(cursor.getColumnIndex("gender"));

// Add data to list


dataList.add("ID: " + id + "\nName: " + name + "\nAge: " +
age +
"\nPhone: " + phone + "\nGender: " + gender);
userIds.add(id); // Store the corresponding ID
}
cursor.close();

// Bind data to ListView


ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, dataList);
listView.setAdapter(adapter);

// Set item double-click listener


listView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
private long lastClickTime = 0;
private static final long DOUBLE_CLICK_THRESHOLD = 300; //
Time in milliseconds

@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
long clickTime = System.currentTimeMillis();
if (clickTime - lastClickTime < DOUBLE_CLICK_THRESHOLD)
{
// Double-click detected
int userId = userIds.get(position); // Get the ID
of the selected user
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.delete("users", "id=?", new
String[]{String.valueOf(userId)});
Toast.makeText(ShowDataActivity.this, "User
deleted", Toast.LENGTH_SHORT).show();

// Remove item from the list and update the adapter


dataList.remove(position);
userIds.remove(position); // Keep IDs in sync
adapter.notifyDataSetChanged();
} else {
// Single-click detected (delayed to ensure no
second click is incoming)
new android.os.Handler().postDelayed(() -> {
if (System.currentTimeMillis() - lastClickTime
>= DOUBLE_CLICK_THRESHOLD) {
int userId = userIds.get(position); // Get
the ID of the selected user
Intent i = new
Intent(ShowDataActivity.this, MainActivity3.class);
i.putExtra("id", userId);
startActivity(i);
}
}, DOUBLE_CLICK_THRESHOLD);
}

lastClickTime = clickTime;
}
});
}
}

Screenshot: Displaying fetched data.

XML Codes For Data Update

Step 1: Create a new activity MainActivity3.java and its layout.

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_margin="20dp"
tools:context=".MainActivity3">

<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="10dp"
android:gravity="center"
android:textStyle="bold"
android:text="SQLITE DATABASE FORM"
android:textSize="24sp" />

<EditText
android:id="@+id/edtName2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="10dp"
android:ems="10"
android:gravity="center"
android:hint="NAME"
android:inputType="text"
android:textSize="24sp" />

<EditText
android:id="@+id/edtAge2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="10dp"
android:ems="10"
android:gravity="center"
android:hint="ENTER YOUR AGE"
android:inputType="number" />

<EditText
android:id="@+id/edtPhoneNumber2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="3dp"
android:layout_marginBottom="10dp"
android:ems="10"
android:gravity="center"
android:hint="PHONE NUMBER"
android:inputType="text" />

<Spinner
android:id="@+id/spinnerGender2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="-3dp"
android:layout_marginBottom="10dp" />

<Button
android:id="@+id/btnUpdate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_marginBottom="10dp"
android:gravity="center"
android:text="UPDATE DATA" />

<Button
android:id="@+id/btnViewData2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_marginBottom="10dp"
android:text="VIEW ALL DATA" />

</LinearLayout>

JAVA Codes For Data Update

package com.gasco.gee.example.sqliteformapp;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity3 extends AppCompatActivity {

//Variable declaration
Spinner genderSpinner;
EditText edtName, edtAge, edtPhone;
Button btnUpdate, btnViewAll;
DatabaseHelper dbHelper = new DatabaseHelper(this);

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

// Retrieve the Intent data within onCreate


Intent i = getIntent();
int cid = i.getIntExtra("id", -1); // Get the 'id' passed via the intent

// Initialize Views
edtName = (EditText) findViewById(R.id.edtName2);
edtAge = (EditText) findViewById(R.id.edtAge2);
edtPhone = (EditText) findViewById(R.id.edtPhoneNumber2);
btnUpdate = (Button) findViewById(R.id.btnUpdate);
btnViewAll = (Button) findViewById(R.id.btnViewData2);
genderSpinner = findViewById(R.id.spinnerGender2);

//Function to display all saved data


displayData(cid);

//Update button click listener


btnUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
updateData(cid);
}
});

//ViewAll button click listener


btnViewAll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity3.this, ShowDataActivity.class);
startActivity(intent);
}
});
}

//Display Data Function


private void displayData(int cid) {

SQLiteDatabase db = dbHelper.getReadableDatabase();
String selection = "id = ?";
String[] selectionArgs = {String.valueOf(cid)};
Cursor cursor = db.query("users", null, selection, selectionArgs, null, null, null);

//Looping through database to get the data


if (cursor != null && cursor.moveToFirst()) {
@SuppressLint("Range") int id = cursor.getInt(cursor.getColumnIndex("id"));
@SuppressLint("Range") String name =
cursor.getString(cursor.getColumnIndex("name"));
@SuppressLint("Range") int age = cursor.getInt(cursor.getColumnIndex("age"));
@SuppressLint("Range") String phone =
cursor.getString(cursor.getColumnIndex("phone_number"));
@SuppressLint("Range") String gender =
cursor.getString(cursor.getColumnIndex("gender"));

// Set the retrieved data into the corresponding views


edtName.setText(name);
edtAge.setText(String.valueOf(age)); // Convert 'int' to 'String' for EditText
edtPhone.setText(phone);
// Set the gender in the Spinner
setGenderSpinner(gender);

cursor.close(); // Close the cursor


} else {
// Handle the case where no data was found (optional)
Toast.makeText(MainActivity3.this, "No data found for the given ID",
Toast.LENGTH_SHORT).show();
}

//Function to populate the Spinner with data options for selection


private void setGenderSpinner(String gender) {
// Define gender options
String[] genderOptions = {"Select Gender","Male", "Female", "Other"};

// Create an ArrayAdapter for the spinner


ArrayAdapter<String> genderAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_spinner_item, genderOptions);

genderAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

// Set the adapter to the spinner


genderSpinner.setAdapter(genderAdapter);

// Find the position of the gender in the spinner's options list


int genderPosition = -1;
for (int i = 0; i < genderOptions.length; i++) {
if (genderOptions[i].equalsIgnoreCase(gender)) {
genderPosition = i;
break;
}
}

// Set the spinner selection based on the gender position found


if (genderPosition != -1) {
genderSpinner.setSelection(genderPosition);
} else {
// Optionally handle cases where the gender doesn't match any known value
genderSpinner.setSelection(0); // Default to "Male" if not found
}
}

//Function to update the data after changes is made


private void updateData(int cid) {
// Get the data entered by the user
String name = edtName.getText().toString();
String ageString = edtAge.getText().toString();
String phone = edtPhone.getText().toString();
String gender = genderSpinner.getSelectedItem().toString();

// Validate input
if (name.isEmpty() || ageString.isEmpty() || phone.isEmpty()) {
Toast.makeText(this, "Please fill in all fields", Toast.LENGTH_SHORT).show();
return;
}

// Convert age from String to int


int age = Integer.parseInt(ageString);

// Get writable database for updating


SQLiteDatabase db = dbHelper.getWritableDatabase();

// Prepare the values to be updated


ContentValues values = new ContentValues();
values.put("name", name);
values.put("age", age);
values.put("phone_number", phone);
values.put("gender", gender);

// Perform the update


String whereClause = "id = ?";
String[] whereArgs = {String.valueOf(cid)};
int rowsUpdated = db.update("users", values, whereClause, whereArgs);

// Check if the update was successful


if (rowsUpdated > 0) {
Toast.makeText(this, "Data updated successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Failed to update data", Toast.LENGTH_SHORT).show();
}

// Close the database


db.close();
}
}

Testing the App

• Step 1: Run the app on an emulator or device.

• Step 2: Test saving, displaying, editing, and deleting data.


o Screenshot: Data list with actions.

You might also like