I have got an error about no such talbe: Account while I am calling data from database.
My database name is "account.db" and table name is "Account". There are two columns, first is "name" and second is "email".
I am writing in kotlin language. Please look at below for my DBHelper and DBManager.
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.os.Build
import android.widget.Toast
import java.io.FileOutputStream
import java.io.IOException
import java.lang.Exception
import java.util.ArrayList
class DbManager {
var DB_PATH = ""
var DB_NAME = "account.db"
val dbVersion = 1
//CREATE TABLE IF NOT EXISTS MyNotes (ID INTEGER PRIMARY KEY,title TEXT, Description TEXT);"
// val sqlCreateTable = "CREATE TABLE IF NOT EXISTS " + dbTable + " (" + colID + " INTEGER PRIMARY KEY," +
// colTitle + " TEXT, " + colDes + " TEXT);"
var sqlDB: SQLiteDatabase? = null
constructor(context: Context) {
var db = DBHelper(context)
sqlDB = db.writableDatabase
}
inner class DBHelper(context: Context) : SQLiteOpenHelper(context, DB_NAME, null, dbVersion) {
var mDatabase: SQLiteDatabase? = null
var mContext: Context? = null
//Todo: Get All Data users
fun getAllUsers(): List<Account>?{
val temp = ArrayList<Account>()
val db = writableDatabase
var c: Cursor?
try {
c = db.rawQuery("SELECT * FROM Account ", null)
if (c == null) return null
c.moveToFirst()
do {
val account = Account(c.getString(c.getColumnIndex("name")), c.getString(c.getColumnIndex("email")))
temp.add(account)
} while (c.moveToNext())
c.close()
} catch (e: Exception) {
}
db.close()
return temp
}
fun createDataBase() {
//Todo: Create Database
val isDBExist = checkDataBase()
if (isDBExist) { } else {
this.readableDatabase
try {
copyDataBase()
Toast.makeText(this.mContext, "Copy has been finished.", Toast.LENGTH_SHORT).show()
} catch (ex: Exception) {
}
}
}
init {
if (Build.VERSION.SDK_INT > 17) {
DB_PATH = context.applicationInfo.dataDir + "/databases/"
} else {
DB_PATH = "/data/data/" + context.packageName + "/databases/"
}
this.mContext = mContext
}
override fun close() {
if (mDatabase != null)
mDatabase!!.close()
super.close()
}
fun checkDataBase(): Boolean {
//Todo: Check Database
var tempDB: SQLiteDatabase? = null
try {
val path = DB_PATH + DB_NAME
tempDB = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY)
} catch (ex: Exception) {
}
if (tempDB != null)
tempDB.close()
return if (tempDB != null) true else false
}
fun copyDataBase() {
//Todo:Copy Database
try {
val myInput = mContext!!.assets.open(DB_NAME)
val outputFileName = DB_PATH + DB_NAME
val myOutput = FileOutputStream(outputFileName)
val buffer = ByteArray(1024)
var length: Int
length= myInput.read(buffer)
while (length > 0) {
myOutput.write(buffer, 0, length)
}
myOutput.flush()
myOutput.close()
myInput.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
fun openDataBase() {
//Todo: Open Database
val path = DB_PATH + DB_NAME
mDatabase = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READWRITE)
}
override fun onCreate(db: SQLiteDatabase) {
createDataBase()
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
if(oldVersion>=newVersion){
copyDataBase()
}
}
// companion object {
// var DB_PATH = ""
// var DB_NAME = "account.db"
// }
}
}
Here is my MainActivity.kt
import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.row.*
import kotlinx.android.synthetic.main.row.view.*
import java.util.ArrayList
class MainActivity : AppCompatActivity() {
var lstUsers=ArrayList<Account>()
lateinit var dbHelper: DBHelper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
dbHelper = DBHelper(applicationContext)
dbHelper.createDataBase()
}
fun buGetData(v: View){
//Todo: Load Data from db set to listview
LoadData()
}
fun LoadData(){
val accout = dbHelper.getAllUsers()
//this.listView.removeAllViews()
//List View
for (list in accout!!) {
lstUsers.add(list)
}
var myNotesAdapter= MyAdapter(this, lstUsers)
listView.adapter=myNotesAdapter
}
inner class MyAdapter:BaseAdapter {
var listMyAdapter = ArrayList<Account>()
var context:Context?=null
constructor(context:Context, listMyAdapter:ArrayList<Account>):super(){
this.listMyAdapter=listMyAdapter
this.context=context
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
var myView=layoutInflater.inflate(R.layout.row,null)
var myAc=listMyAdapter[position]
myView.txtUser.text = myAc.userName
myView.txtEmail.text = myAc.email
return myView
}
override fun getItem(position: Int): Any {
return listMyAdapter[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getCount(): Int {
return listMyAdapter.size
}
}
}
The error has shown like the picture below.
Please help me to solve it. Best regards, Sai Tawng Pha
I have solved my problem with update a few line of code. I want to share for other people.
If some one want to read exist Database file from Assests folder with Kotlin. Please have look below.
MainActivity.kt
import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.row.*
import kotlinx.android.synthetic.main.row.view.*
import java.util.ArrayList
class MainActivity : AppCompatActivity() {
var lstUsers=ArrayList<Account>()
var dbHelper: DBHelper? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
dbHelper = DBHelper(this)
dbHelper!!.createDatabase()
}
fun buGetData(v: View){
lstUsers = this.dbHelper!!.getAllUsers() as ArrayList<Account>
this.container.removeAllViews()
//List View
for (account in lstUsers) {
// val inflater = baseContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
// val addView = inflater.inflate(R.layout.row, null)
var addView = layoutInflater.inflate(R.layout.row,null)
addView.txtUser.text = account.userName
addView.txtEmail.text = account.email
//add View
container.addView(addView)
}
}
}
DBHelper.kt
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;
import android.util.Log;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
public class DbHelper extends SQLiteOpenHelper {
private static String DB_PATH= "";
private static String DB_NAME= "account.db";
private SQLiteDatabase mDatabase;
private final Context mContext;
public DbHelper(Context context) {
super(context, DB_NAME, null, 11);
this.mContext = context;
if(Build.VERSION.SDK_INT >= 17){
this.DB_PATH = context.getApplicationInfo().dataDir+"/databases/";
Log.e("Path:", DB_PATH);
}else {
this.DB_PATH = "/data/data/"+context.getPackageName()+"/databases/";
Log.e("Path:", DB_PATH);
}
}
#Override
public synchronized void close() {
if(mDatabase != null){
mDatabase.close();
}
super.close();
}
private boolean checkDatabase(){
//Todo: Check Database
SQLiteDatabase tempDB = null;
try {
String path = DB_PATH+DB_NAME;
tempDB = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
}catch (Exception ex){}
if(tempDB!=null){
tempDB.close();
}
return tempDB!=null?true:false;
}
public void copyDatabase(){
//Todo: Copy Database
try {
InputStream myInput = mContext.getAssets().open(DB_NAME);
String outputFileName = DB_PATH+DB_NAME;
OutputStream myOutput = new FileOutputStream(outputFileName);
byte[] buffer = new byte[1024];
int length;
while ((length=myInput.read(buffer))>0){
myOutput.write(buffer,0,length);
}
myOutput.flush();
myOutput.close();
myInput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void openDatabase(){
//Todo: Open Database
String path = DB_PATH+DB_NAME;
mDatabase = SQLiteDatabase.openDatabase(path,null, SQLiteDatabase.OPEN_READWRITE);
}
public void createDatabase(){
//Todo: Create Database
boolean isDBExist = checkDatabase();
if (isDBExist){
}else {
this.getReadableDatabase();
try {
copyDatabase();
}catch (Exception e){throw new Error("Copy Database Error");}
}
}
public List<Account>getAllUsers(){
//Todo: Get All Users
List<Account> temp = new ArrayList<Account>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor c;
try {
c = db.rawQuery("SELECT * FROM Account", null);
if (c==null) return null;
c.moveToFirst();
do {
Account account = new Account(c.getString(c.getColumnIndex("name")),(c.getString(c.getColumnIndex("email"))));
temp.add(account);
}while (c.moveToNext());
c.close();
}catch (Exception e){}
db.close();
return temp;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
main_activity.xml
<?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=".MainActivity">
<Button
android:id="#+id/buGetData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Get Data" />
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/buGetData"
android:layout_centerHorizontal="true"
android:layout_marginTop="-15dp"
android:orientation="vertical"></LinearLayout>
</RelativeLayout>
row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txtUserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="TextView"
android:textSize="18sp" />
<TextView
android:id="#+id/txtEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="TextView" />
</LinearLayout>
Please look the screenshot below.
Note: Please replace your Database file from Assets folder and change the name of your database name and table name from DBHelper.kt at createDataBase Function.
I hope, it will be useful for you.
Related
I'm currently working on a settings page for my app and have been trying to obtain the user profile image from the firebase storage. I am able to upload the picture from the storage.
However, the app does not produce the image onto the activity itself. Is there something wrong with my code?
XML:
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/main_chat_toolbar"
android:background="#color/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
</androidx.appcompat.widget.Toolbar>
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/profile_image"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="85dp"
app:civ_border_color="#color/colorPrimary"
android:src="#drawable/pikachu"
app:civ_border_width="2dp" />
<EditText
android:id="#+id/setting_username"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_below="#id/profile_image"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:drawableLeft="#drawable/ic_action_name"
android:hint="Username"
android:inputType="textMultiLine" />
<EditText
android:id="#+id/set_profile_status"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_below="#+id/setting_username"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:drawableLeft="#drawable/ic_user_status"
android:hint="Hey, I'm available now!"
android:inputType="textMultiLine" />
<Button
android:id="#+id/setting_updatebtn"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_below="#id/set_profile_status"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:background="#drawable/btn_rect"
android:text="Update Settings" />
</RelativeLayout>
Java
package com.shiminu1521462c.fyp_2;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.io.File;
import java.util.HashMap;
import de.hdodenhof.circleimageview.CircleImageView;
public class SettingActivity extends AppCompatActivity {
private EditText etUsername, etUserStatus;
private Button changeSettings;
private CircleImageView userProfileImage;
private Toolbar mToolbar;
private String currentUserID;
private FirebaseAuth mAuth;
private DatabaseReference RootRef;
private static final int GalleryPick = 1;
private StorageReference UserProfileImageRef;
private ProgressDialog LoadingBar;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mToolbar = (Toolbar) findViewById(R.id.main_chat_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Settings");
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
RootRef = FirebaseDatabase.getInstance().getReference();
UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
InitializeFields();
etUsername.setVisibility(View.INVISIBLE);
changeSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UpdateSettings();
}
});
RetrieveUserInfo();
userProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GalleryPick);
}
});
}
private void InitializeFields() {
changeSettings = (Button) findViewById(R.id.setting_updatebtn);
etUsername = (EditText) findViewById(R.id.setting_username);
etUserStatus = (EditText) findViewById(R.id.set_profile_status);
userProfileImage = (CircleImageView) findViewById(R.id.profile_image);
LoadingBar = new ProgressDialog(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GalleryPick && resultCode == RESULT_OK && data != null) {
Uri ImageUri = data.getData();
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
LoadingBar.setTitle("Set Profile Image");
LoadingBar.setMessage("Please wait while your profile image is uploading...");
LoadingBar.setCanceledOnTouchOutside(false);
LoadingBar.show();
final Uri resultUri = result.getUri();
StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
Toast.makeText(SettingActivity.this, "Profile Image Uploaded Successfully!", Toast.LENGTH_SHORT).show();
final String downloadUrl = task.getResult().getMetadata().getReference().getDownloadUrl().toString();
RootRef.child("Users").child(currentUserID).child("image")
.setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(SettingActivity.this, "Image saved in Database successfully!", Toast.LENGTH_SHORT).show();
LoadingBar.dismiss();
}else{
String message = task.getException().toString();
Toast.makeText(SettingActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
LoadingBar.dismiss();
}
}
});
} else {
String message = task.getException().toString();
Toast.makeText(SettingActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
LoadingBar.dismiss();
}
}
});
}
}
}
private void UpdateSettings() {
String setUsername = etUsername.getText().toString();
String setStatus = etUserStatus.getText().toString();
if (TextUtils.isEmpty(setUsername)) {
Toast.makeText(this, "Please enter your username..", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(setStatus)){
Toast.makeText(this, "Please set a status..", Toast.LENGTH_SHORT).show();
}
else {
HashMap<String, Object> profileMap = new HashMap<>();
profileMap.put("uid", currentUserID);
profileMap.put("name", setUsername);
profileMap.put("status", setStatus);
RootRef.child("Users").child(currentUserID).updateChildren(profileMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
sendUserToDashboardActivity();
Toast.makeText(SettingActivity.this, "Profile updated successfully!", Toast.LENGTH_SHORT).show();
} else {
String message = task.getException().toString();
Toast.makeText(SettingActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void RetrieveUserInfo() {
RootRef.child("Users").child(currentUserID)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if ((dataSnapshot.exists())
&& (dataSnapshot.hasChild("name")
&& (dataSnapshot.hasChild("image")))) {
String retrieveUsername = dataSnapshot.child("name").getValue().toString();
String retrieveStatus = dataSnapshot.child("status").getValue().toString();
String retrieveProfileImage = dataSnapshot.child("image").getValue().toString();
etUsername.setText(retrieveUsername);
etUserStatus.setText(retrieveStatus);
Picasso.get().load(retrieveProfileImage).into(userProfileImage);
} else if ((dataSnapshot.exists())
&& (dataSnapshot.hasChild("name"))) {
String retrieveUsername = dataSnapshot.child("name").getValue().toString();
String retrieveStatus = dataSnapshot.child("status").getValue().toString();
etUsername.setText(retrieveUsername);
etUserStatus.setText(retrieveStatus);
} else {
etUsername.setVisibility(View.VISIBLE);
Toast.makeText(SettingActivity.this, "Please set and update profile information..", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void sendUserToDashboardActivity() {
Intent mainIntent = new Intent(SettingActivity.this, DashboardActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent myIntent = new Intent(getApplicationContext(), DashboardActivity.class);
startActivityForResult(myIntent, 0);
return true;
}
}
Thank you.
Why not load the image using the resultUri?
Uri resultUri = result.getUri();
Glide.with(this).load(new File(resultUri.getPath())).into(imageView);
Do that after image upload is successful.
have you added the internet permission in the manifest file?
<uses-permission android:name="android.permission.INTERNET" />
I finally managed to solve my issue! This is the altered code, hopefully it helps others who need it! :)
final Uri resultUri = result.getUri();
final StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final String downloadUrl = uri.toString();
RootRef.child("Users").child(currentUserID).child("image").setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(SettingActivity.this, "Profile image stored to firebase database successfully.", Toast.LENGTH_SHORT).show();
LoadingBar.dismiss();
} else {
String message = task.getException().getMessage();
Toast.makeText(SettingActivity.this, "Error Occurred..." + message, Toast.LENGTH_SHORT).show();
LoadingBar.dismiss();
}
}
});
}
});
}
Please i am trying to create a login from a preloaded database. But i am having problems copying database. Below is my debug error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.babbangona.preloadedtestingagain, PID: 11863
java.lang.Error: Error copying database
at com.babbangona.preloadedtestingagain.DBHandler.createDatabase(DBHandler.java:42)
at com.babbangona.preloadedtestingagain.DBcopyActivity$1.onClick(DBcopyActivity.java:28)
at android.view.View.performClick(View.java:6199)
at android.view.View$PerformClick.run(View.java:23235)
at android.os.Handler.handleCallback(Handler.java:836)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6251)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1073)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934) I/art:
Enter while loop. I/art: Enter while loop. Disconnected from the
target VM, address: 'localhost:8600', transport: 'socket'
My DBHandler java file:
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class DBHandler extends SQLiteOpenHelper{
String DB_PATH = null;
private static String DB_NAME = "rehoboth.db";
private SQLiteDatabase myDatabase;
private final Context myContext;
public DBHandler(Context context){
super(context, DB_NAME, null, 2);
this.myContext = context;
this.DB_PATH = "/data/data" + context.getPackageName() + "/databases/";
Log.e("Path 1", DB_PATH);
}
public void createDatabase() throws IOException {
boolean dbExist = checkDatabase();
if(dbExist){
/* openDatabase();
int cVersion = myDatabase.getVersion();
if(cVersion != 2){
onUpgrade(myDatabase, myDatabase.getVersion(),2);
close();
}*/
}else{
this.getReadableDatabase();
try{
copyDatabase();
}catch (IOException e){
throw new Error("Error copying database");
}
}
}
private boolean checkDatabase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDatabase() throws IOException{
InputStream myInput = myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[10];
int length;
while((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDatabase() throws SQLException{
String myPath = DB_PATH + DB_NAME;
myDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
#Override
public synchronized void close(){
if(myDatabase != null)
myDatabase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db){
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
if(newVersion > oldVersion)
try{
copyDatabase();
}catch (IOException e){
e.printStackTrace();
}
}
public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy){
return myDatabase.query("rehoboth", null, null, null, null, null, null);
}
}
My main Activity:
import android.app.Activity;
import android.database.Cursor;
import android.database.SQLException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
public class DBcopyActivity extends Activity {
Cursor c = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dbcopy);
((Button) findViewById(R.id.button1)).setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
DBHandler myDbHelper = new DBHandler(DBcopyActivity.this);
try{
myDbHelper.createDatabase();
}catch(IOException ioe){
throw new Error("Unable to create database");
}try{
myDbHelper.openDatabase();
}catch(SQLException sqle){
throw sqle;
}
Toast.makeText(DBcopyActivity.this, "Successfully Imported", Toast.LENGTH_SHORT).show();
c = myDbHelper.query("rehoboth", null, null, null, null, null, null);
if(c.moveToFirst()){
do{
Toast.makeText(DBcopyActivity.this,
"_id: " + c.getString(0) + "\n" +
"NAME: " + c.getString(1) + "\n" +
"PASSWORD: " + c.getString(2),
Toast.LENGTH_LONG).show();
}while (c.moveToNext());
}
}
});
}
}
SimpleCustomAdapter worked and populated my ListView, but then I wanted to implement a delete ImageButton within the ListView. To achieve that I had to make a custom adapter. Now it doesn't show data in ListView.
This is my MainActivity.java where I put the MyListAdapter class too (at the bottom). I am a beginner so I am aware that code might be all over the place. MainAcitivty has call for adapter, a setonclicklistener for listview which also sends id of item in sharedpreferences so I can catch it in deleteNotes within adapter. Also, delete button works perfectly fine and I can delete notes, but the only problem is that Title and Date dont show in ListView, whereas before they did. Thanks
package com.example.android.notepad2;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.media.Image;
import android.preference.PreferenceManager;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import static com.example.android.notepad2.R.id.parent;
import static com.example.android.notepad2.R.layout.listtemplate;
public class MainActivity extends AppCompatActivity {
NDb mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb = new NDb(this);
ListView listview;
// listview
listview = (ListView) findViewById(R.id.listview);
String[] array = new String[] {mydb.name, mydb.date};
int[] display = new int[] {R.id.title, R.id.date};
Cursor c = mydb.fetchAll();
MyListAdapter adapter = new MyListAdapter(this, listtemplate, c, array, display, 0);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", (int)l);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("ajdi", (int)l);
editor.apply();
Intent intent = new Intent(MainActivity.this, NoteDisplay.class);
intent.putExtras(dataBundle);
MainActivity.this.startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.add_note:
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", 0);
Intent intent = new Intent(MainActivity.this,NoteDisplay.class);
intent.putExtras(dataBundle);
MainActivity.this.startActivity(intent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public class MyListAdapter extends SimpleCursorAdapter{
private LayoutInflater mInflater;
private Context context;
private int layout;
public MyListAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags){
super(context, layout, c, from, to, flags);
this.context = context;
this.layout = layout;
mInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup par){
ViewHolder holder;
if(convertView==null){
mInflater = LayoutInflater.from(getBaseContext());
convertView = mInflater.inflate(R.layout.listtemplate, null);
holder = new ViewHolder();
holder.btn = (ImageButton) convertView.findViewById(R.id.delete_note);
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.date = (TextView) convertView.findViewById(R.id.date);
holder.btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
int l = sp.getInt("ajdi", 0);
if (l != 0) {
mydb.deleteNotes(l);
Toast.makeText(MainActivity.this, "Deleted", Toast.LENGTH_SHORT).show();
finish();
startActivity(getIntent());
}
}
});
convertView.setTag(holder);
}else{
holder= (ViewHolder) convertView.getTag();
}
return convertView;
}
}
public class ViewHolder{
ImageButton btn;
TextView title;
TextView date;
}
}
This is my Database java file.
package com.example.android.notepad2;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by DelicAnte on 04.10.2017..
*/
public class NDb extends SQLiteOpenHelper {
public static final String dbname = "mydb";
public static final String mynotes = "mynotes";
public static final String _id = "_id";
public static final String name = "name";
public static final String content = "content";
public static final String date = "date";
SQLiteDatabase db;
public NDb(Context context){
super(context,dbname,null,1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table mynotes"
+"(_id integer primary key, name text, content text, date text)");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS" + mynotes);
onCreate(db);
}
public boolean insertNotes(String name, String content, String date){
db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("content", content);
contentValues.put("date", date);
db.insert(mynotes, null, contentValues);
return true;
}
public Cursor fetchAll(){
db = this.getReadableDatabase();
Cursor mCursor = db.query(mynotes, new String[] {"_id", "name", "content", "date"}, null, null, null, null, null);
if(mCursor!=null){
mCursor.moveToFirst();
}
return mCursor;
}
public Integer deleteNotes(Integer id){
db = this.getWritableDatabase();
return db.delete(mynotes, "_id=?", new String[] {Integer.toString(id)});
}
public Cursor getData(int id){
db = this.getReadableDatabase();
Cursor c = db.rawQuery("select * from " + mynotes +" where _id=" + id + "", null);
return c;
}
}
This is my listtemplate.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2"
>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/title"
android:textSize="22sp"
android:layout_weight="1"
android:paddingBottom="15dp"
/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/date"
android:textSize="14sp"
android:layout_weight="0.5"
/>
<ImageButton
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="right"
android:src="#drawable/delete_note"
android:layout_weight="0.5"
android:focusable="false"
android:id="#+id/delete_note"
/>
<!-- android:focusable="false"
android:focusableInTouchMode="false"
android:clickable="false"-->
</LinearLayout>
</LinearLayout>
If anyone might be interested. I solved this by adding adapter.bindView in mainactivity.java. In that method you set text for title, content and finally a button setonclicklistener.
When i press "Lägg till(Add)" i put textin my three edittext boxes, then i'll press OK and it should save it in database and display it in my listview with the first editbox text as tite. When i press on a item in my listview i want to be abel to show inputed text and if i press "RADERA(delete)" i want to be able to delete it from databas and listview.
my database adapter
package com.projekt;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
static final String KEY_ROWID = "id";
static final String KEY_PASS = "pass";
static final String KEY_USERNAME = "user";
static final String KEY_TITLE = "title";
static final String TAG = "DBAdapter";
static final String DATABASE_NAME = "DBPASS";
static final String DATABASE_TABLE = "information";
static final int DATABASE_VERSION = 1;
static final String DATABASE_CREATE = "create table information (id integer primary key autoincrement, "
+ "user text not null, pass text not null, title text not null);";
final Context context;
DatabaseHelper DBHelper;
SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
}
// ---opens the database---
public DBAdapter open() throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}
public void close() {
DBHelper.close();
}
public long insertInfo(String title, String user, String pass) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_USERNAME, user);
initialValues.put(KEY_PASS, pass);
return db.insert(DATABASE_TABLE, null, initialValues);
}
public boolean deleteInfo(long rowId) {
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
public void delete_byID(int id){
db.delete(DATABASE_TABLE, KEY_ROWID+"="+id, null);
}
public Cursor getAllInfo() {
return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_USERNAME,
KEY_PASS, KEY_TITLE }, null, null, null, null, null);
}
public Cursor getInfo(String title) throws SQLException {
Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
KEY_ROWID, KEY_USERNAME, KEY_PASS, KEY_TITLE }, KEY_PASS + "= '" + title + "'",
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean updateInfo(long rowId, String title, String user, String pass) {
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
args.put(KEY_USERNAME, user);
args.put(KEY_PASS, pass);
return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}
my program
package com.projekt;
import java.util.ArrayList;
//import java.util.Arrays;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
//import android.text.Editable;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
public class layout2 extends Activity implements OnClickListener, OnItemClickListener {
Button btn3;
ListView lv;
private ArrayAdapter<String> listAdapter;
String titleInfo;
ArrayList<String> nameList;
EditText anvNamn;
EditText pass;
EditText title;
DBAdapter db = new DBAdapter(this);
String passInfo = "";
String anv = "";
String titleInfo2 = "";
String visa;
int del;
Cursor c;
Button btn5;
public void onCreate(Bundle savedInstanceState) {
//Start
super.onCreate(savedInstanceState);
setContentView(R.layout.program_layout);
btn3 = (Button) findViewById(R.id.button3);
btn3.setOnClickListener(this);
btn5 = (Button) findViewById(R.id.button5);
btn5.setOnClickListener(this);
lv = (ListView) findViewById(R.id.listView1);
nameList = new ArrayList<String>();
listAdapter = new ArrayAdapter<String>(this, R.layout.row, nameList);
lv.setAdapter(listAdapter);
lv.setOnItemClickListener(this);
getAllData();
//Stop
}
private ArrayList<String> getAllData() {
// ---get all contacts---
db.open();
c = db.getAllInfo();
if (c.moveToFirst()) {
do {
anv = c.getString(1);
passInfo = c.getString(2);
titleInfo2 = c.getString(3);
//in = new String (anv, passInfo, titleInfo2);
//nameList.add(in);
listAdapter.add(titleInfo2);
//updateList();
} while (c.moveToNext());
//listAdapter.add(titleInfo2);
//del = c.getInt(c.getColumnIndex(db.KEY_ROWID));
}
db.close();
//listAdapter.add(titleInfo2);
return nameList;
}
public void inputDialog() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
LinearLayout lila1 = new LinearLayout(this);
lila1.setOrientation(1);
anvNamn = new EditText(this);
pass = new EditText(this);
title = new EditText(this);
lila1.addView(title);
lila1.addView(anvNamn);
lila1.addView(pass);
title.setText("Titel");
anvNamn.setText("Användarnamn");
pass.setText("Lösenord");
alert.setView(lila1);
title.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
title.setText("");
}
});
anvNamn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
anvNamn.setText("");
}
});
pass.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
pass.setText("");
}
});
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String titleDB = title.getText().toString();
String userDB = anvNamn.getText().toString();
String passDB = pass.getText().toString();
listAdapter.add(titleDB);
db.open();
db.insertInfo(titleDB, userDB, passDB);
db.close();
}
});
alert.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
alert.show();
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button3:
inputDialog();
break;
case R.id.button5:
Intent nextActivity = new Intent(this, MainActivity.class);
startActivity(nextActivity);
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) {
// TODO Auto-generated method stub
String text = nameList.get(arg2);
//final int ar = arg2;
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(titleInfo2);
alert.setMessage("Användarnamn: " + anv + "\nLösenord: "+ passInfo);
final String radera = listAdapter.getItem(arg2).toString();
final long raderaPos = listAdapter.getItemId(arg2);
alert.setNegativeButton("RADERA",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//String s = (String) arg0.getItemAtPosition(arg2);
db.open();
//db.updateInfo(arg2, anv, passInfo, titleInfo);
db.deleteInfo(arg2);
db.updateInfo(arg2, anv, passInfo, titleInfo);
db.close();
listAdapter.remove(radera);
}
});
alert.show();
}
}
im from sweden my string names may be confusing.
Never ever use parameter names like arg0,1,...
It is impossible to understand code that uses such names.
Apparently, in some places, the code uses arg2 (the position of the view in the adapter) where it should use arg3 (the item's row id).
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 3 years ago.
Improve this question
I really need a sqlite database file for studies.
I'm creating an application in C# and I need a database with many tables, field, views, indexes, constraints and so on. And I don't want to create it myself using sqlite command line tool.
So I suppose may be someone can say where I can find such file, may be different applications or examples, or even can send me their own database file. I will appreciate any help.
There is a nice sample database called Chinook. It's trying to be the modern example to replace NorthWind. They have versions for different database servers including SQLite.
Homepage, DB diagram, etc.. http://chinookdatabase.codeplex.com/
Github (seems more updated than CodePlex) https://github.com/lerocha/chinook-database
Latest SQLite download to date of post: https://chinookdatabase.codeplex.com/releases/view/55681#fileDownload6
Download SQLite Sample Database to get the Chinook database file directly http://www.sqlitetutorial.net/sqlite-sample-database/
More SQLite related projects and samples on CodePlex http://www.codeplex.com/site/search?query=sqlite&ac=8
Also, check this sample in the SQLite .NET client forums (attached to first post)
Getting the Microsoft EFQuerySamples project to work with SQLite
Maybe a GUI tool to create database stuff will make starting easier, check this one, free for personal use
http://www.sqliteexpert.com/
Personally, I create SQLite databases for testing NHibernate mappings. Usually I create my classes and mappings then use the mappings to generate schema to a new SQLite file (or in memory database, more often) and use that. Most NHibernate introduction articles do that as well.
SQLite is whidely used by many applications so I am pretty sure very lot examples can be found on your computer. For example, on my Win10 PC if I search in "c:\Users\Konstantin" (my profile) for files with:
file name mask: *.sqlite;*.db
text inside: SQLite format 3
I am currently getting 785 results. Most of them, which have that text in the beginning - it is 99% SQLite database files. Particularly I see that it is used by skype, viber, dropbox, office and firefox.
I used sqlightCrud operation
First creat database class.
package com.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;
public class DataBaseSampleActivity {
/** for database */
static final String DataBaseName = "EmployeDB";
/** for employee table */
static final String EmployeTable = "Employees";
static final String ColEmpID = "EmpId";
static final String ColEmpName = "EmpName";
static final String ColEmpAge = "EmpAge";
static final String ColDept = "Dept";
/** for department table */
static final String DeptTable = "Department";
static final String ColDeptID = "DeptId";
static final String ColDeptName = "DeptName";
public static final int DATABASE_VERSION = 2;
//private static final String KEY_ROWID = "_id";
private static final String EMPLOYEE_TABLE_CREATE ="Create table " + EmployeTable +
//"(_id INTEGER UNIQUE," + [old code]
"("+ColEmpID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
ColEmpName + " VARCHAR(15) ," +
ColEmpAge + " INT(15) ," +
ColDept + " VARCHAR(15)) ";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DataBaseSampleActivity(Context ctx){
Log.i("test****", "**test***");
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper{
public DatabaseHelper(Context context){
super(context, DataBaseName , null, DATABASE_VERSION);
Log.i("context","context");
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(EMPLOYEE_TABLE_CREATE);
Log.i("************", "table created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.w("tag", "Upgrading database from version " + oldVersion + " to "+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + EmployeTable);
onCreate(db);
}
};
public DataBaseSampleActivity open() throws SQLException{
db = DBHelper.getWritableDatabase();
Log.i("open", "message");
return this;
}
public void close(){
DBHelper.close();
}
//public long insert(Integer empid, String empname, Integer empage, String empdept) {
public long insert(String empname, Integer empage, String empdept) {
Log.i("**** suruchitest **** ","*** test ***");
ContentValues initialValues = new ContentValues();
//initialValues.put(ColEmpID, empid);
initialValues.put(ColEmpName, empname);
initialValues.put(ColEmpAge, empage);
initialValues.put(ColDept, empdept);
return db.insert(EmployeTable, null, initialValues);
}
public Cursor getEmpValues(){
Cursor mCursor = db.query(EmployeTable, null, null, null, null, null, null);
return mCursor;
}
public boolean deleteEmpList(long rowId){
Toast.makeText(context, "deleted", 2000).show();
return db.delete(EmployeTable, ColEmpID +" = " + rowId, null) > 0;
}
public boolean updateEmplist(String empname, Integer empage, String empdept, Integer rowid){
ContentValues initialValues = new ContentValues();
Log.i("##### "+rowid,""+empname+" "+empage+" "+empdept);
//initialValues.put(ColEmpID, rowid);
initialValues.put(ColEmpName,empname);
initialValues.put(ColEmpAge,empage);
initialValues.put(ColDept,empdept);
try{
int b = db.update(EmployeTable, initialValues, ColEmpID+ " = " + rowid, null);
Log.i("update", "up "+rowid+" ddd "+b);
return true;
}catch (Exception e){
Log.d("asdfasdfsadfasdf", "_--___--__--_=-_");
return false;
}
}
}
2. create Main Activity
package com.db;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
Button buttonsubmit;
EditText empid,empname,empage,empdept;
String emp_name, emp_dept;
//Integer emp_id,emp_age;
Integer emp_age;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonsubmit = (Button) findViewById(R.id.btnSubmit);
buttonsubmit.setOnClickListener(this);
// empid =(EditText) findViewById(R.id.empid);
empname =(EditText) findViewById(R.id.empname);
empage =(EditText) findViewById(R.id.empage);
empdept =(EditText) findViewById(R.id.empdpt);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DataBaseSampleActivity dbObj = new DataBaseSampleActivity(getApplicationContext());
// String Emp_ids = empid.getText().toString();
// emp_id = Integer.parseInt(Emp_ids);
//emp_id = empid.getText().toString();
String Emp_ages = empage.getText().toString();
emp_age = Integer.parseInt(Emp_ages);
//emp_age = empage.getText().toString();
emp_name = empname.getText().toString();
emp_dept = empdept.getText().toString();
try {
Log.i("try", "message");
dbObj.open();
//long temp = dbObj.insert(emp_id, emp_name, emp_age, emp_dept);
long temp = dbObj.insert(emp_name, emp_age, emp_dept);
//Toast.makeText(getApplicationContext(), "temp"+temp, 3000).show();
dbObj.close();
Intent intent = new Intent(this,ShowListView.class);
startActivity(intent);
} catch (Exception e) {
// TODO: handle exception
Log.i("catch", "message");
}
}
}
2. Create listclass to show tha data
package com.db;
import java.lang.reflect.Array;
import java.util.ArrayList;
import android.R.integer;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ShowListView extends Activity {
ArrayList<String> arrname = new ArrayList<String>();
ArrayList<String> arrage = new ArrayList<String>();
ArrayList<String> arrdept = new ArrayList<String>();
ArrayList<Integer> arrRowId = new ArrayList<Integer>();
ArrayList<Integer> arrDelId = new ArrayList<Integer>();
Array[] arr;
Button deleteBtn;
Button btnadd;
int index = 0;
public int pos;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.emplist);
//Toast.makeText(getApplicationContext(), "LIST VIEW", 5000).show();
ToGetCursorValues();
}
public void ToGetCursorValues(){
DataBaseSampleActivity db = new DataBaseSampleActivity(getApplicationContext());
db.open();
try {
Cursor cur = db.getEmpValues();
cur.moveToFirst();
arrRowId.clear();
arrname.clear();
arrage.clear();
arrdept.clear();
while (!cur.isAfterLast()) {
arrRowId.add(cur.getInt(cur.getColumnIndex(db.ColEmpID)));
arrname.add(cur.getString(cur.getColumnIndex(db.ColEmpName)));
arrage.add(cur.getString(cur.getColumnIndex(db.ColEmpAge)));
arrdept.add(cur.getString(cur.getColumnIndex(db.ColDept)));
cur.moveToNext();
}
//Log.i("#####","col "+arrlist.size());
//Toast.makeText(getApplicationContext(), "* "+arrname.size()+","+arrage.size()+","+arrdept.size(), 5000).show();
//Toast.makeText(getApplicationContext(), "***** "+arrRowId.get(0), 2000).show();
} catch (Exception e) {
// TODO: handle exception
}
ListView lst = (ListView) findViewById(R.id.mylist);
lst.setAdapter(new ListAdapter(getApplicationContext()));
db.close();
}
public class ListAdapter extends BaseAdapter implements OnCheckedChangeListener,OnClickListener{
private LayoutInflater inflater = null;
public ListAdapter(Context c){
Log.i("Context","Context");
inflater = LayoutInflater.from(c);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
//return 0;
return arrname.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
class ViewHolder{
TextView empnameview;
TextView empageview;
TextView empdeptview;
CheckBox empchkbox;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(final int position, View convertView, ViewGroup parent) {
Log.i("*view","view*");
ViewHolder vh;
//ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
Log.i("*null1*","*null1*");
vh = new ViewHolder();
convertView = inflater.inflate(R.layout.customlist, null);
Log.i("*null2*","*null2*");
pos = position;
vh.empnameview = (TextView) convertView.findViewById(R.id.ename);
vh.empageview = (TextView) convertView.findViewById(R.id.eage);
vh.empdeptview = (TextView) convertView.findViewById(R.id.edept);
vh.empchkbox = (CheckBox) convertView.findViewById(R.id.ckekDelete);
Log.i("*null3*","*null3*");
vh.empnameview.setText(arrname.get(position));
vh.empnameview.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(ShowListView.this,UpdateDB.class);
String name = arrname.get(position);
int age = Integer.parseInt(arrage.get(position));
String dept = arrdept.get(position);
int rowid = arrRowId.get(position);
intent.putExtra("KeyName" , name);
intent.putExtra("Keyage" , age);
intent.putExtra("Keydept" , dept);
intent.putExtra("Rowid", rowid);
startActivity(intent);
}
});
vh.empageview.setText(arrage.get(position));
vh.empdeptview.setText(arrdept.get(position));
vh.empchkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
//Toast.makeText(getApplicationContext(), "OnChecked"+position, 2000).show();
if(buttonView.isChecked()){
arrDelId.add(arrRowId.get(position));
//Toast.makeText(getApplicationContext(), "OnChecked"+position, 2000).show();
// DataBaseSampleActivity db = new DataBaseSampleActivity(getApplicationContext());
// db.open();
// db.deleteEmpList(arrRowId.get(position));
// Toast.makeText(getApplicationContext(), "delet", 3000).show();
// db.close();
//
}
else{
for(int i=0;i<arrDelId.size();i++){
if(arrRowId.get(position) == arrDelId.get(i)){
arrDelId.remove(i);
}
}
}
}
});
Log.i("******", "complete");
} else {
Log.i("*not*","*not*");
vh = (ViewHolder) convertView.getTag();
}
deleteBtn = (Button) findViewById(R.id.delBtn);
deleteBtn.setOnClickListener(this);
btnadd = (Button) findViewById(R.id.addBtn);
btnadd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent inte = new Intent(ShowListView.this, MainActivity.class);
startActivity(inte);
}
});
// imageView.setImageResource(thumbarr[position]);
return convertView;
}
public View getView1(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
for(int i=0;i<arrDelId.size();i++){
//Toast.makeText(getApplicationContext(), "OnDeleteClick "+i, 2000).show();
DataBaseSampleActivity db = new DataBaseSampleActivity(getApplicationContext());
db.open();
db.deleteEmpList(arrDelId.get(i));
//Toast.makeText(getApplicationContext(), "delet", 3000).show();
db.close();
}
ToGetCursorValues();
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
}
}
}
3. for update
package com.db;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class UpdateDB extends Activity implements OnClickListener{
Intent intnt;
EditText editname,editage,editdept;
Button updateBtn;
int row_id;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editname = (EditText) findViewById(R.id.empname);
editage = (EditText) findViewById(R.id.empage);
editdept = (EditText) findViewById(R.id.empdpt);
updateBtn = (Button) findViewById(R.id.btnSubmit);
updateBtn.setText("Update");
intnt = getIntent();
editname.setText(intnt.getStringExtra("KeyName"));
editage.setText(""+intnt.getIntExtra("Keyage",0));
editdept.setText(intnt.getStringExtra("Keydept"));
row_id = intnt.getIntExtra("Rowid", 0);
updateBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "update", 3000).show();
DataBaseSampleActivity db = new DataBaseSampleActivity(getApplicationContext());
db.open();
String empname = editname.getText().toString();
int empage = Integer.parseInt(editage.getText().toString());
String empdept = editdept.getText().toString();
//db.deleteEmpList(row_id);
db.updateEmplist(empname, empage, empdept,row_id);
//Toast.makeText(getApplicationContext(), "delet", 3000).show();
db.close();
Intent list = new Intent(UpdateDB.this,ShowListView.class);
startActivity(list);
}
});
// Toast.makeText(getApplicationContext(), "update "+intnt.getIntExtra("Keyage",0), 3000).show();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}