part 36 - Read Assets Database

 MainActivity.java : 

package first.learn.databasereadlearn;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

DbController dbController ;
Context mContext;

ListView listView2 ;

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

mContext = this;

listView2 = (ListView) findViewById(R.id.listView2);


dbController = new DbController(mContext, "ahsan.db");

dbController.openAssetsDb();


ArrayList<ModelStudent> modelStudentArrayList = new ArrayList<>();

modelStudentArrayList = dbController.getDatabaseContent();


if(modelStudentArrayList.size()>0){

ModelStudent m = modelStudentArrayList.get(0);

System.out.println("Data Base : Name : "+ m.getName());


}else {

System.out.println("Data Base : No Data Found");

}



StudentAdapter adapter = new StudentAdapter(mContext, R.layout.list_item, modelStudentArrayList);
listView2.setAdapter(adapter);





}



}


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"
tools:context=".MainActivity"
android:orientation="vertical">


<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/listView2"/>



</LinearLayout>


dbOpenHelper. java : 

package first.learn.databasereadlearn;



import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class ExternalDbOpenHelper extends SQLiteOpenHelper {

//���� � ����� � ������ �� ����������
public static String DB_PATH;
public static String DB_NAME;
public SQLiteDatabase database;
public final Context mContext;



public SQLiteDatabase getDb() {
return database;
}

public ExternalDbOpenHelper(Context context, String databaseName) {
super(context, databaseName, null, 1);
this.mContext = context;

System.out.println("Database Name:-----3 = "+ databaseName);
String packageName = context.getPackageName();
DB_PATH = String.format("//data//data//%s//databases//", packageName);
DB_NAME = databaseName;
openDataBase();
}



public SQLiteDatabase openDataBase() throws SQLException {
String path = DB_PATH + DB_NAME;
if (database == null) {
createDataBase();
database = SQLiteDatabase.openDatabase(path, null,
SQLiteDatabase.OPEN_READWRITE);
}
System.out.println("Database Path:-----2 = "+ database.getPath());
return database;
}



public void createDataBase() {
boolean dbExist = checkDataBase();
if (!dbExist) {
this.getReadableDatabase();
this.close();
try {
copyDataBase();
} catch (IOException e) {
Log.e(this.getClass().toString(), "Copying error");
throw new Error("Error copying database!");
}
} else {
Log.i("tag", "Token ExternalDbOpenHelper Database already exists");
//Log.i(this.getClass().toString(), "Database already exists");

}
}
private boolean checkDataBase() {
boolean isValid = false ;
SQLiteDatabase checkDb = null;
try {
String path = DB_PATH + DB_NAME;
// checkDb = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
isValid = isValidSQLite(path, 32);

} catch (SQLException e) {
Log.e(this.getClass().toString(), "Error while checking db");
Log.i("tag", "check db Execption");
}
if (checkDb != null) {
checkDb.close();
}
// return checkDb != null;

return isValid;
}

private void copyDataBase() throws IOException {

InputStream externalDbStream = mContext.getAssets().open(DB_NAME);

String outFileName = DB_PATH + DB_NAME;

OutputStream localDbStream = new FileOutputStream(outFileName);

byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = externalDbStream.read(buffer)) > 0) {
localDbStream.write(buffer, 0, bytesRead);
}
localDbStream.close();
externalDbStream.close();
Log.i("tag", "Database copied");

}



@Override
public synchronized void close() {
if (database != null) {
database.close();
}
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {}
// @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}

@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
db.disableWriteAheadLogging();
}

@Override
public void onConfigure(SQLiteDatabase db) {
super.onConfigure(db);
db.disableWriteAheadLogging();
}




///////////////////////////////////////////////////////





public boolean isValidSQLite(String dbPath, int minSizeInMb) {
File file = new File(dbPath);

if (!file.exists() || !file.canRead()) {
return false;
}

boolean isReadable = false ;

try {
FileReader fr = new FileReader(file);
char[] buffer = new char[16];

try {
fr.read(buffer, 0, 16);
} catch (IOException e) {
e.printStackTrace();
}
String str = String.valueOf(buffer);
fr.close();

isReadable = str.equals("SQLite format 3\u0000");

} catch (Exception e) {
e.printStackTrace();

}

if (file.length() > (1024 * 1024 * minSizeInMb) && isReadable) {
return true;
}else {
try {
file.delete();
} catch (Exception e) {
e.printStackTrace();
}
return false ;
}
}


}



dbController.java : 

package first.learn.databasereadlearn;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;

public class DbController {

Context mContext ;
SQLiteDatabase database ;
String DBName ;


public DbController(Context mContext, String DBName) {
this.mContext = mContext;
this.DBName = DBName;
}


public DbController openAssetsDb () throws SQLException {

ExternalDbOpenHelper externalDbOpenHelper = new ExternalDbOpenHelper(mContext, DBName);
database = externalDbOpenHelper.openDataBase();

return this ;
}



/*

CREATE TABLE "Student" (
"studentId" INTEGER,
"RollNumber" TEXT,
"Name" TEXT,
"Age" TEXT,
"Address" TEXT,
"PhoneNumber" TEXT,
PRIMARY KEY("studentId" AUTOINCREMENT)
);


*/




public ArrayList<ModelStudent> getDatabaseContent () {

ArrayList<ModelStudent> modelStudentArrayList = new ArrayList<>();

if(database!=null){

System.out.println( "Database Not Null ");

Cursor cursor ;

cursor = database.rawQuery("select * from Student", null );

if(cursor!=null){
cursor.moveToFirst();
}

if(cursor!=null && cursor.moveToFirst()){

if(!cursor.isAfterLast()){

do {

String rollNumber = cursor.getString(cursor.getColumnIndexOrThrow("RollNumber"));
String name = cursor.getString(cursor.getColumnIndexOrThrow("Name"));
String age = cursor.getString(cursor.getColumnIndexOrThrow("Age"));
String address = cursor.getString(cursor.getColumnIndexOrThrow("Address"));
String phoneNumber = cursor.getString(cursor.getColumnIndexOrThrow("PhoneNumber"));

ModelStudent m = new ModelStudent();
m.setRollNumber(rollNumber);
m.setName(name);
m.setAge(age);
m.setAddress(address);
m.setPhoneNumber(phoneNumber);

modelStudentArrayList.add(m);

}while (cursor.moveToNext());

cursor.close();



}

}


} else {

System.out.println( "Database Null ");

}

return modelStudentArrayList;


}


}


ModelStudent.java : 

package first.learn.databasereadlearn;

public class ModelStudent {


String StudentId, Name, RollNumber, Age, Address, PhoneNumber;

public ModelStudent() {
}


public ModelStudent(String studentId, String name, String rollNumber, String age, String address, String phoneNumber) {
StudentId = studentId;
Name = name;
RollNumber = rollNumber;
Age = age;
Address = address;
PhoneNumber = phoneNumber;
}

public String getStudentId() {
return StudentId;
}

public void setStudentId(String studentId) {
StudentId = studentId;
}

public String getName() {
return Name;
}

public void setName(String name) {
Name = name;
}

public String getRollNumber() {
return RollNumber;
}

public void setRollNumber(String rollNumber) {
RollNumber = rollNumber;
}

public String getAge() {
return Age;
}

public void setAge(String age) {
Age = age;
}

public String getAddress() {
return Address;
}

public void setAddress(String address) {
Address = address;
}

public String getPhoneNumber() {
return PhoneNumber;
}

public void setPhoneNumber(String phoneNumber) {
PhoneNumber = phoneNumber;
}
}



Adapter.java : 

package first.learn.databasereadlearn;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

public class StudentAdapter extends ArrayAdapter<ModelStudent> {

Context mContext ;
ArrayList <ModelStudent> modelStudentArrayList ;

public StudentAdapter(@NonNull Context context, int resource, @NonNull ArrayList<ModelStudent> objects) {
super(context, resource, objects);

mContext = context ;
modelStudentArrayList = objects;
}


@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

View view ;

if(convertView == null){

LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_item, null);
}else {
view = convertView ;
}


TextView tvMobile = ( TextView) view.findViewById(R.id.tvMobile);
TextView tvAge = ( TextView) view.findViewById(R.id.tvAge);
TextView tvName = ( TextView) view.findViewById(R.id.tvName);
TextView tvRoll = ( TextView) view.findViewById(R.id.tvRoll);
TextView tvAddress = (TextView)view.findViewById(R.id.tvAddress);

ModelStudent modelStudent = modelStudentArrayList.get(position);

tvName.setText(modelStudent.getName());
tvAge.setText(modelStudent.getAge());
tvMobile.setText(modelStudent.getPhoneNumber());
tvRoll.setText(modelStudent.getRollNumber());
tvAddress.setText(modelStudent.getAddress());


return view ;
}
}


list_item.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:layout_margin="8dp">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2"
>

<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Roll : "/>


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

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Age : "/>

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Address : "/>

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Mobile : "/>



</LinearLayout>


<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">

<TextView
android:id="@+id/tvRoll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Roll : "/>


<TextView
android:id="@+id/tvName"

android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Name : "/>

<TextView
android:id="@+id/tvAge"

android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Age : "/>

<TextView
android:id="@+id/tvAddress"

android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Address : "/>

<TextView
android:id="@+id/tvMobile"

android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Mobile : "/>




</LinearLayout>

</LinearLayout>


<View
android:padding="2dp"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/black"/>







</LinearLayout>

No comments:

Post a Comment