How to use My Sqlite Database in Android - java

I am using database in my application, but I make database in SQLite browser and I tried it in my application with guide from this link, and when I try in my eclipse running project to my phone , my application success call database but in another case i try to copy my apk application from folder bin in android and install it.. when i install apk file my application error cannot call database.. and never call database again.. please help me.. thanks here my code :
DataBaseHelper.java
public class DataBaseHelper extends SQLiteOpenHelper{
//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/com.apps.visitkuningan/databases/";
private static String DB_NAME = "db_keterangan.sqlite3";
private SQLiteDatabase myDataBase;
private final Context myContext;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* #param context
*/
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist){
//do nothing - database already exist
}else{
//By calling this method and empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException{
//Open the database
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) {
}
// Add your public helper methods to access and get content from the database.
// You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
// to you to create adapters for your views.
}
This is code using query :
public class KetWisata extends Activity{
Intent arah;
String tampilarah;
String tempat;
Bundle bundel2 = new Bundle();
Cursor cur;
Cursor cur2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.ket_data);
String tampil = getIntent().getExtras().getString("key");
ImageView img1 = (ImageView) findViewById(R.id.gambar);
TextView nama = (TextView) findViewById(R.id.nama);
TextView alamat = (TextView) findViewById(R.id.alamat);
TextView keterangan = (TextView) findViewById(R.id.keterangan);
Button arahkan = (Button) findViewById(R.id.arahkan);
// Create the database
DataBaseHelper myDbHelper = new DataBaseHelper(
this.getApplicationContext());
myDbHelper = new DataBaseHelper(this);
SQLiteDatabase db = myDbHelper.getReadableDatabase();
arahkan.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
startActivity(arah);
}
});
if(tampil.equalsIgnoreCase("wis_balongdalem"))
{
img1.setBackgroundResource(R.drawable.wis_balong);
nama.setText("Balong Dalem");
tempat="Balong Dalem";
tampilarah ="Balong Dalem";
}
if(tampil.equalsIgnoreCase("wis_curugbangkong"))
{
img1.setBackgroundResource(R.drawable.wis_bangkong);
nama.setText("Curug Bangkong");
tempat="Curug Bangkong";
tampilarah ="Curug Bangkong";
}
if(tampil.equalsIgnoreCase("wis_buperciberem"))
{
img1.setBackgroundResource(R.drawable.wis_ciberem);
nama.setText("Bumi Perkemahan Cibeureum");
tempat="Bumi Perkemahan Cibeureum";
tampilarah ="Bumi Perkemahan Cibeureum";
}
if(tampil.equalsIgnoreCase("wis_cibulan"))
{
img1.setBackgroundResource(R.drawable.wis_cibulan);
nama.setText("Wisata Cibulan");
tempat="Cibulan";
tampilarah ="Cibulan";
}
if(tampil.equalsIgnoreCase("wis_balongcicerem"))
{
img1.setBackgroundResource(R.drawable.wis_situ);
nama.setText("Situ Cicereum");
tempat="Situ Ciceureum";
tampilarah ="Situ Ciceureum";
}
if(tampil.equalsIgnoreCase("wis_balongcigugur"))
{
img1.setBackgroundResource(R.drawable.wis_cigugur);
nama.setText("Wisata Cigugur");
tempat="Wisata Cigugur";
tampilarah ="Wisata Cigugur";
}
if(tampil.equalsIgnoreCase("wis_curugcilengkrang"))
{
img1.setBackgroundResource(R.drawable.wis_cilengkrang3);
nama.setText("Lembah Cilengkrang");
tempat="Lembah Cilengkrang";
tampilarah ="Lembah Cilengkrang";
}
if(tampil.equalsIgnoreCase("wis_cipari"))
{
img1.setBackgroundResource(R.drawable.wis_cipari2);
nama.setText("Taman Purbakala Cipari");
tempat="Taman Purbakala Cipari";
tampilarah ="Taman Purbakala Cipari";
}
if(tampil.equalsIgnoreCase("wis_balongdarmaloka"))
{
img1.setBackgroundResource(R.drawable.wis_darmaloka2);
nama.setText("Balong Darmaloka");
tempat="Balong Darmaloka";
tampilarah ="Balong Darmaloka";
}
if(tampil.equalsIgnoreCase("wis_linggarjati"))
{
img1.setBackgroundResource(R.drawable.wis_linggarjat2i);
nama.setText("Linggarjati Indah");
tempat="Linggarjati Indah";
tampilarah ="Linggarjati Indah";
}
if(tampil.equalsIgnoreCase("wis_guamaria"))
{
img1.setBackgroundResource(R.drawable.wis_guamaria);
nama.setText("Gua Maria");
tempat="Gua Maria";
tampilarah ="Gua Maria";
}
if(tampil.equalsIgnoreCase("wis_gedungnaskah"))
{
img1.setBackgroundResource(R.drawable.wis_muslinggar2);
nama.setText("Gedung Perundingan Linggarjati");
tempat="Gedung Perundingan Linggarjati";
tampilarah ="Gedung Perundingan Linggarjati";
}
if(tampil.equalsIgnoreCase("wis_buperpalutungan"))
{
img1.setBackgroundResource(R.drawable.wis_palutungan2);
nama.setText("Bumi Perkemahan Palutungan");
tempat="Bumi Perkemahan Palutungan";
tampilarah ="Bumi Perkemahan Palutungan";
}
if(tampil.equalsIgnoreCase("wis_buperpaniis"))
{
img1.setBackgroundResource(R.drawable.wis_paniis2);
nama.setText("Bumi Perkemahan Paniis");
tempat="Bumi Perkemahan Paniis";
tampilarah ="Bumi Perkemahan Paniis";
}
if(tampil.equalsIgnoreCase("wis_paseban"))
{
img1.setBackgroundResource(R.drawable.wis_paseban);
nama.setText("Gedung Merapat Lima");
tempat="Gedung Merapat Lima";
tampilarah ="Gedung Merapat Lima";
}
if(tampil.equalsIgnoreCase("wis_makamvanbeck"))
{
img1.setBackgroundResource(R.drawable.wis_makamvanbeck);
nama.setText("Situs Makam Van Beck");
tempat="Situs Makam Van Beck";
tampilarah ="Situs Makam Van Back";
}
if(tampil.equalsIgnoreCase("wis_sanggariang"))
{
img1.setBackgroundResource(R.drawable.wis_sanggariang2);
nama.setText("Sanggariang");
tempat="Sanggariang";
tampilarah ="Sanggariang";
}
if(tampil.equalsIgnoreCase("wis_sangkanurip"))
{
img1.setBackgroundResource(R.drawable.wis_sangkanurip);
nama.setText("Sangkanurip Alami");
tempat="Sangkanurip Alami";
tampilarah ="Sangkanurip Alami";
}
if(tampil.equalsIgnoreCase("wis_curugsidomba"))
{
img1.setBackgroundResource(R.drawable.wis_sidomba2);
nama.setText("Sidomba");
tempat="Sidomba";
tampilarah ="Sidomba";
}
if(tampil.equalsIgnoreCase("wis_talagaremis"))
{
img1.setBackgroundResource(R.drawable.wis_talagaremis2);
nama.setText("Talagaremis");
tempat="Talagaremis";
tampilarah ="Talagaremis";
}
if(tampil.equalsIgnoreCase("wis_tngc"))
{
img1.setBackgroundResource(R.drawable.wis_tngc);
nama.setText("Taman Nasional Gunung Ciremai");
tempat="Taman Nasional Gunung Ciremai";
tampilarah ="Taman Nasional Gunung Ciremai";
}
if(tampil.equalsIgnoreCase("wis_wadukdarma"))
{
img1.setBackgroundResource(R.drawable.wis_waduk);
nama.setText("Waduk Darma");
tempat="Waduk Darma";
tampilarah ="Waduk Darma";
}
if(tampil.equalsIgnoreCase("wis_tirtaagung"))
{
img1.setBackgroundResource(R.drawable.wis_tirtaagung);
nama.setText("Tirta Agung Mas");
tempat="Tirta Agung Mas";
tampilarah ="Tirta Agung Mas";
}
if(tampil.equalsIgnoreCase("wis_sangkanaqua"))
{
img1.setBackgroundResource(R.drawable.wis_sangkanaqua);
nama.setText("Sangkan Resort Aqua Park");
tempat="Sangkan Resort Aqua Park";
tampilarah ="Sangkan Resort Aqua Park";
}
if(tampil.equalsIgnoreCase("wis_talaganilem"))
{
img1.setBackgroundResource(R.drawable.wis_talaganilem);
nama.setText("Talaga Nilem");
tempat="Talaga Nilem";
tampilarah ="Talaga Nilem";
}
cur = db.rawQuery("SELECT keterangan FROM KETERANGAN_WIS WHERE nama_tempat='" + tempat + "';", null);
cur2 = db.rawQuery("SELECT alamat FROM KETERANGAN_WIS WHERE nama_tempat='" + tempat + "';", null);
cur.moveToPosition(0);
cur2.moveToPosition(0);
keterangan.append(cur.getString(0));
alamat.append(cur2.getString(0));
// Close
myDbHelper.close();
bundel2.putString("key", tampilarah);
arah = new Intent(KetWisata.this, Arahkan.class);
arah.putExtras(bundel2);
}
}
Please help me guys.. !!

when you run from eclipse to phone it will perform the build before deploying it to the phone. So after you put your database into the assets perform a build before copying the apk file from bin or else you will be copying the apk file which was built before you copied your database

Related

android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database- Logic issue in application

I am learning android yet and not expert. I think I have some logic issue in handle my sqllite database. Let me explain what I am doing and what I am getting.
I have one application of quotes. I am providing local database as well online. I have included database file in Assets and copying database from it during first time when user open application from splash screen. After that I am checking last author and last quote number of local database which are stored in user's device and comparing with online database. If there new data in online then I am downloading and storing it in splash screen.
Now my splash screen code for do same is like below
DAO database=DAO.getInstance(this);
int lastAuthor =database.getLastAuthor();
String updatesUrl = constant.MainUrl + String.valueOf(lastAuthor)+ "/" + String.valueOf(lastQuote);
My DAO class is looking like this
public class DAO {
private SQLiteDatabase database;
private DBHandler dbHandler;
private static final String TABLE_QUOTES = "quotes";
private static final String TABLE_AUTHORS = "authors";
private static final String TABLE_SETTINGS = "settings";
private static final String QU_ID = "_quid";
private static final String QU_TEXT = "qu_text";
private static final String QU_AUTHOR = "qu_author";
private static final String QU_FAVORITE = "qu_favorite";
private static final String QU_TIME = "qu_time";
private static final String AU_NAME = "au_name";
private static final String AU_PICTURE = "au_picture";
private static final String AU_PICTURE_SDCARD = "au_picture_sdcard";
private static final String AU_WEB_ID = "au_web_id";
private static DAO dBObject;
private final Object lockObj=new Object();
public static DAO getInstance(Context context){
if(dBObject==null)dBObject=new DAO(context);
return dBObject;
}
private DAO(Context context) {
synchronized (lockObj) {
dbHandler = new DBHandler(context);
try {
dbHandler.createDataBase();
} catch (IOException e) {
e.printStackTrace();
}
dbHandler.openDataBase();
open();
}
}
public int getLastAuthor() {
String query = "SELECT " + AU_WEB_ID + " FROM " + TABLE_AUTHORS
+ " ORDER BY " + AU_WEB_ID + " DESC LIMIT 1";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
int tmp = cursor.getInt(cursor.getColumnIndex(AU_WEB_ID));
cursor.close();
return tmp;
}
// ==============================================================================
public int getLastQuote() {
String query = "SELECT " + QU_ID + " FROM " + TABLE_QUOTES
+ " ORDER BY " + QU_ID + " DESC LIMIT 1";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
int tmp = cursor.getInt(cursor.getColumnIndex(QU_ID));
cursor.close();
return tmp;
}
// ==============================================================================
public void addAuthor(String au_name, String au_picture, int au_web_id) {
open();
ContentValues v = new ContentValues();
v.put(AU_NAME, au_name);
v.put(AU_PICTURE, au_picture);
v.put(AU_PICTURE_SDCARD, 1);
v.put(AU_WEB_ID, au_web_id);
database.insert(TABLE_AUTHORS, null, v);
}
// ==============================================================================
public void addQuote(String qu_text, int qu_author, int _quid, String qu_time) {
open();
ContentValues v = new ContentValues();
v.put(QU_TEXT, qu_text);
v.put(QU_AUTHOR, qu_author);
v.put(QU_FAVORITE, "0");
v.put(QU_ID, _quid);
v.put(QU_TIME, qu_time);
database.insert(TABLE_QUOTES, null, v);
}
// ==============================================================================
//method changed
private void open() throws SQLException {
if(database!=null&&database.isOpen())return; //changed line
database = dbHandler.getWritableDatabase();
}
// ==============================================================================
public void closeDAO(){
synchronized (lockObj){
if(dbHandler!=null)dbHandler.close();
dbHandler=null;
database=null;
}
}
public static void dispose(){
if(dBObject!=null){
dBObject.closeDAO();
}
dBObject=null;
}
}
And My database handler class looking like this
public class DBHandler extends SQLiteOpenHelper {
private static String DB_PATH;
private static String DB_NAME = "xxx";
private SQLiteDatabase myDataBase;
private final Context myContext;
public DBHandler(Context context) {
super(context, DB_NAME, null, constant.DATABASE_VERSION);
this.myContext = context;
DB_PATH = context.getDatabasePath(DB_NAME).toString();
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
// ==============================================================================
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
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;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
// ==============================================================================
public void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH;
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) {
}
}
I am getting errors in logcat like this
Failed to open database '/data/user/0/com.newdeveloper.test/databases/xxx'.
android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:835)
at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:820)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:723)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:692)
at com.newdeveloper.test.utility.DBHandler.checkDataBase(DBHandler.java:69)
at com.newdeveloper.test.utility.DBHandler.createDataBase(DBHandler.java:32)
at com.newdeveloper.test.utility.DAO.<init>(DAO.java:41)
at com.newdeveloper.test.utility.DAO.getInstance(DAO.java:31)
at com.newdeveloper.test.activities.SplashScreensActivity.checkForUpdate(SplashScreensActivity.java:111)
at com.newdeveloper.test.activities.SplashScreensActivity.access$000(SplashScreensActivity.java:41)
at com.newdeveloper.test.activities.SplashScreensActivity$1.onAnimationEnd(SplashScreensActivity.java:98)
at android.view.animation.AnimationSet.getTransformation(AnimationSet.java:400)
However application does not getting crashed and working fine as I
need. But This errors are confusing me what I need to change for
resolve this errors. I am trying to solve from last two days but not
found any working solution for it. Let me know if any senior developer
can help me for come out from this. Thanks
If you are not already using a bundled database with your apk, you have not actually created the database here in your code.
#Override
public void onCreate(SQLiteDatabase db) {
//you must create the database here
}
// ==============================================================================
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//Handle the database update here
}
You need to do something like this.
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_STRING);
} catch (SQLException e) {
e.printStackTrace();
}
Log.e(TAG, "Table Created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_STRING);
onCreate(db);
Log.d(TAG, "Table upgraded to Version :" + newVersion);
}
I would also recommend to start using ROOM Android Architecture Component, which provides much better abstraction level for the Sqlite for the pattern are using.

How to use AsyncTask for copy Database in Android

I want use AsyncTask for copy database in my application. The application has 4 fragments, and any fragment shows one table from the database (database has 4 tables). But when I run the application, it show me this error:
03-07 12:49:18.775 11190-11190/com.tellfa.dastanak E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.tellfa.dastanak, PID: 11190
android.database.sqlite.SQLiteException: no such table: tbl_Book (code 1): , while compiling: SELECT * FROM tbl_Book WHERE Cat_ID = ?
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:897)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:508)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:726)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1426)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1365)
at com.tellfa.dastanak.Database.DataBase.getCat1_Datas(DataBase.java:157)
at com.tellfa.dastanak.Fragments.Home_Frag.onCreateView(Home_Frag.java:49)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1106)
at android.support.v4.view.ViewPager.populate(ViewPager.java:952)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1474)
at android.view.View.measure(View.java:17496)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:610)
at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:677)
at android.view.View.measure(View.java:17496)
at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:940)
at android.view.View.measure(View.java:17496)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
at android.view.View.measure(View.java:17496)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1438)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:724)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:615)
at android.view.View.measure(View.java:17496)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
at android.view.View.measure(View.java:17496)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1438)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:724)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:615)
at android.view.View.measure(View.java:17496)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2636)
at android.view.View.measure(View.java:17496)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2031)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1193)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1400)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1078)
at android.view.Vi
AsyncTask code :
public class LoadDB_AsyncTask extends AsyncTask<Void, Void, Boolean> {
Context mContext;
boolean loadedDB = false;
private DataBase dataBase;
private ProgressDialog progressDialog;
private static final String LOG_TAG = "log : ";
public LoadDB_AsyncTask(Context context) {
this.mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.i(LOG_TAG, "onPreExecute in loadDB");
progressDialog = new ProgressDialog(mContext);
progressDialog.setMessage("Data loading ...");
progressDialog.setCancelable(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
Log.i(LOG_TAG, "onProgressUpdate in loadDB");
progressDialog.show();
}
#Override
protected Boolean doInBackground(Void... params) {
Log.i(LOG_TAG, "doInBackground in loadDB");
dataBase = new DataBase(mContext);
boolean dbExist = dataBase.checkDataBase();
if (dbExist) {
loadedDB = true;
} else {
publishProgress(null);
}
try {
dataBase.createDataBase();
} catch (IOException e) {
throw new Error("Error on create DataBase");
}
dataBase.close();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Log.i(LOG_TAG, "onPostExecute in loadDB");
if (!loadedDB) {
progressDialog.dismiss();
Log.i(LOG_TAG, "Loaded DataBase");
Toast.makeText(mContext, "Data Loaded", Toast.LENGTH_SHORT).show();
} else {
Log.i(LOG_TAG, "The database was already loaded");
}
try {
finalize();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
}
DataBase code:
public class DataBase extends SQLiteOpenHelper {
private static String DB_PATH = "";
private static String DB_NAME = "Dastansara";
private static int DB_VERSION = 1;
private SQLiteDatabase sqLiteDatabase;
private final Context myContext;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
*
* #param context
*/
public DataBase(Context context) {
super(context, DB_NAME, null, DB_VERSION);
if (android.os.Build.VERSION.SDK_INT >= 17) {
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
} else {
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
}
this.myContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
/**
* Creates a empty database on the system and rewrites it with your own database.
*/
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database alerdy exist
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
*
* #return true if it exists, false if it doesn't
*/
public boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPATH = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPATH, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
/// database does't exist yet
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Open DataBase
*
* #throws SQLException
*/
public void openDataBase() throws SQLException {
String myPATH = DB_PATH + DB_NAME;
sqLiteDatabase = SQLiteDatabase.openDatabase(myPATH, null, SQLiteDatabase.OPEN_READONLY);
}
/**
* Close DataBase
*/
public void closeDataBase() {
sqLiteDatabase.close();
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
*/
public void copyDataBase() throws IOException {
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String myPath = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(myPath);
byte[] buffer = new byte[1024];
int length;
//transfer bytes from the inputfile to the outputfile
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
#Override
public synchronized void close() {
if (sqLiteDatabase != null) {
sqLiteDatabase.close();
}
super.close();
}
public Cursor getCat1_Datas(SQLiteDatabase sqLiteDatabase) {
try {
String query = "SELECT * FROM tbl_Book WHERE Cat_ID = ?";
Cursor cursor = sqLiteDatabase.rawQuery(query, new String[] {"1"});
if (cursor != null) {
cursor.moveToNext();
}
return cursor;
} catch (SQLException e) {
Log.e("Data Adapter", "getTestData >>" + e.toString());
throw e;
}
}
}
Fragment code:
public class Home_Frag extends Fragment {
DataProvider dataProvider;
DataBase dataBase;
SQLiteDatabase sqLiteDatabase;
Cursor cursor;
ListView listView;
Cat1_frag_adapter cat1FragAdapter;
private LoadDB_AsyncTask task;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.frag_home,
container, false);
task = new LoadDB_AsyncTask(getContext());
task.execute();
dataBase = new DataBase(getActivity());
sqLiteDatabase = dataBase.getReadableDatabase();
cursor = dataBase.getCat1_Datas(sqLiteDatabase);
listView = (ListView) rootView.findViewById(R.id.list);
cat1FragAdapter = new Cat1_frag_adapter(getActivity(), R.layout.list_card_layout);
listView.setAdapter(cat1FragAdapter);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
listView.setNestedScrollingEnabled(true);
}
if (cursor.moveToFirst()) {
do {
String id;
String title;
//id = cursor.getString(0);
title = cursor.getString(2);
dataProvider = new DataProvider(title);
cat1FragAdapter.add(dataProvider);
} while (cursor.moveToNext());
}
return rootView;
}
How to fix this error and use Asynctask in my application? tnx <3
Create your database tables in the onCreate of your DBHandler class.(Replace table name and columns)
Helper class
DBHandler Class:
public class DBHandler {
private static String TAG = "DBHandler";
static File dir = new File(Environment.getExternalStorageDirectory() + "");
private static String MYDATABASE_NAME = dir + "/test/tablename.db";// dir+"/
public static final String MYDATABASE_TABLE = "tablename";
public static final int MYDATABASE_VERSION = 1;
public static final String KEY_TDATE = "TDATE" ;
public static final String KEY_TARIFFFCBASIS = "TARIFFFCBASIS" ;
private static final String SCRIPT_CREATE_DATABASE = "create table "
+ MYDATABASE_TABLE + " (" + KEY_ID
+ " integer primary key autoincrement, "
+KEY_TDATE + " text , "
+KEY_TARIFFFCBASIS + " text );"
private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;
private Context context;
public DBHandler(Context c) {
context = c;
if(logger == null){
logger = MasterLibraryFunction.getlogger(context, TAG);
logger.info("In Side DBHandler(Context c)");
}
}
public DBHandler openToRead() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null,
MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
return this;
}
public DBHandler openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null,
MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return this;
}
public void close() {
sqLiteHelper.close();
}
/**
* Check if the database exist
*
* #return true if it exists, false if it doesn't
*/
public boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
checkDB = SQLiteDatabase.openDatabase(MYDATABASE_NAME, null,
SQLiteDatabase.OPEN_READONLY);
checkDB.close();
} catch (SQLiteException e) {
// database doesn't exist yet.
}
return checkDB != null ? true : false;
}
public int deleteAll() {
return sqLiteDatabase.delete(MYDATABASE_TABLE, null, null);
}
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SCRIPT_CREATE_DATABASE);
}
}
}
AsyncTask code :
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
private String resp;
#Override
protected String doInBackground(String... params) {
// Open DB file to write/read
db_helper = new DBHandler(getApplicationContext());
db_helper.openToWrite();
// Complete your operation and close db_helper
return resp;
}
#Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
}
#Override
protected void onPreExecute() {
// Things to be done before execution of long running operation. For
// example showing ProgessDialog
}
}
}

Android Studio App Crash from Sqlite database

I'm hoping my question isn't too broad. What I would really like to know is how to tell exactly where my code is hitting a wall.
I'm not getting errors from my debugger, the app just crashes when the emulator starts an activity that uses a sqlite database (3rd activity in). I am positive it is the addition of sqlite into my code that causes the crash because it ran before I added it.
This code simply needs to access and read from an external database that I created and pasted into the assets folder. I reviewed the sqlite database in firefox's SQLite Manager; the information seems to be formatted correctly.
I created an assets folder within app/src/Main to facilitate the addition of the external database "ex3.db". Then I copied and pasted the database file there.
So here is the code. LetterImage is a class that holds strings retrieved from the sqlite database. MyDBHandler creates an empty database, copies the old one into it, and fills LetterImage with the values returned from a query based on a string. LoadSubjectActivity calls them both to search the database and return a string.
LetterImage:
public class LetterImage {
private Integer _ID;
private String _letter;
private String _bigfilename;
private String _littlefilename;
//Constructor(s)
public LetterImage(){
}
public LetterImage(Integer ID, String letter, String bigfilename, String littlefilename){
this._ID = ID;
this._letter = letter;
this._bigfilename = bigfilename;
this._littlefilename = littlefilename;
}
public LetterImage(String letter){
this._letter = letter;
}
//End Constructors
//Begin setters and getters
//ID is primary key
public void setID(Integer ID){
this._ID = ID;
}
public Integer getID(){
return this._ID;
}
//letter is main identifier used to search database
// passed to LoadSubjectActivity
// from ChooseSubjectABCActivity as extra from intent
public void setLetter(String letter){
this._letter = letter;
}
public String getLetter(){
return this._letter;
}
//Capital letter image file name
public void setBigFileName(String bigfilename){
this._bigfilename = bigfilename;
}
public String getBigFileName(){
return this._bigfilename;
}
//Lowercase Letter image file name
public void setLittleFileName(String littlefilename){
this._littlefilename = littlefilename;
}
public String getLittleFileName(){
return this._littlefilename;
}
}
Now, here is MyDBHandler:
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;
import android.database.Cursor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
public class MyDBHandler extends SQLiteOpenHelper{
private final Context myContext;
private static Context context;
private static final int DATABASE_VERSION = 1;
private static String DB_PATH = "data/data" + context.getPackageName() + "/databases/";
private static final String DATABASE_NAME = "ex3.db";
public static final String TABLE_IMAGES = "tbl1";
private SQLiteDatabase myDataBase;
//Fields in Database
public static final String COLUMN_ID = "_id";
public static final String COLUMN_BIGIMAGEFILE = "bigImage";
public static final String COLUMN_LITTLEIMAGEFILE = "littleImage";
public static final String COLUMN_LETTER = "letter";
//Constructor
public MyDBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.myContext = context;
}
//if there is no existing database, create an empty one
public void createDatabase() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist) {
//do nothing
}else {
//call this method and create an empty database
this.getReadableDatabase();
try {
copyDataBase();
} catch(IOException e){
throw new Error("Error copying database");
}
}
}
//check to see if there is an existing database
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DATABASE_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e){
throw new Error("Unable to open database");
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
//fills new empty database with existing database ex3
private void copyDataBase() throws IOException{
InputStream myInput = myContext.getAssets().open(DATABASE_NAME);
String outFileName = DB_PATH + DATABASE_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
//opens the new database
public void openDatabase() throws SQLException {
String myPath = DB_PATH + DATABASE_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){
}
//creates an instance of letter LetterImage
//queries the new database by searching for the row with where the value of COLUMN_LETTER = letter
//fills LetterImage with the values from that row
public LetterImage findLetter(String letter) {
String query = "Select * FROM " + TABLE_IMAGES + " WHERE " + COLUMN_LETTER + " = \"" + letter + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
LetterImage LetterImage = new LetterImage();
if (cursor.moveToFirst()) {
cursor.moveToFirst();
LetterImage.setID(Integer.parseInt(cursor.getString(0)));
LetterImage.setBigFileName(cursor.getString(1));
LetterImage.setLittleFileName(cursor.getString(2));
LetterImage.setLetter(cursor.getString(3));
cursor.close();
} else {
LetterImage = null;
}
db.close();
return LetterImage;
}
}
Finally, here are the pertinent parts of the LoadSubjectActivity class:
public class LoadSubjectActivity extends MainActivity{
private DrawingView drawView;
private ImageButton currPaint;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_load_subject);
//receives string letter, from last activity
//letter will be used to search array and return files names of the images to be used
Intent intent = getIntent();
String letter = intent.getExtras().getString("letter");
//displayFN calls testDB(letter) to test the database
//It should simply display the string returned by testDB()
TextView displayFN = (TextView)findViewById(R.id.display_filenames);
displayFN.setText(testDB(letter.toLowerCase()));
//Eventually, button images will be filled dynamically
ImageButton bigLetter = (ImageButton)findViewById(R.id.big_letter);
ImageButton littleLetter = (ImageButton)findViewById(R.id.little_letter);
bigLetter.setImageResource(R.drawable.biga);
littleLetter.setImageResource(R.drawable.littlea);
drawView = (DrawingView)findViewById(R.id.drawing);
LinearLayout paintLayout = (LinearLayout)findViewById(R.id.paint_colors);
currPaint = (ImageButton)paintLayout.getChildAt(0);
currPaint.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.paint_pressed));
}
//Function to test the database takes a string as an argument to search the database
public String testDB(String letter){
//create a new instance of dbHandler
MyDBHandler dbHandler = new MyDBHandler(this);
//try to either create an empty database or open the existing one
try{
dbHandler.createDatabase();
} catch (IOException ioe){
throw new Error("Unable to create database");
}
try{
dbHandler.openDatabase();
} catch(SQLException sqle){
sqle.printStackTrace();
throw new Error ("unable to open database");
}
LetterImage letterImage = dbHandler.findLetter(letter);
String blFileName = letterImage.getBigFileName();
//return the big letter image file name;
return blFileName;
}
Anyway, I apologize in advance for any obvious problems. I have traced the logic to the best of my ability...I am teaching myself java and sql...this is my first android project. Any and all insight is greatly appreciated.
I figured out one way to fix this:
1.) rewrite checkDatabase(). I referenced this tutorial: How to use an existing database with an Android application, and found this:
private boolean checkDataBase(){
File dbFile = new File(DB_PATH + DATABASE_NAME);
//Log.v("dbFile", dbFile + " "+ dbFile.exists());
return dbFile.exists();
}
2.) Hard code DB_PATH name, since context.getFilesDir and getDatabasePath() weren't returning the paths I needed.
***going through logcat and tracing the errors back to the exact place the problem started was how I found what I needed to change. In this instance, checkDatabase() wasn't returning false to createDatabase(), so the code was trying to open a database that didn't exist.

What is error no such table: ... in android?

I need to show my data on a ListView everything is correct but When i run this project i get this error :
(1) no such table: WebSite_CategoryBack
My DataBase is correct .I think that my code has error.
This is my MainActivity.java:
public class MainActivity extends ActionBarActivity {
public static Context context;
public static final String DIR_SDCARD =Environment.getExternalStorageDirectory().getAbsolutePath();
public static final String DIR_DATABASE = DIR_SDCARD + "/Mafatih/";
DB db = new DB(MainActivity.this);
public String Titel_Drawer;
public String messageCursor;
private ListView mainListView ;
public SQLiteDatabase sql;
public Cursor cursor;
public ArrayList<String> array;
private ArrayAdapter<String> listAdapter ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File file= new File(DIR_DATABASE);
file.mkdirs();
try{
db.createDataBase();
}catch (IOException e) {
Log.e("create DB3", e.toString());
}
try{
db.openDataBase();
}catch (SQLException e) {
Log.e("create DB3", e.toString());
}
sql = db.getReadableDatabase();
cursor = sql.rawQuery("SELECT * FROM WebSite_CategoryBack;", null);
array = new ArrayList<String>();
while(cursor.moveToNext()){
Titel_Drawer = cursor.getString(cursor.getColumnIndex("tittle"));
array.add(Titel_Drawer);
}
cursor.close();
mainListView = (ListView) findViewById( R.id.mainListView );
listAdapter = new ArrayAdapter<String>(this, R.layout.drawer_layout_main,R.id.rowTextView_Main, array);
mainListView.setAdapter( listAdapter );
mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
int itemposition = position;
String itemvalue = (String) mainListView.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
"Position :"+itemposition+" ListItem : " +itemvalue , Toast.LENGTH_LONG).show();
}
});
mainListView.setTextFilterEnabled(true);
}
And this is my DB.java:
public class DB extends SQLiteOpenHelper{
public static final String DIR_SDCARD =Environment.getExternalStorageDirectory().getAbsolutePath();
public static final String DIR_DATABASE = DIR_SDCARD + "/Mafatih/";
private static String DB_NAME = "Resaleh.db";
private SQLiteDatabase myDataBase;
private final Context myContext;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* #param context
*/
public DB(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist){
//do nothing - database already exist
}else{
//By calling this method and empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database --> "+e.toString());
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DIR_DATABASE + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
Log.e("asdf", "checkDataBase-->"+e.toString());
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
/* (non-Javadoc)
* #see android.database.sqlite.SQLiteOpenHelper#getReadableDatabase()
*/
#Override
public synchronized SQLiteDatabase getReadableDatabase() {
return super.getReadableDatabase();
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DIR_DATABASE + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
try{
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
}catch (IOException e) {
Log.e("Copy", e.toString());
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException{
//Open the database
String myPath = DIR_DATABASE + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY|SQLiteDatabase.NO_LOCALIZED_COLLATORS);
}
#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) {
}
}
THANKS.
There is one good reason why this error will come and i used to get this...
The reason why i got was like i created the db without THAT TABLE now when during course of time if i add a new table then it wont appear and i used to get the error so to make it fresh i used to do the following :-
rename DB.
change version of DB.
uninstall the app.
now install the app.
This used to solve the issue in my case...
thx
By default the SQLite DB is created and saved in the path : data/data/.... on internal storage and opened from there. In case we want to save it on SD card, the address should be manually set and called exactly from the SD card otherwise we will have error.
The correct code is:
public class MainActivity extends ActionBarActivity {
public static Context context;
public static final String DIR_SDCARD =Environment.getExternalStorageDirectory().getAbsolutePath();
public static final String DIR_DATABASE = DIR_SDCARD + "/Mafatih/";
public String Titel_Drawer;
public String messageCursor;
private ListView mainListView ;
public SQLiteDatabase sql;
public Cursor cursor;
public ArrayList<String> array;
private ArrayAdapter<String> listAdapter ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File file= new File(DIR_DATABASE);
file.mkdirs();
sql = SQLiteDatabase.openOrCreateDatabase(DIR_DATABASE + "/Resaleh.db", null);
cursor = sql.rawQuery("SELECT * FROM WebSite_CategoryBack;", null);
array = new ArrayList<String>();
while(cursor.moveToNext()){
Titel_Drawer = cursor.getString(cursor.getColumnIndex("tittle"));
array.add(Titel_Drawer);
}
cursor.close();
mainListView = (ListView) findViewById( R.id.mainListView );
listAdapter = new ArrayAdapter<String>(this, R.layout.drawer_layout_main,R.id.rowTextView_Main, array);
mainListView.setAdapter( listAdapter );
mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
int itemposition = position;
String itemvalue = (String) mainListView.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
"Position :"+itemposition+" ListItem : " +itemvalue , Toast.LENGTH_LONG).show();
}
});
mainListView.setTextFilterEnabled(true);
}
Delete the DB.java.THANKS.

Can write files to server in the emulator but not the device?

So I've run into a peculiar problem. I am trying to write a data file to the device. I developed the app in eclipse under 2.2, my device is 2.3.3, so I made the emulator run at 2.3.3, it writes files fine. Why does this not work on the device? It also is coded to copy the database file on the device to a php server. On the server the file is essentially empty, i pulled the db file from the device as well and it's empty. The only time it works is on the emulator, i get a legit file on the server and when i pull the database it's got data in it. I'm so lost. If you want to see some code then ask, I would have posted some but with 40+ classes I really don't know where to begin.
Thanks in advance.
Here is code relating to the database creation
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "database";
private static final int DATABASE_VERSION = 1;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table database (_id integer primary key autoincrement," +
"name text not null);";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Method is called during creation of the database
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
// Method is called during an upgrade of the database, e.g. if you increase
// the database version
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion,
int newVersion) {
Log.w(DbHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
database.execSQL("DROP TABLE IF EXISTS database");
onCreate(database);
}
}
here is the adapter..
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DbAdapter {
// Database fields
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "name";
static final String DATABASE_TABLE = "database";
private Context context;
private SQLiteDatabase database;
private DbHelper dbHelper;
public DbAdapter(Context ctx) {
context = ctx;
}
public SQLiteDatabase openToRead() throws SQLException {
dbHelper = new DbHelper(context);
database = dbHelper.getReadableDatabase();
return database;
}
public SQLiteDatabase open() throws SQLException {
dbHelper = new DbHelper(context);
database = dbHelper.getWritableDatabase();
return database;
}
public void close() {
dbHelper.close();
}
//
/**
* Create a new todo If the todo is successfully created return the new
* rowId for that note, otherwise return a -1 to indicate failure.
*/
public long createRow(String name) {
ContentValues initialValues = createContentValues(name);
return database.insert(DATABASE_TABLE, null, initialValues);
}
/**
* Update the todo
*/
public boolean updateRows(long rowId,
String name) {
ContentValues updateValues = createContentValues(
name);
return database.update(DATABASE_TABLE, updateValues, KEY_ROWID + "="
+ rowId, null) > 0;
}
/**
* Deletes todo
*/
public boolean deleteRow(long rowId) {
return database.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
/**
* Return a Cursor over the list of all todo in the database
*
* #return Cursor over all notes
*/
public Cursor fetchAllRows() {
return database.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME}, null, null, null,
null, null);
}
/**
* Return a Cursor positioned at the defined todo
*/
public Cursor fetchRow(long rowId) throws SQLException {
Cursor mCursor = database.query(true, DATABASE_TABLE, new String[] {
KEY_ROWID ,KEY_NAME},
KEY_ROWID + "=" + rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
/**fetches keyword**/
public Cursor fetchKeyword(String keyword, String column, String[] columns) throws SQLException {
Cursor mCursor = database.query(DATABASE_TABLE, columns, column + "='" + keyword + "'",
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
private ContentValues createContentValues(String name){
ContentValues values = new ContentValues();
values.put(KEY_NAME, name);
return values;
}
//returns (an) entire column(s), all rows
public Cursor fetchColumns(String[] colnames) {
Cursor mCursor = database.query(DATABASE_TABLE, colnames, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
Ok, I've Isolated it to these three classes.. below is the class that creates the entry and uploads it to the server. as far as i can tell the database isn't being created the right way.. as in there are no tables in the file
public class CreateName extends Activity{
//variables
private DbAdapter mDbHelper;
EditText textField;
TextView txtEnter2;
TextView txtEnter;
Button btnSubmit;
Context context;
SharedPreferences prefs;
SharedPreferences.Editor spe;
SQLiteDatabase db;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.submit);
//constructors
context = getApplicationContext();
prefs = PreferenceManager.getDefaultSharedPreferences(context);
spe = prefs.edit();
init();
listen();
}
public void checker() {
Intent i = new Intent(this, MoveForward.class);
startActivity(i);
}
private void listen() {
btnSubmit.setOnClickListener(new Button.OnClickListener()
{
public void onClick (View v)
{
mDbHelper = new DbAdapter(context);
String words = textField.getText().toString();
Log.v(words, words);
mDbHelper.open();
mDbHelper.createRow(words);
mDbHelper.close();
spe.putString("name", words);
spe.commit();
PHPBuddy buddy = new PHPBuddy();
try {
buddy.uploadFile("database");
} catch (Exception e) {
// ask the user to retry
e.printStackTrace();
}
checker();
}
}
);
}
private void init() {
textField = (EditText)findViewById(R.id.edtTxt);
txtEnter2 = (TextView)findViewById(R.id.txtEnter2);
txtEnter = (TextView)findViewById(R.id.txtEnter);
btnSubmit =(Button)findViewById(R.id.btnSubmit);
txtEnter.setText("Enter your proper name");
txtEnter2.setText("ex: John Smith");
}
}
Maybe there is a cursor or db i'm forgetting to close?
Here is more code..
public class SBMain extends Activity {
Button btnSpinner;
String[] items;
String text;
Spinner s;
Intent i, j;
int activity;
SharedPreferences prefs;
SharedPreferences.Editor spe;
SQLiteDatabase db;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinnerscreen);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
spe = prefs.edit();
init();
fillSpinner();
btnSpinner.setOnClickListener(new Button.OnClickListener()
{
public void onClick (View v)
{
Cursor cc = (Cursor)(s.getSelectedItem());
if (cc != null) {
text = cc.getString(cc.getColumnIndex("name"));
}
checker();
}
});
}
public void checker() {
if (text .equals("Create Name")){
i = new Intent(this, GetName.class);
spe.putString("name", text);
spe.commit();
startActivity(i);
}else{
spe.putString("name", text);
spe.commit();
i = new Intent(this, MoveForward.class);
startActivity(i);
}
}
private void fillSpinner(){
DbAdapter mDbHelper = new DbAdapter(this);
mDbHelper.open();
Cursor c = mDbHelper.fetchColumns(new String[] {"_id","name"});;
if ( ! c.moveToFirst() ){
c.close();
mDbHelper.createRow("Create Name");
mDbHelper.close();
c = mDbHelper.fetchColumns(new String[] {"_id","name"});
}else{
mDbHelper.close();
}
// create an array to specify which fields we want to display
String[] from = new String[]{"name"};
// create an array of the display item we want to bind our data to
int[] to = new int[]{android.R.id.text1};
// create simple cursor adapter
SimpleCursorAdapter adapter =
new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
// get reference to our spinner
s.setAdapter(adapter);
}
private void init() {
btnSpinner = (Button)findViewById(R.id.btnSpinner);
s = (Spinner) findViewById( R.id.spinner1 );
}
}
Here is the splash activity that downloads the file
public class Splash extends Activity{
String file_url = "http://ipaddress/xampp/uploads/";
Context context = this;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread splashThread = new Thread() {
#Override
public void run() {
float percent = 0;
try {
int waited = 0;
int time = 1000;
while (waited < time) {
sleep(100);
waited += 100;
String perc = Integer.toString(waited / time);
}
} catch (InterruptedException e) {
// do nothing
} finally {
//if this is the apps first time running, get a list of names.
if(isFirstRun()){
PHPBuddy buddy = new PHPBuddy();
try {
buddy.downloadFile("database");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//ToDo add spared prefs editor to set isfirstrun to true
Intent i = new Intent();
i.setClassName("com.project",
"com.project.SBMain");
startActivity(i);
}else{
//make registered user page
Intent i = new Intent();
//ToDo add spared prefs editor to set isfrstrun to false
//ToDo add intent for true
}
finish();
}
}
};
splashThread.start();
}
public boolean isFirstRun(){
String rb = "isfirstrun";
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor spe;
spe = prefs.edit();
//spe.putBoolean("isfirstrun", true);
//boolean test = prefs.getBoolean(rb, true);
return true;//prefs.getBoolean(rb, true);
}
}
here is the php
<?php
$myFile = "requestslog.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
fwrite($fh, "\n\n---------------------------------------------------------------\n");
foreach($_SERVER as $h=>$v)
if(ereg('HTTP_(.+)',$h,$hp))
fwrite($fh, "$h = $v\n");
fwrite($fh, "\r\n");
fwrite($fh, file_get_contents('php://input'));
fclose($fh);
echo "<html><head /><body><iframe src=\"$myFile\" style=\"height:100%; width:100%;\"> </iframe></body></html>"
?>
<?php
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
echo "File ". $_FILES['userfile']['name'] ." uploaded successfully.\n";
move_uploaded_file ($_FILES['userfile'] ['tmp_name'], $_FILES['userfile'] ['name']);
} else {
echo "Possible file upload attack: ";
echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
print_r($_FILES);
}
?>
my first guess is that you are trying to write the database somewhere where you don't have permission.
i would recommend using the method File getDir (String name, int mode) of your Activity to get a folder inside your app where you can read and write.
I think I figured it out.
First I set up a class that would copy the database to the SD card right after it was created; from there, I examined the file and saw that it was indeed intact.
Then, I moved the copy call to the place right before the database gets sent to the server. It didn't look fine in "SQLite Database Browser," so I opened it up in Firefox's SQLite manager and voila, all the data was there. So, with Firefox I go and look at the file that was uploaded to the server. What looked empty in the SQLite Database Browser has data in it!

Categories