KEMBAR78
BCA Android Notes U7 | PDF | Android (Operating System) | Boolean Data Type
0% found this document useful (0 votes)
63 views20 pages

BCA Android Notes U7

This document discusses data storage in Android, including: 1. It covers internal and external storage in Android, as well as creating and working with SQLite databases. 2. It then discusses creating an Android application that allows writing text to a file, saving it to internal or external storage, clearing the text, removing the file, and fetching text from the file. 3. Code examples are provided for the Android manifest file, layout XML, and Java code to implement reading from and writing to internal and external storage files.

Uploaded by

Jadoo Singh
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)
63 views20 pages

BCA Android Notes U7

This document discusses data storage in Android, including: 1. It covers internal and external storage in Android, as well as creating and working with SQLite databases. 2. It then discusses creating an Android application that allows writing text to a file, saving it to internal or external storage, clearing the text, removing the file, and fetching text from the file. 3. Code examples are provided for the Android manifest file, layout XML, and Java code to implement reading from and writing to internal and external storage files.

Uploaded by

Jadoo Singh
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/ 20

Unit 7: Data Storage and Introduction to

SQLite
1. File system in android

2. Internal and External storage

3. Creating SQLite Database

4. Editing Tasks with SQLite

5. Cursors and Content Values

6. Working with Android Database

7. Publish Android Application in Android Market


Android I/O :

Refer Universe PDF file CMP516Android Programming.pdf


activity_main.xml
<?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:padding="24dp"
tools:context=".MainActivity">

<TextView
android:id="@+id/tvFilenameLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="File name" />

<TextView
android:id="@+id/tvFilenameValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="SomeFilename.txt"
android:textSize="30sp" />

<com.google.android.material.textfield.TextInputLayout
android:id="@+id/tilMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp">

<com.google.android.material.textfield.TextInputEditText
android:id="@+id/etMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Write your message here."
android:maxLines="5"
android:minLines="3"
android:text="" />
</com.google.android.material.textfield.TextInputLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:orientation="horizontal">

<Button
android:id="@+id/btnSaveInFile"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="12dp"
android:layout_weight="1"
android:backgroundTint="#3cba54"
android:text="Save in File" />

<Button
android:id="@+id/btnClearText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="12dp"
android:layout_weight="1"
android:backgroundTint="#f4c20d"
android:text="Clear Text" />

</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:orientation="horizontal">

<Button
android:id="@+id/btnRemoveFile"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="12dp"
android:layout_weight="1"
android:backgroundTint="#db3236"
android:text="Remove File" />

<Button
android:id="@+id/btnFetchTextFromFile"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="12dp"
android:layout_weight="1"
android:backgroundTint="#4885ed"
android:text="Fetch from file" />

</LinearLayout>

<TextView
android:id="@+id/tvOutputLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="Output from file : " />

<TextView
android:id="@+id/tvFileMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:background="#eee"
android:padding="16dp"
android:textColor="#000" />

</LinearLayout>
Internal File IO
MainActivity.java
package com.ndroid.sampleexample;

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;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class MainActivity extends AppCompatActivity {

TextView tvFilenameValue;
EditText etMessage;
Button btnSaveInFile;
Button btnClearText;
Button btnRemoveFile;
Button btnFetchTextFromFile;
TextView tvFileMessage;

private final String FILENAME = "world.txt";

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

registerUi();
populateView();
addListeners();
}

private void registerUi() {


tvFilenameValue = findViewById(R.id.tvFilenameValue);
etMessage = findViewById(R.id.etMessage);
btnSaveInFile = findViewById(R.id.btnSaveInFile);
btnClearText = findViewById(R.id.btnClearText);
btnRemoveFile = findViewById(R.id.btnRemoveFile);
btnFetchTextFromFile = findViewById(R.id.btnFetchTextFromFile);
tvFileMessage = findViewById(R.id.tvFileMessage);
}

private void populateView() {


tvFilenameValue.setText(FILENAME);
}

private void addListeners() {


btnSaveInFile.setOnClickListener(view -> {
String strMsg = etMessage.getText().toString();
saveData(FILENAME, strMsg);
});

btnClearText.setOnClickListener(view -> {
etMessage.setText("");
});

btnRemoveFile.setOnClickListener(view -> {
//..
});

btnFetchTextFromFile.setOnClickListener(view -> {
String strMsg = fetchData(FILENAME);
tvFileMessage.setText(strMsg);
});
}

void saveData(String strFilename, String strData) {


try {
FileOutputStream fos = openFileOutput(strFilename, MODE_PRIVATE);
fos.write(strData.getBytes());
fos.flush();
fos.close();
toast("Text Saved to file");
} catch (IOException e) {
e.printStackTrace();
}
}

private String fetchData(String strFilename) {


try {
FileInputStream fis = openFileInput(strFilename);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);

String temp;
StringBuilder sbData = new StringBuilder();

while ((temp = br.readLine()) != null) {


sbData.append(temp);
sbData.append("\n");
}

fis.close();
return sbData.toString();
} catch (IOException e) {
e.printStackTrace();
return "";
}
}

private void toast(String msg) {


Toast.makeText(getApplicationContext(), msg,
Toast.LENGTH_LONG).show();
}
}
External File IO
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ndroid.sampleexample">

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:requestLegacyExternalStorage="true"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.SampleExample">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>

</manifest>

MainActivity.java
package com.ndroid.sampleexample;

import androidx.appcompat.app.AppCompatActivity;

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

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class MainActivity extends AppCompatActivity {

TextView tvFilenameValue;
EditText etMessage;
Button btnSaveInFile;
Button btnClearText;
Button btnRemoveFile;
Button btnFetchTextFromFile;
TextView tvFileMessage;

private final String FOLDER_NAME = "AndroidFileIoSession";


private final String FILENAME = "world.txt";
private File fWorld;

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

registerUi();
createFileAndDirectory();
populateView();
addListeners();
}

private void registerUi() {


tvFilenameValue = findViewById(R.id.tvFilenameValue);
etMessage = findViewById(R.id.etMessage);
btnSaveInFile = findViewById(R.id.btnSaveInFile);
btnClearText = findViewById(R.id.btnClearText);
btnRemoveFile = findViewById(R.id.btnRemoveFile);
btnFetchTextFromFile = findViewById(R.id.btnFetchTextFromFile);
tvFileMessage = findViewById(R.id.tvFileMessage);
}
private void createFileAndDirectory() {
try {
File root = Environment.getExternalStorageDirectory();
File fDir = new File(root, FOLDER_NAME);
if (!fDir.exists())
fDir.mkdir();

fWorld = new File(fDir, FILENAME);


if (!fWorld.exists())
fWorld.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}

private void populateView() {


tvFilenameValue.setText(FILENAME);
}

private void addListeners() {


btnSaveInFile.setOnClickListener(view -> {
String strMsg = etMessage.getText().toString();
saveData(fWorld, strMsg);
});

btnClearText.setOnClickListener(view -> {
etMessage.setText("");
});

btnRemoveFile.setOnClickListener(view -> {
fWorld.delete();
toast("File got delete successfully");
});

btnFetchTextFromFile.setOnClickListener(view -> {
String strMsg = fetchData(FILENAME);
tvFileMessage.setText(strMsg);
});
}

void saveData(File fWorld, String strData) {


try {
if (!fWorld.exists())
createFileAndDirectory();
//FileOutputStream fos = openFileOutput(strFilename,
MODE_PRIVATE);
FileOutputStream fos = new FileOutputStream(fWorld);
fos.write(strData.getBytes());
fos.flush();
fos.close();
toast("Text Saved to file");
} catch (IOException e) {
e.printStackTrace();
}
}

private String fetchData(String strFilename) {


try {
//FileInputStream fis = openFileInput(strFilename);
FileInputStream fis = new FileInputStream(fWorld);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);

String temp;
StringBuilder sbData = new StringBuilder();

while ((temp = br.readLine()) != null) {


sbData.append(temp);
sbData.append("\n");
}

fis.close();
return sbData.toString();
} catch (IOException e) {
e.printStackTrace();
return "";
}
}

private void toast(String msg) {


Toast.makeText(getApplicationContext(), msg,
Toast.LENGTH_LONG).show();
}
}
SQLite
Refer Universe PDF file CMP516Android Programming.pdf
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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="24dp">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Student Details" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="Enter Roll No:" />

<EditText
android:id="@+id/etRollno"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Name:" />

<EditText
android:id="@+id/etName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Marks:" />

<EditText
android:id="@+id/etMarks"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number" />

<Button
android:id="@+id/btnInsert"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClickInsert"
android:text="Insert" />

<Button
android:id="@+id/btnDelete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClickDelete"
android:text="Delete" />

<Button
android:id="@+id/Update"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClickUpdate"
android:text="Update" />

<Button
android:id="@+id/btnView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClickView"
android:text="View" />

<Button
android:id="@+id/btnViewAll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClickViewAll"
android:text="View All" />

</LinearLayout>
MainActivity.java
package com.hinduja.tybcapracsql;

import android.app.AlertDialog;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {


EditText etRollNo, etName, etMarks;
SQLiteDatabase sqlDb;

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

registerUi();

// Creating database and table


sqlDb = openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null);
sqlDb.execSQL("CREATE TABLE IF NOT EXISTS student(rollno VARCHAR,name
VARCHAR,marks VARCHAR);");
}

private void registerUi() {


etRollNo = findViewById(R.id.etRollno);
etName = findViewById(R.id.etName);
etMarks = findViewById(R.id.etMarks);
}

private boolean hasValidFields() {


if (etRollNo.getText().toString().trim().length() == 0 ||
etName.getText().toString().trim().length() == 0 ||
etMarks.getText().toString().trim().length() == 0) {
showMessage("Error", "Please enter all field properly.");
return false;
}
return true;
}

private boolean isValidRollNo() {


if (etRollNo.getText().toString().trim().length() == 0) {
showMessage("Error", "Please enter Roll No.");
return false;
}
return true;
}

public void onClickInsert(View v) {


if (!hasValidFields()) return;
String insertQuery = "INSERT INTO student VALUES('" +
etRollNo.getText() + "','"
+ etName.getText() + "','" +
etMarks.getText() + "');";

log(insertQuery);
sqlDb.execSQL(insertQuery);
showMessage("Success", "Record added.");
clearText();
}

public void onClickDelete(View v) {


if (!isValidRollNo()) return;
Cursor c = sqlDb.rawQuery("SELECT * FROM student WHERE rollno='" +
etRollNo.getText() + "'", null);
if (c.moveToFirst()) {
sqlDb.execSQL("DELETE FROM student WHERE rollno='" +
etRollNo.getText() + "'");
showMessage("Success", "Record Deleted.");
} else {
showMessage("Error", "Invalid Roll No");
}
clearText();
}

public void onClickUpdate(View v) {


if (!isValidRollNo()) return;
Cursor c = sqlDb.rawQuery("SELECT * FROM student WHERE rollno='" +
etRollNo.getText() + "'", null);
if (c.moveToFirst()) {
sqlDb.execSQL("UPDATE student SET name='" + etName.getText() +
"',marks='" + etMarks.getText() +
"' WHERE rollno='" + etRollNo.getText() + "'");
showMessage("Success", "Record Modified");
} else {
showMessage("Error", "Invalid Roll no");
}
clearText();
}

public void onClickView(View v) {


if (!isValidRollNo()) return;
Cursor c = sqlDb.rawQuery("SELECT * FROM student WHERE rollno='" +
etRollNo.getText() + "'", null);
if (c.moveToFirst()) {
etName.setText(c.getString(1));
etMarks.setText(c.getString(2));
} else {
showMessage("Error", "Invalid Roll no");
clearText();
}
}

public void onClickViewAll(View v) {


Cursor c = sqlDb.rawQuery("SELECT * FROM student", null);
if (c.getCount() == 0) {
showMessage("Error", "No records found");
return;
}
StringBuffer buffer = new StringBuffer();
while (c.moveToNext()) {
buffer.append("RollNo: " + c.getString(0) + "\n");
buffer.append("Name: " + c.getString(1) + "\n");
buffer.append("Marks: " + c.getString(2) + "\n\n");
}
showMessage("Student Details", buffer.toString());
}

private void clearText() {


etRollNo.setText("");
etName.setText("");
etMarks.setText("");
etRollNo.requestFocus();
}

private void showMessage(String title, String message) {


AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton("Back", null);
builder.show();
}

private void log(String msg) {


System.out.println(msg);
toast(msg);
//showMessage("Query", msg);
}

private void toast(String msg) {


Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
}
Publish Android Application in
Android Market
Refer Universe PDF file CMP516Android Programming.pdf

You might also like