How to use AsyncTask for copy Database in Android - java

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

Related

Radio Button is messed up when its scrolling

i have 57 radio button in list view, i want to divide those radio button into 19 groups, so each group has 3 radio button. but when i scrolled it the view is messed up and automatically adding radio button become double.
the data is gotten from sqlite database.
KlasifikasiActivity
public class KlasifikasiActivity extends AppCompatActivity {
private ListView lvKlasifikasi;
private ListKlasifikasiAdapter adapter;
private List<Klasifikasi> mKlasifikasiList;
private DatabaseHelper mDBHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_klasifikasi);
lvKlasifikasi = (ListView)findViewById(R.id.stepSwitcher);
mDBHelper = new DatabaseHelper(this);
File database = getApplicationContext().getDatabasePath(DatabaseHelper.DBNAME);
if (false == database.exists()){
mDBHelper.getReadableDatabase();
if (copyDatabase(this)){
Toast.makeText(this,"COPY SUCCESS",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this,"COPY ERROR",Toast.LENGTH_SHORT).show();
return;
}
}
//get db metode
mKlasifikasiList = mDBHelper.getListKlasifikasiByGroup();
adapter = new ListKlasifikasiAdapter(this,mKlasifikasiList);
lvKlasifikasi.setAdapter(adapter);
}
private boolean copyDatabase(Context context) {
try {
InputStream inputStream = context.getAssets().open(DatabaseHelper.DBNAME);
String outFileName = DatabaseHelper.DBLOCATION + DatabaseHelper.DBNAME;
OutputStream outputStream = new FileOutputStream(outFileName);
byte[] buff = new byte[1024];
int length = 0;
while ((length = inputStream.read(buff)) > 0){
outputStream.write(buff,0,length);
}
outputStream.flush();
outputStream.close();
Log.w("MainActivity","DB copied");
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
DatabaseHelper and function method
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "database.db";
public static final String DBLOCATION = "/data/data/com.example.damar.finalproject/databases/";
private Context mContext;
private SQLiteDatabase mDatabase;
public DatabaseHelper(Context context){
super(context,DBNAME,null,1);
this.mContext = context;
}
#Override
public void onCreate(SQLiteDatabase db){
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
}
public void openDatabase(){
String dbPath = mContext.getDatabasePath(DBNAME).getPath();
if (mDatabase != null && mDatabase.isOpen()){
return;
}
mDatabase = SQLiteDatabase.openDatabase(dbPath, null,SQLiteDatabase.OPEN_READWRITE);
}
public void closeDatabase(){
if (mDatabase!=null){
mDatabase.close();
}
}
public List<Klasifikasi> getListKlasifikasiByGroup(){
Klasifikasi klasifikasi = null;
List<Klasifikasi> klasifikasiList = new ArrayList<>();
openDatabase();
Cursor cursor = mDatabase.rawQuery("SELECT * FROM klasifikasi group by group_index", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
klasifikasi = new Klasifikasi(cursor.getInt(0),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getInt(4));
klasifikasiList.add(klasifikasi);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
return klasifikasiList;
}
}
have you checked list just after fetching from db and before set to adapter

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.

Adding Data to SQLiteDatabase

I have a SQLite DB file in assets which is then imported in the application.
The select query works fine and shows the results but at the same time if I try to insert data into the table it does not work. I get no error so that I can identify the problem.
DatabaseHelper class: addProject() method is to insert data.
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DB_VERSION=1;
private static String DB_PATH="";
private static final String DB_NAME="AndroidProject.sqlite";
//Projects Table attrib
String TABLE_PROJECT="Project";
String KEY_PROJECT_ID = "_id";
String KEY_PROJECT_NAME = "project_name";
String KEY_PROJECT_DESC = "project_desc";
String KEY_PROJECT_TYPE = "project_type";
String KEY_PROJECT_START_DATE = "start_date";
String KEY_PROJECT_END_DATE = "end_date";
private SQLiteDatabase myDatabase;
private final Context myContext;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
if (Build.VERSION.SDK_INT>=15){
DB_PATH=context.getApplicationInfo().dataDir + "/databases/";
}
else {
DB_PATH= Environment.getDataDirectory() + "/data/" + context.getPackageName() + "/databases/";
}
this.myContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void checkAndCopyDatabase(){
boolean doExists=checkDatabase();
if (doExists){
Log.d("TAG", "Database alredy exists");
}
else{
this.getReadableDatabase();
}
try {
copyDatabase();
} catch (IOException e) {
e.printStackTrace();
Log.d("TAG", "Error Copying DATABASE");
}
}
public boolean checkDatabase(){
SQLiteDatabase checkDB=null;
try {
String myPath=DB_PATH+DB_NAME;
checkDB=SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READWRITE);
}catch (SQLiteException e){
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
public 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[1024];
int length;
while ((length=myInput.read(buffer))>0){
myOutput.write(buffer,0,length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDatabase(){
String myPath = DB_PATH + DB_NAME;
myDatabase=SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READWRITE);
}
public synchronized void close(){
if (myDatabase != null){
myDatabase.close();
}
super.close();
}
public Cursor QueryData(String query){
return myDatabase.rawQuery(query,null);
}
public void addProject(SqlProjects blog){
//SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_PROJECT_NAME, blog.get_project_name());
values.put(KEY_PROJECT_DESC, blog.get_project_desc());
values.put(KEY_PROJECT_TYPE, blog.get_project_type());
values.put(KEY_PROJECT_START_DATE, blog.get_project_start_date());
values.put(KEY_PROJECT_END_DATE, blog.get_project_end_date());
try {
Log.d("TAG", "Adding data");
myDatabase.insertOrThrow(TABLE_PROJECT, null, values);
} catch (SQLiteException e) {
e.printStackTrace();
}
myDatabase.close();
}
}
SqlProjects class Constructor, getters and setters
public class SqlProjects {
private DatabaseHelper helper;
int _id;
String _project_name, _project_desc,_project_type;
String _project_start_date,_project_end_date;
public SqlProjects() {
}
public SqlProjects(String _project_name, String _project_desc, String _project_type, String _project_start_date, String _project_end_date) {
this._project_name = _project_name;
this._project_desc = _project_desc;
this._project_type = _project_type;
this._project_start_date = _project_start_date;
this._project_end_date = _project_end_date;
}
public SqlProjects(int _id, String _project_name, String _project_desc, String _project_type, String _project_start_date, String _project_end_date) {
this._id = _id;
this._project_name = _project_name;
this._project_desc = _project_desc;
this._project_type = _project_type;
this._project_start_date = _project_start_date;
this._project_end_date = _project_end_date;
}
public int get_project_id() {
return _id;
}
public void set_project_id(int _project_id) {
this._id = _project_id;
}
public String get_project_name() {
return _project_name;
}
public void set_project_name(String _project_name) {
this._project_name = _project_name;
}
public String get_project_desc() {
return _project_desc;
}
public void set_project_desc(String _project_desc) {
this._project_desc = _project_desc;
}
public String get_project_type() {
return _project_type;
}
public void set_project_type(String _project_type) {
this._project_type = _project_type;
}
public String get_project_start_date() {
return _project_start_date;
}
public void set_project_start_date(String _project_start_date) {
this._project_start_date = _project_start_date;
}
public String get_project_end_date() {
return _project_end_date;
}
public void set_project_end_date(String _project_end_date) {
this._project_end_date = _project_end_date;
}
}
Main Class
final DatabaseHelper db = new DatabaseHelper(Add_Project.this);
btnAddProjects.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!(TextUtils.isEmpty(editName.getText().toString())) && !(TextUtils.isEmpty(editDesc.getText().toString())) && !(tvStartDate.getText().equals("")) && !(tvEndDate.getText().equals(""))) {
db.addProject(new SqlProjects(editName.getText().toString(), editDesc.getText().toString(), editType.getSelectedItem().toString(), tvStartDate.getText().toString(), tvEndDate.getText().toString()));
editName.setText("");
editDesc.setText("");
tvStartDate.setText("");
tvEndDate.setText("");
Toast.makeText(getApplicationContext(), "Added Successfully", Toast.LENGTH_SHORT).show();
onBackPressed();
}
}
});
I think you have forgot to open the database before insert operation.
btnAddProjects.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!(TextUtils.isEmpty(editName.getText().toString())) && !(TextUtils.isEmpty(editDesc.getText().toString())) && !(tvStartDate.getText().equals("")) && !(tvEndDate.getText().equals(""))) {
//open db before any operation
db.openDatabase();
db.addProject(new SqlProjects(editName.getText().toString(), editDesc.getText().toString(), editType.getSelectedItem().toString(), tvStartDate.getText().toString(), tvEndDate.getText().toString()));
editName.setText("");
editDesc.setText("");
tvStartDate.setText("");
tvEndDate.setText("");
Toast.makeText(getApplicationContext(), "Added Successfully", Toast.LENGTH_SHORT).show();
onBackPressed();
}
}
});
Seems like the issue anyways check it out!

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.

How to use My Sqlite Database in Android

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

Categories