Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6942315
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T12:59:58+00:00 2026-05-27T12:59:58+00:00

I am creating an app that needs a database. I created it using sqlite

  • 0

I am creating an app that needs a database. I created it using sqlite database browser, which means the app I created, imports the database I created into the phone.

The app that I create requires that the user enter data into the database. When upgrading the database, I hope to retain the data that the user had input.

My database helper code is below:

public class DatabaseHelper extends SQLiteOpenHelper {

//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/test.test/databases/";

private static String DB_NAME = "TestDatabase";

private static final int DB_VERSION = 1;

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, DB_VERSION);
    this.myContext = context;
}//constructor  

/**
 *  # Create Database #
 * 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
    }//if

    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");

        }//catch
    }//else

}//createDatabase

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.

    }//catch

    if(checkDB != null) 
    { 
        checkDB.close();

    }//if

    return checkDB != null ? true : false;

}//checkDatabase


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();

}//copyDatabase

// # open database #
public void openDatabase() throws SQLException {

    //Open the database
    String myPath = DB_PATH + DB_NAME;
    myDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

}//openDatabase

@Override
public synchronized void close() 
{
    if(myDatabase != null)
        myDatabase.close();

    super.close();

}//close

@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

public List<String> selectData
    (String tableName, String [] columns, String selection, String[] selectionArgs,
            String groupBy, String having, String orderBy) {

    List<String> list = new ArrayList<String>();

    Cursor cursor = this.myDatabase.query(tableName, columns, selection, selectionArgs, groupBy, having, orderBy);

    if (cursor.moveToFirst()) 
    {
        do 
        {
            list.add(cursor.getString(0));
        }

        while (cursor.moveToNext());
    }

    if (cursor != null && !cursor.isClosed()) 
    {
        cursor.close();
    }
    return list;

}//selectData

public void insertData (String tableName, String nullColumnHack, ContentValues values) {

    try
    {
        myDatabase.insert(tableName, nullColumnHack, values);
    } catch (Exception e) {
        Log.e("Error :","unable to insert data");
    }//catch

}//insertData

//edit row
public void updateData (String tableName, ContentValues values, String whereClause, String[] whereArgs) {

    try
    {
        myDatabase.update(tableName, values, whereClause, whereArgs);
    } catch (Exception e) {
        Log.e("Error :","unable to update data");
    }//catch
}//updateData

public void deleteRow (String tableName, String whereClause, String[] whereArgs) {

    try
    {
        myDatabase.delete(tableName, whereClause, whereArgs);
    } catch (Exception e) {
        Log.e("Error :","unable to delete row");
    }//catch
}//deleteRow
}

*note: My database consist of more than one table. Two tables require user input. The others don’t.

I hope that real answer could be given, instead of giving website that is not in the exact situation that I have, as I get confused easily.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T12:59:59+00:00Added an answer on May 27, 2026 at 12:59 pm

    You should add some code into the onUpgrade method. With that, you can check the oldVersion and the newVersion and do the proper ALTER TABLE statements. As you can see, the current version is 23 and the check code checks what is the old version. If version 22 it does just the v22 statements, but if version 21 it does both v21 AND v22 statements. This is part of the Google I/O app:

    private static final int VER_LAUNCH = 21;
    private static final int VER_SESSION_FEEDBACK_URL = 22;
    private static final int VER_SESSION_NOTES_URL_SLUG = 23;
    
    private static final int DATABASE_VERSION = VER_SESSION_NOTES_URL_SLUG;
    
    ...
    
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.d(TAG, "onUpgrade() from " + oldVersion + " to " + newVersion);
    
        // NOTE: This switch statement is designed to handle cascading database
        // updates, starting at the current version and falling through to all
        // future upgrade cases. Only use "break;" when you want to drop and
        // recreate the entire database.
        int version = oldVersion;
    
        switch (version) {
            case VER_LAUNCH:
                // Version 22 added column for session feedback URL.
                db.execSQL("ALTER TABLE " + Tables.SESSIONS + " ADD COLUMN "
                        + SessionsColumns.SESSION_FEEDBACK_URL + " TEXT");
                version = VER_SESSION_FEEDBACK_URL;
    
            case VER_SESSION_FEEDBACK_URL:
                // Version 23 added columns for session official notes URL and slug.
                db.execSQL("ALTER TABLE " + Tables.SESSIONS + " ADD COLUMN "
                        + SessionsColumns.SESSION_NOTES_URL + " TEXT");
                db.execSQL("ALTER TABLE " + Tables.SESSIONS + " ADD COLUMN "
                        + SessionsColumns.SESSION_SLUG + " TEXT");
                version = VER_SESSION_NOTES_URL_SLUG;
        }
    
        Log.d(TAG, "after upgrade logic, at version " + version);
        if (version != DATABASE_VERSION) {
            Log.w(TAG, "Destroying old data during upgrade");
    
            db.execSQL("DROP TABLE IF EXISTS " + Tables.BLOCKS);
    
            // ... delete all your tables ...
    
            onCreate(db);
         }
     }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

i am creating an app that needs a database. i created it using sqlite
We are creating an app that uses modules which are dynamically loaded into the
I'm creating an app that needs to be accessed by both a web front
I am creating a WPF app that needs to allow users to work in
I am creating a small console app that needs a progress bar. Something like...
I'm creating and app that will rely on a database, and I have all
I am creating an app that is having a UIWebView which contains an advert.
i'm creating a web app that's running on an Advantage Database server, not my
I'm creating a Windows app that automatically updates itself. I'm not using ClickOnce for
I am working on a web app that needs read/write access to an SQLite

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.