jeudi 31 mars 2016

Android sqlite view can be created but not selected

I am facing a strange problem with my sqlite in an Android app.

My sqlite_master table shows these contents:

type    name
---------------------------------------------------
table   android_metadata
table   LOCALLOG_CALLERPATH
index   sqlite_autoindex_LOCALLOG_CALLERPATH_1
table   sqlite_sequence
table   LOCALLOG_EXCEPTIONTYPE
index   sqlite_autoindex_LOCALLOG_EXCEPTIONTYPE_1
table   LOCALLOG
view    V_ALL
view    V_E_F_STACKTRACE

But when I do a

database.rawQuery("SELECT * FROM sqlite_master", null) 

the cursor returned contains 7 rows (not 9, as expected), and the two indices are missing, as well as the two views are reported as "table", not as "view".

I tried then to do a

database.rawQuery("CREATE VIEW TEST AS SELECT * FROM sqlite_master",null);

which succeeded. But a

database.rawQuery("SELECT * FROM TEST", null);

right afterwards reported me an exception "Error compiling SELECT * FROM TEST. No such table".

Any idea what I am doing wrong here? Why can't I access my views in the database?

Thanks in advance.

Weird use case with SQL

I need "@bb" to equal the COUNT in that first subquery but "a" isn't recognized in the first subquery only the second? I've tried a lot of things with INNER JOIN and scopes but can't get anything to work. I don't use advanced SQL that much.

SELECT name,id AS a,buyin,smallblind,@bb=(SELECT COUNT(players.tbl) FROM players WHERE players.tbl=a) FROM tables WHERE tables.active>300 AND (SELECT COUNT(players.tbl) FROM players WHERE players.tbl=a)<8;

I searched a while and didn't see a solution to this specific problem. I also tried some hours with trial and error in sqllite.

How can I set a path to access my project file in visual studio

I have craete a database folder inside my WPF project and I stored my database over there. I want to use this as my data source path for accessing the database. I made it like in this way SQLiteConnection conn = new SQLiteConnection("Data Source=M:\ANC\xyz\ABC\bin\Debug\Database;Version=3;"); So can I shorten this one .

Copy a sqlite table from assets to data/data in Android

I am making a function that provides sqlite database update. I have a database(such as demo.db) in assets folder that is copied to my data folder when I enter the Android App for the first time. However, when I have a new version for my app, I need to replace a sqlite table in the assets folder which has already been created in the data/data folder.Here is my code:

MySQLiteHelpter extends SQLiteOpenHelper:

@Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        for(int i = oldVersion; i <=  newVersion; i++){
            switch (i){
                case 8:
                    //delete the older table 
                    db.execSQL("drop table if exists " + DFY_BD_DISTRICT);

                    //do something.
                    //I need to copy the table from the assets folder even I have already created the database in the previous version.

                    break;
            }
        }
    }

Here is my code I use to copy my database to data/data folder for the first time:

public static void loadDB(Context context, String dbName) {
    String packName = context.getPackageName();
    String dbPath = "data/data/" + packName + "/databases";

    try {
        File e = new File(dbPath);
        if(!e.exists()) {
            e.mkdirs();
        }

        File dest = new File(e, dbName);
        if(dest.exists()) {
            return;
        }

        dest.createNewFile();
        InputStream in = context.getResources().getAssets().open(dbName);
        int size = in.available();
        byte[] buf = new byte[size];
        in.read(buf);
        in.close();
        FileOutputStream out = new FileOutputStream(dest);
        out.write(buf);
        out.close();
    } catch (Exception var10) {
        var10.printStackTrace();
    }

}

As I have searched on the Internet,I have found some question similar to mine:Android SQLite Database - Copying Table From Assets to Local App Database I am glad that if you can give me some help : )

storing selected values of spinner in sqlite

I need to store the value selected from the spinner into my already existing table in sqlite database.I cannot get a clear idea from the internet because it only shows how to enter the spinner values in db and not the selected value.This is the code for implementing spinner(static)

 Spinner staticSpinner = (Spinner) findViewById(R.id.static_spinner);

    // Create an ArrayAdapter using the string array and a default spinner
    ArrayAdapter<CharSequence> staticAdapter = ArrayAdapter
            .createFromResource(this, R.array.man_array,
                    android.R.layout.simple_spinner_item);

    // Specify the layout to use when the list of choices appears
    staticAdapter
            .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // Apply the adapter to the spinner
    staticSpinner.setAdapter(staticAdapter);

    Spinner dynamicSpinner = (Spinner) findViewById(R.id.dynamic_spinner);

    String[] items = new String[] {"rate_of_flow", "30", "40", "50" };

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, items);

My application can use both dynamic and static spinner.I don't have any preference.Can you help me?

my database cannot saved and not create a table?

Give me a solution? and can you tell me if this class have an errror?

public class UserDbHelper extends SQLiteOpenHelper {


private static final String DATABASE_NAME = "HISSABBOOK.db";
private static final int DATABASE_VERSION = 1;
private static final String CREATE_QUERY =
        "CREATE TABLE " + UserTransaction.TransactionInfo.TABLE_NAME + "(" + UserTransaction.TransactionInfo.DATE + " TEXT," + "" + UserTransaction.TransactionInfo.AMOUNT + " TEXT," + "" + UserTransaction.TransactionInfo.CATEGORY + " TEXT," + UserTransaction.TransactionInfo.PAYMENTMETHOD + " TEXT," + "" + UserTransaction.TransactionInfo.TAG + " TEXT," + "" + UserTransaction.TransactionInfo.QUANTITY + " TEXT," + "" + UserTransaction.TransactionInfo.DESCRIPTION + " TEXT);";

public UserDbHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    Log.e("Database operation", "Database created/open....");
}




@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL(CREATE_QUERY);
    Log.e("DATABASE OPERATION","Table created...");

}

public void addIncomeData(String date, String amount, String category, String paymentmethod, String tag, String quantity, String description, SQLiteDatabase db)
{


    ContentValues contentValues = new ContentValues();
    contentValues.put(UserTransaction.TransactionInfo.DATE, date);
    contentValues.put(UserTransaction.TransactionInfo.AMOUNT, amount);
    contentValues.put(UserTransaction.TransactionInfo.CATEGORY, category);
    contentValues.put(UserTransaction.TransactionInfo.PAYMENTMETHOD, paymentmethod);
    contentValues.put(UserTransaction.TransactionInfo.TAG, tag);
    contentValues.put(UserTransaction.TransactionInfo.QUANTITY, quantity);
    contentValues.put(UserTransaction.TransactionInfo.DESCRIPTION, description);
    db.insert(UserTransaction.TransactionInfo.TABLE_NAME, null, contentValues);
    Log.e("DATABASE OPERATION", "one row inserted...");
}

public class AddIncomeActivity extends AppCompatActivity  {

Button donebtn;
EditText dateEdt,amountEdt,tagEdt,quantityEdt,descriptionEdt;
Spinner paymentmethodSpin,categorySpin;
Context context =this;
UserDbHelper userDbHelper;
SQLiteDatabase sqLiteDatabase;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.addincome_activity);
    donebtn=(Button)findViewById(R.id.btn_done);
    dateEdt=(EditText)findViewById(R.id.date_id);
    amountEdt=(EditText)findViewById(R.id.amount_id);
    tagEdt=(EditText)findViewById(R.id.tag_id);
    quantityEdt=(EditText)findViewById(R.id.quantity);
    descriptionEdt=(EditText)findViewById(R.id.description_id);
    paymentmethodSpin=(Spinner)findViewById(R.id.paymentmethod_spin);
    categorySpin=(Spinner)findViewById(R.id.category_spin);
    getSupportActionBar();


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.savemenu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id=item.getItemId();

    if(id==R.id.save)
    {

        Toast.makeText(this,"Save",Toast.LENGTH_LONG).show();
        return true;
    }
    else if (id==R.id.mainhome)
    {
        startActivity(new Intent(this,MainActivity.class));
        return true;
    }
    else if (id==android.R.id.home)
    {
        return true;
    }

    return super.onOptionsItemSelected(item);
}





public void addIncome(View view){

    String date=dateEdt.getText().toString();
    String amount=amountEdt.getText().toString();
    String category=categorySpin.getSelectedItem().toString();
    String paymentmethod=paymentmethodSpin.getSelectedItem().toString();
    String tag=tagEdt.getText().toString();
    String quantity=quantityEdt.getText().toString();
    String description=descriptionEdt.getText().toString();
    userDbHelper=new UserDbHelper(context);
    sqLiteDatabase=userDbHelper.getWritableDatabase();
    userDbHelper.addIncomeData(date,amount,category,paymentmethod,tag,quantity,description,sqLiteDatabase);
    Toast.makeText(getBaseContext(),"Data Saved",Toast.LENGTH_LONG).show();
    userDbHelper.close();

}

this class contain information a fields?

public class UserTransaction {

public static abstract class TransactionInfo {

    public static final String TABLE_NAME = "transaction";
    public static final String DATE = "date";
    public static final String AMOUNT = "amount";
    public static final String CATEGORY = "category";
    public static final String PAYMENTMETHOD = "paymentmethod";
    public static final String TAG = "tag";
    public static final String QUANTITY = "quantity";
    public static final String DESCRIPTION = "quantity";
}
}

SQLite.swift using datetime

I'm using sqlite.swift for my database and I have a table that I would like to use a datetime column in.

currently I have a datamanager that helps me handle accessing the DB. So I have a class that has static constants like so:

static let itemId = Expression<Int>("itemId")
static let timeUpdateTime = Expression<String>("itemUpdateTime")

and I create the table like so:

static func createTable() throws {
    // create connection
    guard let DB = SQLiteDataStore.sharedInstance.BBDB else {
        throw DataAccessError.Datastore_Connection_Error
    }
    do {
        let _ = try DB.run(table.create(ifNotExists: true) { t in
            t.column(itemId, primaryKey: .Autoincrement)
            t.column(itemUpdateTime)
            })
    } catch _ {
        //error handling if table exists
    }
}

however I'm not sure how to filter only a range of datetime. e.g from 11am to 2pm. .filter() does not filter datetime and I can't filter a range of string as well. I know I can create an Expression<NSDate> for the table column, but it will be converted to a TEXT in the DB and I can't use that to get a range of datetime... How do I filter a range of datetime?

Trying to store username and password in a database and having it check if the username and password match to log in

package com.example.chris.thegiver;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LogIn extends AppCompatActivity implements View.OnClickListener {
    private Button btnRegister2, btnLogIn;
    private EditText etUser, etPass;

    DatabaseHelper helper = new DatabaseHelper(this);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_log_in);

        btnRegister2 = (Button) findViewById(R.id.btnRegister2);
        btnLogIn= (Button) findViewById(R.id.btnLogIn);

        btnRegister2.setOnClickListener(this);

    }
**I think this is where I am having my problem. The app doesnt seem to access the database at all and in order to log in I need to check if the Username matches the password. If the password == the username then it will allow the user to log in. Unforunately that is not happening.**


    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.btnRegister2){
            startActivity(new Intent(LogIn.this, RegisterActivity.class));
        }
        if(v.getId() == R.id.btnLogIn){
            EditText a = (EditText) findViewById(R.id.etUser);
            String str = a.getText().toString();
            EditText b = (EditText) findViewById(R.id.etPass);
            String pass = b.getText().toString();
            String password = helper.searchPass(str);
            if(pass.equals(password)){
                Intent i = new Intent(LogIn.this,HomeActivity.class);
                i.putExtra("Username: ", str);
                startActivity(i);
            }
            else{
                Toast temp = Toast.makeText(LogIn.this, "Username and Password dont match!", Toast.LENGTH_SHORT);
                temp.show();
            }

        }
    }
}
**DATABASE CLASS**

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "contacts.db";
    private static final String TABLE_NAME = "contacts";
    private static final String COL_ID = "id";
    private static final String COL_NAME= "name";
    private static final String COL_EMAIL= "email";
    private static final String COL_USERNAME= "username";
    private static final String COL_PASSWORD= "password";
    SQLiteDatabase db;
    private static final String TABLE_CREATE = "create table contacts (id integer primary key not null, name text not null," +
            "email text not null, username text not null, password text not null)";



    public DatabaseHelper(Context context){
        super(context, DATABASE_NAME, null, DATABASE_VERSION);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(TABLE_CREATE);
        this.db = db;

    }

This method give functionality to the database and insert a users information whenever a new user object is created

    public void insertContact(Contact c){
        db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        // * means all values
        String query = "select * from contacts";
        Cursor cursor = db.rawQuery(query,null);
        int count = cursor.getCount();

        values.put(COL_ID, count);
        values.put(COL_NAME,c.getName());
        values.put(COL_EMAIL, c.getEmail());
        values.put(COL_USERNAME, c.getUsername());
        values.put(COL_PASSWORD, c.getPassword());

        **// this will insert the contact object into the database**
        db.insert(TABLE_NAME, null, values);
        db.close();
    }
**This method is where everything may be going wrong this searches the database for the username and checks if the username is equal to the password. If it isnt then b will be printed to the screen**

    public String searchPass(String uname){
        db = this.getReadableDatabase();
        String query = "select uname, pass from" + TABLE_NAME;
        Cursor cursor = db.rawQuery(query, null);
        String a, b;
        b = "not found";
        if(cursor.moveToFirst()){
            do{
                //usernam
                a = cursor.getString(0);

                if(a.equals(uname)){
                    b = cursor.getString(1);
                    break;
                }enter code here
            }
            while(cursor.moveToNext());
        }
        return b;
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        String query = "DROP TABLE IF EXISTS" + TABLE_NAME;
        db.execSQL(query);
        this.onCreate(db);

    }
}
**REGISTRATION CLASS This sends the database all of the usernames information.**

package com.example.chris.thegiver;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class RegisterActivity extends AppCompatActivity {
    // calls the constructor of the DatabaseHelper class which will create the database and table
    DatabaseHelper registerDB = new DatabaseHelper(this);

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

    public void onRegisterClick(View v) {
        if (v.getId() == R.id.btnReg) {

            EditText etName = (EditText) findViewById(R.id.etName);
            EditText etEmail = (EditText) findViewById(R.id.etEmail);
            EditText etUsername = (EditText) findViewById(R.id.etUsername);
            EditText etPassword = (EditText) findViewById(R.id.etPassword);
            EditText etConfirm = (EditText) findViewById(R.id.etConfirm);


            String name = etName.getText().toString();
            String email = etEmail.getText().toString();
            String user = etUsername.getText().toString();
            String password = etPassword.getText().toString();
            String confirm = etConfirm.getText().toString();

****If password equals confirm then store everything in the java sqlite database created above**.

If password and confirm password do not match then a toast message will appear saying passwords dont match.** if (password.equalsIgnoreCase(confirm)) { Contact c = new Contact(); // Uses the contact class created earlier c.setName(name); c.setEmail(email); c.setUsername(user); c.setPassword(password);

                registerDB.insertContact(c);
                startActivity(new Intent(RegisterActivity.this,LogIn.class));
            }
            else {
                // Pop up message
                Toast pass = Toast.makeText(RegisterActivity.this, "Passwords Dont Match!", Toast.LENGTH_SHORT);
                pass.show();
            }

        }
    }

Returning all rows of a column from my content provider

I'm trying to access a Content Provider I already made (which I made by very closely following a tutorial, I've tested it with the code the tutorial walked me through and it works fine) and read the email addresses that I've added into a SQLite database. In the database is the ID, a COLUMN_NAME, and a COLUMN_EMAIL. I want to get all the rows for the email column and have that be an ArrayList of strings that's returned into this activity.

So far my best guess is that somewhere somehow I'll query the database using the query method from the content provider, return the cursor to the activity, and then collect all the Strings from the rows and either manage to send a query with a projection for just that column or filter out all the @lorem.com's or second index of the cursor or some kind of post data retrieval filter.

Basically I'm just pretty stuck.

Okay so here's my code:

public class EmailScheduler extends AppCompatActivity implements LoaderManager .LoaderCallbacks {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_email_scheduler);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    final TextView emailText = (TextView) findViewById(R.id.emailText);
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Cursor cursor = getContacts();
            Log.i("TAG", cursor.getColumnName(2));
            emailText.append(cursor.toString());
        }
    });
}

private static final int CONTACT_LOADER = 0;
public Uri contactUri;
ArrayList<String> addresses = new ArrayList<>();
Cursor cursor;

private Cursor getContacts() {
    // Run query
    Uri uri = Contact.CONTENT_URI;
    String[] projection = new String[] { Contact._ID,
            Contact.COLUMN_NAME };
    String selection = Contact.COLUMN_EMAIL + " = '"
            + ("1") + "'";
    String[] selectionArgs = null;
    String sortOrder = Contact.COLUMN_NAME
            + " COLLATE LOCALIZED ASC";
    return getContentResolver().query(uri, projection, selection, selectionArgs,
            sortOrder);
}
// called by LoaderManager to create a Loader
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    CursorLoader cursorLoader;

    switch (id) {
        case CONTACT_LOADER:
            cursorLoader = new CursorLoader(this,
                    contactUri, // Uri of contact to display
                    null, // null projection returns all columns
                    null, // null selection returns all rows
                    null, // no selection arguments
                    null); // sort order
            break;
        default:
            cursorLoader = null;
            break;
    }

    return cursorLoader;
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {

    Log.i("TAG", "got to the beginning of onloadfinish " + data);
    if (data != null && data.moveToFirst()) {
        int nameIndex = data.getColumnIndex(Contact.COLUMN_NAME);
        int emailIndex = data.getColumnIndex(Contact.COLUMN_EMAIL);
        String address = data.getString(emailIndex);
        Log.i("TAG", address);

        while (data.getString(emailIndex) != null){
            addresses.add(cursor.getString(cursor.getColumnIndex(
                    Contact.COLUMN_EMAIL)));
            Log.i("TAG", addresses.toString());}
    }
}

@Override
public void onLoaderReset(Loader<Cursor> loader) { }

}

In the onCreate method it returns this data when I run it: android.content.ContentResolver$CursorWrapperInner@60c9bd2

How do I get the information I need from that? Everything I try turns into a dead end.

Nested ArrayList and manual database entry

I'm working on a RecyclerView in Android that looks like this:

A

A topic1

A topic2

A topic3

B

B topic1

B topic2

With the topics hidden until you tap on the parent letter.

I've got something that I think should be working, but now if I add rows to my database manually (which is by design), additional rows aren't recognized, even if I uninstall the app and load it back in. This is what I'm looking at:

final List<AToZList> aToZ = addTopics();
mAdapter = new AToZAdapter(getContext(), aToZ);

...

private List<AToZList> addTopics() {
        topics = new ArrayList<Topic>();
        List<AToZList> aToZ;
        AToZList A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z;
        A=B=C=D=E=F=G=H=I=J=K=L=M=N=O=P=Q=R=S=T=U=V=W=X=Y=Z = null;

        Cursor topicCursor = database.rawQuery("SELECT " + ExternalDbContract.QuoteEntry.TOPIC +
                " FROM " + ExternalDbContract.QuoteEntry.TABLE_NAME, null);

        try {
            for (topicCursor.moveToFirst(); !topicCursor.isAfterLast(); topicCursor.moveToNext()) {
                String firstLetter = topicCursor.getString(0).toUpperCase().substring(0, 1);

                switch (firstLetter) {
                    case "A":
                        if(A == null) {
                            A = new AToZList("A", getTopics(firstLetter));
                        }
                        break; //and so on for every letter
                }finally {
                    aToZ = Arrays.asList(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z);
                }
    topicCursor.close();
    return aToZ;

...

private ArrayList<Topic> getTopics(String firstLetter) {
        Cursor topicCursor = database.rawQuery("SELECT " + ExternalDbContract.QuoteEntry.TOPIC +
                " FROM " + ExternalDbContract.QuoteEntry.TABLE_NAME, null);

        ArrayList<Topic> topicsByLetter = new ArrayList<Topic>();

        for(topicCursor.moveToFirst(); !topicCursor.isAfterLast(); topicCursor.moveToNext()) {
            if (topicCursor.getString(0).toUpperCase().substring(0, 1).equals(firstLetter)) {
                topicsByLetter.add(new Topic(topicCursor.getString(0)));
            }
        }
        topicCursor.close();
        return topicsByLetter;
    }

That's a lot of code.

I've added some logging to see what's actually getting passed through. I have 3 topic entries in the database, two that start with "A" and a third that starts with "B". The A's come through okay (there are two entries for that), and then for some reason it kicks out to the finally block, and ruins the Array because it only has one entry (as in, one "A" entry). topicCursor.getCount() tells me that there are only two entries, but there are three. CURSE YOU CURSOR!

If it would be helpful I've committed where I'm at onto Github.

iOS sqlite insert statments with variables

I am learning how to use sqlite in IOS

I am using the following to insert a record into a table

 int DBID =  [_db  ExecuteINSERT:@"INSERT INTO LOG(NAME , COMPANY , CATEGORY)   VALUES('txt1','txt2','txt3')"];

This works fine and adds the three strings into a row

I want to exchange the hardcoded strings for string variable but can work out what to do. I tried

NSString* myString1 = @"String1";
NSString* myString2 = @"String2";
NSString* myString3 = @"String3";
int DBID = _db  ExecuteINSERT:@"INSERT INTO LOG(NAME , COMPANY,     CATEGORY) VALUES(myString1, myString2, myString3)"];

But I get a sqlite error 1 no such column but there is as it works with hardcoded strings

any ideas where I'm going wrong?

Any help appreciated

Mark

Need to change TableName being passed in to Java SQLite query

I am passing VariableA (barTableName ) to an SQLite query, "SELECT * FROM " + barTableName + " WHERE DRINKTYPE='Beer';". I need barTableName to be able to change, based on what a user chooses. When I hardcode the variable, it works. If I try to change it at all, no matter how far back in the "variable timeline", it gives me a null point exception. Does anyone know how I could acomplish this?

DBHelper

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

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

public class DBHelper extends SQLiteOpenHelper {

    private static String DB_PATH = "/data/data/com.example.sixth/databases/";
    private static String DB_NAME = "BarSample.db"; 
    private final Context myContext;    
    public static String tableName = "BARS";
    String barTableName, sqlquery ;
    public static String firstBarTableName = MainActivity.upperCaseName;//Pass in the specific bar from the spinner choice
    private SQLiteDatabase myDataBase;


    public DBHelper(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 {
                this.close();
                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) {

    }

    public List<String> getAllLabels(){
        List<String> labels = new ArrayList<String>();

        // Select All Query
        String selectQuery = "SELECT  * FROM " + tableName;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                labels.add(cursor.getString(1) + " " + cursor.getString(2)+ ", " + cursor.getString(3));
            } while (cursor.moveToNext());
        }

        // closing connection
        cursor.close();
        db.close();

        // returning labels
        return labels;

    } // will returns all labels stored in database

    public List<String> getBeerDrinkLabels(){
        //naming();
        List<String> allBeerDrinkLabels = new ArrayList<String>();

        if (firstBarTableName.equals("CHANGOS")){
            sqlquery = "SELECT * FROM CHANGOS WHERE DRINKTYPE='Beer';";
        }
        else if(firstBarTableName.equals("LANDOS")){
            sqlquery = "SELECT * FROM LANDOS WHERE DRINKTYPE='Beer';";
        }
        else{
            sqlquery = "SELECT * FROM ANTHONYS WHERE DRINKTYPE='Beer';";
        }


        //String sqlquery="SELECT * FROM " + barTableName + " WHERE DRINKTYPE='Beer';";
        String selectQuery = sqlquery;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                allBeerDrinkLabels.add(cursor.getString(1) + " Price: " + cursor.getString(2));
            } while (cursor.moveToNext());
        }

        // closing connection
        cursor.close();
        db.close();

        // returning labels
        return allBeerDrinkLabels;

    } // will returns all labels stored in database

    public List<String> getWineDrinkLabels(){
        List<String> allWineDrinkLabels = new ArrayList<String>();

        // Select All Query
        String sqlquery="SELECT * FROM "+barTableName + " WHERE DRINKTYPE='Wine';";
        String selectQuery = sqlquery;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                allWineDrinkLabels.add(cursor.getString(1) + ", " + cursor.getString(2));
            } while (cursor.moveToNext());
        }

        // closing connection
        cursor.close();
        db.close();

        // returning labels
        return allWineDrinkLabels;

    } // will returns all labels stored in database

    public List<String> getMixedDrinkDrinkLabels(){
        List<String> allMixedDrinkDrinkLabels = new ArrayList<String>();

        // Select All Query
        String sqlquery="SELECT * FROM "+barTableName + " WHERE DRINKTYPE='Mixed Drink';";
        String selectQuery = sqlquery;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                allMixedDrinkDrinkLabels.add(cursor.getString(1) + ", " + cursor.getString(2));
            } while (cursor.moveToNext());
        }

        // closing connection
        cursor.close();
        db.close();

        // returning labels
        return allMixedDrinkDrinkLabels;

    } // will returns all labels stored in database

    public List<String> getOtherDrinkLabels(){
        List<String> allOtherDrinkLabels = new ArrayList<String>();

        // Select All Query
        String sqlquery="SELECT * FROM "+barTableName + " WHERE DRINKTYPE='Other';";
        String selectQuery = sqlquery;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                allOtherDrinkLabels.add(cursor.getString(1) + ", " + cursor.getString(2));
            } while (cursor.moveToNext());
        }

        // closing connection
        cursor.close();
        db.close();

        // returning labels
        return allOtherDrinkLabels;

    } // will returns all labels stored in database

    public List<String> getShotsDrinkLabels(){
        List<String> allShotsDrinkLabels = new ArrayList<String>();

        // Select All Query
        String sqlquery="SELECT * FROM "+barTableName + " WHERE DRINKTYPE='Shots';";
        String selectQuery = sqlquery;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                allShotsDrinkLabels.add(cursor.getString(1) + ", " + cursor.getString(2));
            } while (cursor.moveToNext());
        }

        // closing connection
        cursor.close();
        db.close();

        // returning labels
        return allShotsDrinkLabels;

    } // will returns all labels stored in database
}

I'm currently try to assign it to splquery with an If statement, based on what is coming in from the other class. I have double, triple checked. The variable coming in IS one of the 3 that are in the if statement, all in caps like is in the statement. I've been working on this for a long while and am beating my head against the wall. Any help would be VERY appreciated.

Update External SQLite Database

I have an App shipped with an external SQLite database on Play Store. The app works fine but when i did update (change database content) of the App on Google Play, the database still reflects the old one. Please how can I make the App to access the latest database.

Below is my DatabaseOpenHelper code.

public class DatabaseOpenHelper extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "mydb.db";
private static  int DATABASE_VERSION = 1;


public DatabaseOpenHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

}

Someone suggest I should change the DATABASE_VERSION to something but the App crashes when I did so.

how can I launch an android application if there is a change in the location stored in the database on the cloud?

I am creating an application which I want to be launched whenever user reaches a certain location. And the coordinates of the that location has already been pre-stored within the database/cloud. A code snippet would help. Thanks.

How do know the csv created from SQLite is closed so I can read from it?

In vb.net, I have my program run sqlite3.exe. Sqlite3 runs the following commands, which are stored in a text file:

.open prod.db
.mode csv
.output output.csv
SELECT STATEMENT
.output stdout
.exit

Once output.csv has been created, I then run a Streamreader to see what the results were and I get the following error:

The process cannot access the file 'output.csv' because it is being used by another process.

However, I know it is not locked up for long because I can go to the csv and open it manually after it is created.

I would write code to check to see when the process finishes, but I'm not sure what process is running to check this (I already check for SQLite3.exe to close). In other words, how do I know my csv is free for Streamreader to open?

Cordova Android sqlite database query and array shuffle

I apologize for such a long post but this is for our senior project and it is crunchtime so I tried to be as detailed as humanly possible for my skill level. Any and all help would be an absolute lifesaver.

My team and I are developing an Android app in Cordova using Visual Studio that uses a prepopulated sqlite database to query from. We can see that the database file is successfully created during the onDeviceReady function with the following code in our index.js:

// deviceready Event Handler
onDeviceReady: function() {
    $("#page1").show();
    app.receivedEvent('deviceready');

    var db = window.sqlitePlugin.openDatabase({name: 'events.db', createFromLocation: 1, iosDatabaseLocation: 'default'});

then in our project.js file we have the following code:

private function getTopTen() {

    //Opens database file for query
    SQLiteDatabase db = this.getReadableDatabase(); 
    Cursor crs = db.rawQuery("SELECT Name FROM events WHERE Park='SomeFakePark' ", null);

    var topTenArray = new Array(10);
    var length = 10;
    int i = 0;

    //Writes the top ten ride/event names into array
    for ( i = 0, i < length, i++) {
        String rideName = crs.getString(crs.getColumnIndex("NAME"));
        topTenArray[i] = rideName;
        crs.moveToNext();
    }
    return topTenArray;
}

^^^^^The function 'getTopTen' above attempts to query the database file for names of rides within a given amusement park. The table and database are both named 'events' and 'events.db' respectively. That table has columns labeled 'Name' and 'Park' and we want to select the first ten entries in column 'Name' that all have the same entry in column 'Park'. For example, starting from the first row of column 'Name' I want to pull the first ten ride names that have the same entry 'SomeFakePark' in the column 'Parks'. Then we want to copy those first ten 'Name' entries into an array for later recall and display.

//Takes a passed array and shuffles it randomly
function randomize(array) {
    var randomArray = [];
    var arrayLength = array.length;
    var i;

    while (counter) {

        i = Math.floor(Math.random() * array.length);

        if (i in array) {
            randomArray.push(array[i]);
            delete array[i];
            counter--;
        }
    }
    return randomArray;
}

^^^^^The above function 'randomize' takes an array (the one created from the first function) and shuffles it randomly.

Finally these two functions are called by a button tap as such:

//Random button actions
$("#rbutton").on("tap", function(){
    randomize(getTopTen());
    navigation(page1, page2);

^^^^^Where the return value of the function randomItinerary() is passed as a parameter for the function randonmize().

I would like to know if this code is on the right track for what I am trying to accomplish? Mainly, is the DB query correct and also when the randomize function finally returns my shuffled array is that array value kept for use to display later or do I need to store it in a permanent global variable somewhere for recall, and if it needs a variable for storing where and how do I create that variable?

Data from database not displaying on new page (JavaScript/HTML)

I am attempting to get the data fetched from the query to be displayed on a different page, however the data is not being displayed on a new page.

The table was being displayed with the data correctly on the same page as the search, however when I tried to change things around so the data is shown on a new page it doesn't work.

I am using JQuery mobile, so it's a one page structure (all pages under index.html) and I have all my javascript on a separate file.

Can anyone see the issue here?

Fetching data function:

    function fetchEvent()
             {
          db = window.openDatabase("SoccerEarth", "2.0", "SoccerEarthDB", 2*1024*1024);
          db.transaction(foundEvent, errorCB);
         }

          function foundEvent(tx)
            {
            var TitleT = document.getElementById("texttitle").value;
           tx.executeSql("SELECT * FROM SoccerEvents WHERE Title LIKE '%" + TitleT + "%'", [], renderEvent);
                        }

function renderEvent(tx, response) {
   /* var div = document.getElementById("responsediv"); */
    var temp = "<table border=\"1\"><tr><th>Title</th><th>Location</th><th>NoPeople</th><th>Date</th><th>Description</th></tr>";

    for (var i = 0; i < response.rows.length; i++) {
        temp += "<tr><td>" + response.rows.item(i).Title + "</td><td>" + response.rows.item(i).Location + "</td><td>" + response.rows.item(i).NoPeople + "</td><td>" + response.rows.item(i).Date + "</td><td>" + response.rows.item(i).Description + "</td></tr>";
         /* div.innerHTML = temp; */
    }
    var page6 = window.open("#page20", "mywin", '');
    page6. dataFromParent = temp;
    page6.render();
}
    var dataFromParent;
    function render() {
        $('datadisplay').innerHTML(dataFromParent);
    }

HTML (page 6):

    <div data-role="page" id="page20" data-theme="d">

    <div data-role="content">
        <div id="datadisplay">
        </div>
    </div>
</div>

Cannot open file SQLite error in Android App

I'm new to SQLite and this is the first database that I'm using in an App, so I'm having some troubles.

At first, I could use the database with no problems, I was fetching the data correctly and it was working fine. But I realized that, after reinstalling the App, it was throwing me a SQLite cannot open file error.

Now it's pretty much crashed and I don't know why. It never works, it always throws me the Cannot open file error.

I never write data to my database, I only use it to fetch some data. This is the content of my DatabaseHelper class:

public static String DB_PATH = "/data/data/myapp.app.databasetest/databases/";

public static String DB_NAME = "mydatabase.db"; public static final int DB_VERSION = 2;

private SQLiteDatabase myDB;
private Context context;

public DatabaseHelper(Context context) {
  super(context, DB_NAME, null, DB_VERSION);
  this.context = contex
}

//check if database exists
private boolean checkDataBase() {
  SQLiteDatabase tempDB = null;

  try {
    String myPath = DB_PATH + DB_NAME;
    //the error appears in the next line
    tempDB = SQLiteDatabase.openDatabase(myPath, null,  SQLiteDatabase.OPEN_READWRITE); //<--Here appears the ERROR
  } catch (SQLiteException e) {
    Log.e("tle99 - check", e.getMessage());
  }
  if (tempDB != null)
      tempDB.close();
  return tempDB != null ? true : false;
}

//copy database to assets folder
public void copyDataBase() throws IOException { 
  try {
    InputStream myInput = context.getAssets().open(DB_NAME);
    String outputFileName = DB_PATH + DB_NAME;
    OutputStream myOutput = new FileOutputStream(outputFileName);

    byte[] buffer = new byte[1024];
    int length;

    while((length = myInput.read(buffer))>0){
      myOutput.write(buffer, 0, length);
    }

    myOutput.flush();
    myOutput.close();
    myInput.close();
  } catch (Exception e) {
   Log.e("tle99 - copyDatabase", e.getMessage());
  }

}

public void openDataBase() throws SQLException {
  String myPath = DB_PATH + DB_NAME;
  myDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}

public void createDataBase() throws IOException {

  boolean dbExist = checkDataBase();

  if (dbExist) {

  } else {
    this.getReadableDatabase();
    try {
      copyDataBase();
    } catch (IOException e) {
      Log.e("tle99 - create", e.getMessage());
    }
  }
}

The error appears when calling the checkDataBase() function (there's a comment next to the line) and as I said it's a SQLite cannot open file. This is the part in the Logcat where I see the error:

03-31 19:09:18.464 21825-21825/? E/SQLiteLog: (14) cannot open file at line 30052 of [b3bb660af9]
03-31 19:09:18.464 21825-21825/? E/SQLiteLog: (14) os_unix.c:30052: (2) open(/data/data/myapp.app.databasetest/databases/mydatabase.db) - 
03-31 19:09:18.466 21825-21825/? E/SQLiteDatabase: Failed to open database '/data/data/myapp.app.databasetest/databases/mydatabase.db'.

I sincerely don't know how to fix it. I've been stuck on it for a couple days now and it's being a real pain to fix. It was working fine until I would reinstall the App, but now it's never working. I don't know what's wrong with my code.

Any help would be much appreciated! Thanks in advance.

how i can insert more rows in this sqlite database and how can i use Autocomplete Textview from it

how i can insert more rows in this sqlite database and how can i use Autocomplete Textview to select longitude and latitude from it this sqlite is very small and i what also to ask if this sqlite i can connect it with json and with mysql server

public class MainActivity3 extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_activity3);
    SQLiteDatabase db;
    db = openOrCreateDatabase( "Temp.db"        , SQLiteDatabase.CREATE_IF_NECESSARY        , null          );
    try {
        final String CREATE_TABLE_CONTAIN = "CREATE TABLE IF NOT EXISTS tbl_Contain ("
                + "ID INTEGER primary key AUTOINCREMENT,"
                + "FNAME TEXT,"
                + "longitude DOUUBLE,"
                + "latitude DOUUBLE,"
                + "info TEXT," + "notes TEXT);";
        db.execSQL(CREATE_TABLE_CONTAIN);
        Toast.makeText(MainActivity3.this, "table created ", Toast.LENGTH_LONG).show();
        String sql =
                "INSERT or replace INTO tbl_Contain (FNAME, longitude, latitude, info,notes) VALUES('nativity charch','31.704415','35.207163','it is an old charch where jesus was born','charch')" ;
        db.execSQL(sql);
        Toast.makeText(MainActivity3.this, "row1 exist ", Toast.LENGTH_LONG).show();
    }
    catch (Exception e) {
        Toast.makeText(MainActivity3.this, "ERROR "+e.toString(), Toast.LENGTH_LONG).show();
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main_activity3, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

Code passing a "null" to DB where there should be a String value

I am writing an app that is pulling info from an SQLite DB and passing it to a list. The code is not finalized, but I am unable to test past a certain point . The error message I am getting is that my table name is a "null" in my SQL Query, but I dont understand why that is happening. I have created a textview within the App that displays the data contained in the String I am passing in. That TextView is showing the correct information. So if the string is working to pass into a TextView, why isnt it working to pass it into a String based SQLQuery?

Specifically, the getBeerDrinkLabels() from the DBHelper is showing "null" for barTableName, which comes from Bar.testingBarSet, which comes from MainActivity.upperCaseName. Bar.testingBarSet shows the correct value in the String that loads into the setBarTester TextView, so why not in the DB Query?

DBHelper Class (Where the SQL Query lives within the public List getBeerDrinkLabels() method)

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

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

public class DBHelper extends SQLiteOpenHelper {

    private static String DB_PATH = "/data/data/com.example.sixth/databases/";
    private static String DB_NAME = "BarSample.db"; 
    private final Context myContext;    
    public static String tableName = "BARS";
    public static String barTableName = Bar.testingBarSet;//Pass in the specific bar from the spinner choice
    public static String drinkType = Bar.setDrinkType;//Use this to pass in selected drink type to SQL query    
    //public static final String KEY_ROWID = "_id";
    //public static final String BARNAME = "Bar Name";
    public static final String BARCITY = "Bar City";
    private SQLiteDatabase myDataBase;


    public DBHelper(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 {
                this.close();
                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) {

    }

    public List<String> getAllLabels(){
        List<String> labels = new ArrayList<String>();

        // Select All Query
        String selectQuery = "SELECT  * FROM " + tableName;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                labels.add(cursor.getString(1) + " " + cursor.getString(2)+ ", " + cursor.getString(3));
            } while (cursor.moveToNext());
        }

        // closing connection
        cursor.close();
        db.close();

        // returning labels
        return labels;

    } // will returns all labels stored in database

    public List<String> getBeerDrinkLabels(){
        List<String> allBeerDrinkLabels = new ArrayList<String>();

        // Select All Query
        String sqlquery="SELECT * FROM "+barTableName + " WHERE DRINKTYPE='Beer';";
        String selectQuery = sqlquery;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                allBeerDrinkLabels.add(cursor.getString(1) + ", " + cursor.getString(2));
            } while (cursor.moveToNext());
        }

        // closing connection
        cursor.close();
        db.close();

        // returning labels
        return allBeerDrinkLabels;

    } // will returns all labels stored in database
}

Main Activity.java (where the String that eventually goes into the Query is created)

package com.example.sixth;
import java.io.IOException;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.database.SQLException;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;


public class MainActivity extends Activity implements
OnItemSelectedListener {
    DBHelper myDB;
    Button selectBar;   
    Spinner spinner;
    static String pullBar,setBar,name, cityState, upperCaseName;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button selectBar = (Button)findViewById(R.id.btnSelectBar);
        myDB = new DBHelper(this);
         // Spinner element
        spinner = (Spinner) findViewById(R.id.spinner);
     // Spinner click listener
        spinner.setOnItemSelectedListener(this);

        try {
            myDB.createDataBase();
        } catch (IOException ioe) {
            throw new Error("Unable to create database");
        }
        try {
            myDB.openDataBase();
        } catch (SQLException sqle) {
            throw sqle;
        }


        // Loading spinner data from database
        loadSpinnerData();

        selectBar.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                pullBar = String.valueOf(spinner.getSelectedItem());
                String[] parts = pullBar.split(" "); //returns an array with the 2 parts
                name = parts[0];

                String nlast = parts[parts.length-2];
                String last = parts[parts.length-1];

                cityState =  nlast+ " " + last;
                upperCaseName=name.toUpperCase();
                setBar = name.toLowerCase();
                Intent i = (new Intent(MainActivity.this, Bar.class));
                startActivity(i);           
            }

        }); 
    }


     private void loadSpinnerData() {
            // database handler
            DBHelper db = new DBHelper(getApplicationContext());

            // Spinner Drop down elements
            List<String> lables = db.getAllLabels();

            // Creating adapter for spinner
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, lables);

            // Drop down layout style - list view with radio button
            dataAdapter
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

            // attaching data adapter to spinner
            spinner.setAdapter(dataAdapter);
        }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        // TODO Auto-generated method stub

    }


    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        // TODO Auto-generated method stub

    }

}

Bar.java (Where the string going in to the Query is finalized)

public class Bar extends Activity{
    String setBarTest = MainActivity.setBar;
    static String testingBarSet = MainActivity.upperCaseName;
    String barNameHolder, picHolder, barContactHolder, barPhoneHolder; 
    int imageInt, textInt1,textInt2, textInt3, textInt4;
    TextView setBarName, setBarContact,setBarPhone, setBarHours;
    static TextView setBarTester;
    ImageView barPic;
    Button viewAll, beer, wine, mixedDrinks, other, specials, getTaxi;
    static String setDrinkType;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bar);

        Button viewAll = (Button)findViewById(R.id.btnviewAll); 
        Button specials = (Button)findViewById(R.id.btnSpecials);   
        Button getTaxi = (Button)findViewById(R.id.btnTaxi);

        barPic = (ImageView) findViewById(R.id.barPic);
        String picHolder = "drawable/"+setBarTest;      
        imageInt = getResources().getIdentifier(picHolder, null, getPackageName());
        barPic.setImageResource(imageInt);

        setBarName = (TextView)findViewById(R.id.barName);
        String barNameHolder = "@string/"+setBarTest;
        textInt1 = getResources().getIdentifier(barNameHolder, null, getPackageName());
        setBarName.setText(textInt1);

        setBarContact = (TextView)findViewById(R.id.barContact);
        String barContactHolder = "@string/"+setBarTest+"Contact";
        textInt2 = getResources().getIdentifier(barContactHolder, null, getPackageName());
        setBarContact.setText(textInt2);

        setBarPhone = (TextView)findViewById(R.id.barPhone);
        String barPhoneHolder = "@string/"+setBarTest+"Phone";
        textInt3 = getResources().getIdentifier(barPhoneHolder, null, getPackageName());
        setBarPhone.setText(textInt3);

        setBarHours = (TextView)findViewById(R.id.barHours);
        String barHoursHolder = "@string/"+setBarTest+"Hours";
        textInt4 = getResources().getIdentifier(barHoursHolder, null, getPackageName());
        setBarHours.setText(textInt4);

        setBarTester = (TextView)findViewById(R.id.setBarTester);
        String barTesterHolder = testingBarSet ;
        //int textInt5 = getResources().getIdentifier(barTesterHolder, null, getPackageName());
        setBarTester.setText(barTesterHolder);

        viewAll.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = (new Intent(Bar.this, Drinks.class));
                startActivity(i);           
            }

        });

        specials.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = (new Intent(Bar.this, NoResult.class));
                startActivity(i);           
            }

        });

        getTaxi.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = (new Intent(Bar.this, Taxi.class));
                startActivity(i);           
            }

        });


    }
}

Drinks.java (Where the DB call is made that is giving the Null value)

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.ListView;
import android.widget.Toast;

public class Drinks extends Activity {
    // TextView drinkHolder;
    public static String drinkType = DBHelper.drinkType;
    String drinkTestHolder = "";
    ExpandableListAdapter listAdapter;
    ExpandableListView expListView;
    List<String> listDataHeader;
    HashMap<String, List<String>> listDataChild;


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drinks);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            drinkType = bundle.getString("sample_name");
        }
        // get the listview
        expListView = (ExpandableListView) findViewById(R.id.lvExp);

        // preparing list data
        prepareListData();

        listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

        // setting list adapter
        expListView.setAdapter(listAdapter);

    }

    private void prepareListData() {
        listDataHeader = new ArrayList<String>();
        listDataChild = new HashMap<String, List<String>>();


        // Adding child data

         listDataHeader.add("Beer"); 
         listDataHeader.add("Mixed Drinks");
         listDataHeader.add("Other Drinks"); 
         listDataHeader.add("Shots");
         listDataHeader.add("Wine");

         //Get Beer entries
         DBHelper db = new DBHelper(getApplicationContext());
         List<String> beerLables = db.getBeerDrinkLabels();


        // Adding child data
        List<String> beer = new ArrayList<String>();

        //beer.add("The Shawshank Redemption");
        for (int i = 0; i < beerLables.size(); i++) {
            beer.add(beerLables.get(i));
        }

        /*
           beer.add("The Godfather");
         * beer.add("The Godfather: Part II"); beer.add("Pulp Fiction");
         * beer.add("The Good, the Bad and the Ugly"); beer.add(
         * "The Dark Knight"); beer.add("12 Angry Men");
         */

        List<String> wine = new ArrayList<String>();
        /*
         * wine.add("The Conjuring"); wine.add("Despicable Me 2");
         * wine.add("Turbo"); wine.add("Grown Ups 2"); wine.add("Red 2");
         * wine.add("The Wolverine");
         */

        List<String> shots = new ArrayList<String>();
        /*
         * shots.add("2 Guns"); shots.add("The Smurfs 2"); shots.add(
         * "The Spectacular Now"); shots.add("The Canyons"); shots.add(
         * "Europa Report");
         */

        List<String> mixedDrinks = new ArrayList<String>();
        /*
         * mixedDrinks.add("2 Guns"); mixedDrinks.add("The Smurfs 2");
         * mixedDrinks.add("The Spectacular Now"); mixedDrinks.add("The Canyons"
         * ); mixedDrinks.add("Europa Report");
         */

        List<String> otherDrinks = new ArrayList<String>();
        /*
         * otherDrinks.add("2 Guns"); otherDrinks.add("The Smurfs 2");
         * otherDrinks.add("The Spectacular Now"); otherDrinks.add("The Canyons"
         * ); otherDrinks.add("Europa Report");
         */

        listDataChild.put(listDataHeader.get(0), beer); // Header, Child data
        listDataChild.put(listDataHeader.get(1), wine);
        listDataChild.put(listDataHeader.get(2), shots);
        listDataChild.put(listDataHeader.get(3), mixedDrinks);
        listDataChild.put(listDataHeader.get(4), otherDrinks);
    }
}

I originally had the DBHelper pulling the String right from MainActivity, but was getting Null value no matter where I put it.

LogCat

 FATAL EXCEPTION: main
 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sixth/com.example.sixth.Drinks}: android.database.sqlite.SQLiteException: near "null": syntax error (code 1): , while compiling: SELECT * FROM null WHERE DRINKTYPE='Beer';
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
    at android.app.ActivityThread.access$600(ActivityThread.java:141)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:5103)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:525)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: android.database.sqlite.SQLiteException: near "null": syntax error (code 1): , while compiling: SELECT * FROM null WHERE DRINKTYPE='Beer';
    at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
    at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
    at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
    at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
    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:1314)
    at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1253)
    at com.example.sixth.DBHelper.getBeerDrinkLabels(DBHelper.java:180)
    at com.example.sixth.Drinks.prepareListData(Drinks.java:62)
    at com.example.sixth.Drinks.onCreate(Drinks.java:38)
    at android.app.Activity.performCreate(Activity.java:5133)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175) 

sqlite column name quoting (feature or bug)

I bumped into something that looks odd to me, but may be I misuse sqlite3.

create table t (v[0] text);
insert into t values('aa');
select * from t;
v
--------
aa
pragma table_info('t')
cid      name     type   no dfl pk
-------- -------- ------ -- --- ----------
0        v        0      0      0
.schema t;
CREATE TABLE t (v[0] text);

Looks like thought the column name is correctly entered into the schema, it is 'wrongly' handled by create/select who silently truncate the column name without any reports.

Now we could think that such odd column name should be entered quoted into the schema, but I can't find a way to do it.

create table u ('v[0]' text);
insert into u values('aa');
select * from u;
v[0]
--------
aa
$ q pragma table_info('u')
cid      name     type   no dfl pk
-------- -------- ------ -- --- ----------
$        v[0]     text   0      0
$ q .schema u
CREATE TABLE u ('v[0]' text);

Hurray, the schema looks good, SELECT * is happy, but now I get stuck about how to use this column.

select v[0] from u;
SQL error 1 : no such column: v
select 'v[0]' from u
'v[0]'
----------
v[0]
select [v[0]] from u
SQL error 1 : unrecognized token: "]"

I really to to have [] in the column name and I don't see any docco saying we can't (columns names are generated in my case)

Thanx for any advise. Cheers Phi

the file information in the database are displayed

I'm beginning rails and following some tuto, I have a problem of display in my home page. All the informations of my db appear (as you can see on the photo). I don't know if it is a setting of my software (SQLitebrowers), or

Photo of the Error !

views/layout/application :

<!DOCTYPE html>
<html>

<head>
  <title>Photo</title>
  <%=s tylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track'=>true %>
    <%=j avascript_include_tag 'application', 'data-turbolinks-track'=>true %>
      <%=c srf_meta_tags %>
</head>

<body>

  <div class="navbar navbar-default">
    <div class="container">
      <div class="navbar-header">
        <%=l ink_to "KÜTO", root_path, class: "navbar-brand"%>
      </div>
      <ul class="nav navbar-nav">
        <li>
          <%=l ink_to "Inscription", new_user_registration_path %>
        </li>
        <li>
          <% if user_signed_in? %>
            <%=l ink_to "Deconnection", destroy_user_session_path, method: :delete, data: {confirm: "Confirmez la deconnection ?"} %>
              <%else%>
                <%=l ink_to "Connection", new_user_session_path %>
                  <% end %>
        </li>
        <% if user_signed_in? %>
          <p>
            <%=l ink_to "Nouveau Plat", new_message_path, class: "navbar-right navbar-text navbar-link"%>
          </p>
          <%end%>
      </ul>
    </div>

  </div>
  <p class="notice">
    <%=notice%>
  </p>
  <p class="alert">
    <%=alert%>
  </p>

  <%=y ield %>

</body>

</html>

and views/messages/index :

<%= @messages.each do |message| %>
<h2> <%= message.title %></h2>
<%= link_to "Voir le message", message_path(message), class: "btn btn-default" %>
<% end %>

<br>

<%= link_to "New Message", new_message_path %>

Have you ever had it? How can I fix it ? I thank you ahead of time that you can help me

Have a good day

In Android studio how to delete row using sqllite

I wrote a code to delete a row. It is not deleting a row. It is showing error in toasr. Suppose value is abc no such column: abc(code 1):, while compliling: Delete from FACULTY where NAME = abc; is comming. What should i do? java file is given below.

package com.adu.collegemanagementsystem;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class DeleteFaculty extends AppCompatActivity    {
EditText id,name;
Button submit;
//MyDBHandler dbHandler;
SQLiteDatabase db;
ContentValues cv;
Cursor c;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_delete_faculty);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    id = (EditText) findViewById(R.id.id);
    name = (EditText) findViewById(R.id.name);
    submit= (Button) findViewById(R.id.add);

    try {
         db=openOrCreateDatabase("CMS",MODE_PRIVATE,null);


          db.execSQL("create table IF NOT EXISTS FACULTY(FID INTEGER PRIMARY      KEY AUTOINCREMENT,"
                + "NAME varchar(50) NOT NULL,"
                + "ADDRESS varchar(50),"
                + "QUALIFICATION varchar(50) ,"
                + "SALARY varchar(50) NOT NULL,"
                + "USERNAME varchar(50) ,"
                + "PASSWORD varchar(100))");

        Toast toast = Toast.makeText(DeleteFaculty.this, "Database Created   Sucessfull ",Toast.LENGTH_LONG);
        toast.show();
    }
    catch (Exception e){

         Toast toast = Toast.makeText(DeleteFaculty.this, "DB not created.",Toast.LENGTH_SHORT);
        toast.show();

    }


}

public void SubmitClicked(View view){

        String fname= name.getText().toString();
        if(fname.isEmpty()){
            Toast toast = Toast.makeText(DeleteFaculty.this, "Please Enter Faculty Name.",Toast.LENGTH_SHORT);
            toast.show();
            name.setFocusable(true);
            name.requestFocus();
        }

        else
        {
            cv=new ContentValues();
            cv.put("NAME", fname);
            try {
                db.execSQL("Delete from FACULTY where NAME = "+fname+";");
              // db.delete("FACULTY", "NAME = " + fname, null);
                Toast toast = Toast.makeText(DeleteFaculty.this, " Faculty Deleted Successfully  .",Toast.LENGTH_SHORT);
                toast.show();


            }

             catch (Exception e){
                Toast.makeText(DeleteFaculty.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();

             }




        }
    }
  }

Using existing SQLite database in Cayenne

I've been playing around with Apache Cayenne in an IntelliJ project. I configure the JDBC in the datanode like in the image but it gives me an error the screen

I have the Cayenne project stored in my IntelliJ project folder, as well as the SQLite database "data.db".

Can anyone help me figuring out this?

SQLiteOpenHelper switching database version

Im trying to switch from different database versions. However, the application keeps crashing when I try to access lower database version when my recent access was a higher database version.

Here is the code

public class DbHelper extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 46;
    // Database Name
    private static final String DATABASE_NAME = "triviaQuiz";
    // tasks table name
    private static final String TABLE_QUEST = "quest";
    // tasks Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_QUES = "question";
    private static final String KEY_ANSWER = "answer"; //correct option
    private static final String KEY_OPTA= "opta"; //option a
    private static final String KEY_OPTB= "optb"; //option b
    private static final String KEY_OPTC= "optc"; //option c
    private SQLiteDatabase dbase;
    public DbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        dbase=db;
        String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_QUEST + " ( "
                + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_QUES
                + " TEXT, " + KEY_ANSWER+ " TEXT, "+KEY_OPTA +" TEXT, "
                +KEY_OPTB +" TEXT, "+KEY_OPTC+" TEXT)";
        db.execSQL(sql);
        addQuestions();
        //db.close();
    }
    private void addQuestions()
    {
        Question q1=new Question("What does ICT stands for?","Individual Computing Techniques", "Information Computer Technology", "Information Computer Tutorial", "Information Computer Technology");
        this.addQuestion(q1);
        Question q2=new Question("Information Technology is also classified as the Science and Art of?", "Recording and Storage", "Past Time", "Information", "Recording and Storage");
        this.addQuestion(q2);
        Question q3=new Question("Based on the lesson, what are the things that you might experience when interacting with other people in the internet?","Free load", "Time Leisure","Cyber Bullying", "Cyber Bullying" );
        this.addQuestion(q3);
        Question q4=new Question("What are the things you need to consider before turning off the computer?", "Make sure to save all your work", "Make sure to log out your account", "Leave a file open","Make sure to log out your account");
        this.addQuestion(q4);
        Question q5=new Question("Password must be?","Easy to guess","Easy to remember","Unique and hard to guess by other people","Unique and hard to guess by other people");
        this.addQuestion(q5);
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUEST);
        // Create tables again
        onCreate(db);
    }
    // Adding new question
    public void addQuestion(Question quest) {
        //SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_QUES, quest.getQUESTION());
        values.put(KEY_ANSWER, quest.getANSWER());
        values.put(KEY_OPTA, quest.getOPTA());
        values.put(KEY_OPTB, quest.getOPTB());
        values.put(KEY_OPTC, quest.getOPTC());
        // Inserting Row
        dbase.insert(TABLE_QUEST, null, values);
    }
    public List<Question> getAllQuestions() {
        List<Question> quesList = new ArrayList<Question>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_QUEST;
        dbase=this.getReadableDatabase();
        Cursor cursor = dbase.rawQuery(selectQuery, null);
        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Question quest = new Question();
                quest.setID(cursor.getInt(0));
                quest.setQUESTION(cursor.getString(1));
                quest.setANSWER(cursor.getString(2));
                quest.setOPTA(cursor.getString(3));
                quest.setOPTB(cursor.getString(4));
                quest.setOPTC(cursor.getString(5));
                quesList.add(quest);
            } while (cursor.moveToNext());
        }
        // return quest list
        return quesList;
    }
    public int rowcount()
    {
        int row=0;
        String selectQuery = "SELECT  * FROM " + TABLE_QUEST;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        row=cursor.getCount();
        return row;
    }

Now, I have 5 java file of these and each have a different database version. When Im switching databases the application keeps crashing. Is there anyway to fix this?

Here is the logcat

03-31 22:45:20.793 25098-25098/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.doepiccoding.navigationdrawer, PID: 25098
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.doepiccoding.navigationdrawer/com.android.pet.view.QuizActivity1}: android.database.sqlite.SQLiteException: Can't downgrade database from version 46 to 45
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
   at android.app.ActivityThread.access$800(ActivityThread.java:135)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:136)
   at android.app.ActivityThread.main(ActivityThread.java:5021)
   at java.lang.reflect.Method.invokeNative(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:515)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:827)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)
   at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.sqlite.SQLiteException: Can't downgrade database from version 46 to 45
   at android.database.sqlite.SQLiteOpenHelper.onDowngrade(SQLiteOpenHelper.java:361)
   at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:255)
   at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:188)
   at com.android.pet.view.DbHelper1.getAllQuestions(DbHelper1.java:80)
   at com.android.pet.view.QuizActivity1.onCreate(QuizActivity1.java:35)
   at android.app.Activity.performCreate(Activity.java:5231)
   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1090)
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 
   at android.app.ActivityThread.access$800(ActivityThread.java:135) 
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
   at android.os.Handler.dispatchMessage(Handler.java:102) 
   at android.os.Looper.loop(Looper.java:136) 
   at android.app.ActivityThread.main(ActivityThread.java:5021) 
   at java.lang.reflect.Method.invokeNative(Native Method) 
   at java.lang.reflect.Method.invoke(Method.java:515)

SQLite - Select with JOINs to Many-to-Many and One-to-Many

I've got a simple recipe database that I'm attempting to write a query for that will pull in a recipe, as well as all the associated ingredients and steps. The recipe itself has a many-to-many relationship with ingredients (to promote re-use of ingredient entries) and a one-to-many relationship with steps (chances are one recipe does not have an identical step to another, so no need for re-use here).

The database is setup like so:

CREATE TABLE Recipe (
    _id INTEGER PRIMARY KEY,
    recipe_name TEXT UNIQUE NOT NULL
);

CREATE TABLE Ingredient (
    _id INTEGER PRIMARY KEY,
    ingredient TEXT UNIQUE NOT NULL
);

CREATE TABLE RecipeIngredient (
    _id INTEGER PRIMARY KEY,
    recipe_id INTEGER,
    ingredient_id INTEGER,
    amount REAL,
    FOREIGN KEY (recipe_id) REFERENCES Recipe(_id),
    FOREIGN KEY (ingredient_id) REFERENCES Ingredient(_id)
);

CREATE TABLE Step (
    _id INTEGER PRIMARY KEY,
    instruction TEXT NOT NULL,
    number INTEGER NOT NULL,
    recipe_id INTEGER,
    FOREIGN KEY (recipe_id) REFERENCES Recipe(_id)
);

I'm able to pull all the information for a given Recipe by _id using INNER JOINS on all the tables (which creates a ton of duplicate data), but where I'm stuck is how can I group/order this to make the data useful without requiring additional parsing of the results to get a meaningful object? Would this just be better to do in 2 queries (one for the ingredients and one for the steps)?

UPDATE

Adding some sample data that comes back from selecting one recipe ID, doing INNER JOINs between the tables (ordered by ingredient/step number):

|| recipe ||    || ingredient||  ||step||   ||step number||
"Recipe One"    "Ingredient 1"   "Step 1"         "1"
"Recipe One"    "Ingredient 1"   "Step 2"         "2"
"Recipe One"    "Ingredient 1"   "Step 3"         "3"
"Recipe One"    "Ingredient 2"   "Step 1"         "1"
"Recipe One"    "Ingredient 2"   "Step 2"         "2"
"Recipe One"    "Ingredient 2"   "Step 3"         "3"
"Recipe One"    "Ingredient 3"   "Step 1"         "1"
"Recipe One"    "Ingredient 3"   "Step 2"         "2"
"Recipe One"    "Ingredient 3"   "Step 3"         "3"

how to generate a number of rows based on field value in SQLite

I'm going over lots of old code and see how much I can optimize them using new stuff I learned. One feels like there is a cleaner way to do it, but I can't figure out what!

I do have the following tables that can be summarize like:

Table summary
-------------------------    
category  | group | rows | priority
------------------------
1         | 1     | 3    | 1
2         | 1     | 3    | 2
3         | 2     | 2    | 1
4         | 2     | 2    | 2
5         | 2     | 2    | 3

Table article
-------------------------------    
article   | category | somedata
-------------------------------
1         | 1        | blabla
2         | 1        | blabla
3         | 2        | blabla
4         | 2        | blabla
5         | 1        | blabla
6         | 1        | blabla
7         | 1        | blabla
8         | 2        | blabla
9         | 3        | blabla
10        | 3        | blabla
11        | 3        | blabla
12        | 4        | blabla
13        | 4        | blabla
14        | 4        | blabla
15        | 4        | blabla
16        | 5        | blabla
17        | 5        | blabla
18        | 5        | blabla
19        | 5        | blabla

My current approach is to do it in two requests like (super simplified for reading purpose)

$category = $db->query("SELECT category, group, rows FROM summary ORDER BY 
group, priority");
$feed = $db->prepare("SELECT article, someData FROM article 
WHERE category = :category LIMIT 0,:rows");

foreach($category as $cat){
    $feed->bindParam(":category",$cat['category'], SQLITE3_INT);
    $feed->bindParam(":rows",$cat['rows'], SQLITE3_INT);
    $feed->execute();
    //some code,exception and data processing handling 
}

Is it possible to do it in only one request straight in SQLite3 and get something like the following response ?

-------------------------    
category  | group | article | someData
------------------------
1         | 1     | 1       | blabla 
1         | 1     | 2       | blabla 
1         | 1     | 5       | blabla 
2         | 1     | 3       | blabla 
2         | 1     | 4       | blabla 
2         | 1     | 8       | blabla 
3         | 2     | 9       | blabla 
3         | 2     | 10      | blabla 
4         | 2     | 12      | blabla 
4         | 2     | 13      | blabla 
5         | 2     | 16      | blabla 
5         | 2     | 17      | blabla 

Show data fetched from database on a different page? (JavaScript/SQLite)

I am having trouble figuring out how to display the data fetched from the SQLite database onto another page.

At the moment I am using a div (responsediv) that the results are displayed within, however this div is on the same page as the search textfields, so instead I want the user to be directed to another page which will display the results.

For example, the page that the user searches on is page5, and let's say I want the data from the database to be displayed on page6 in the "datadisplay" div.

I am using html, javascript, Cordova/Phonegap and JQuery mobile.

Please see my code below.

JavaScript -

    function fetchEvent()
             {
          db = window.openDatabase("SoccerEarth", "2.0", "SoccerEarthDB", 2*1024*1024);
          db.transaction(foundEvent, errorCB);
         }

          function foundEvent(tx)
            {
            var TitleT = document.getElementById("texttitle").value;
           tx.executeSql("SELECT * FROM SoccerEvents WHERE Title LIKE '%" + TitleT + "%'", [], renderEvent);
                        }

           function renderEvent(tx,response)
           {
          var div = document.getElementById("responsediv");

       var temp = "<table border=\"1\"><tr><th>Title</th><th>Location</th><th>NoPeople</th><th>Date</th><th>Description</th></tr>";
          alert(response.rows.length);
          for(var i=0;i<response.rows.length;i++)
          {
          temp += "<tr><td>" + response.rows.item(i).Title + "</td><td>" + response.rows.item(i).Location + "</td><td>" + response.rows.item(i).NoPeople + "</td><td>" + response.rows.item(i).Date + "</td><td>" + response.rows.item(i).Description + "</td></tr>";
          div.innerHTML = temp;
          }
}

HTML -

<div data-role="page" id="page5" data-theme="d">
    <div data-role="header">
        <h1>Search Soccer Event</h1>
    </div>
    <div data-role="content">
        <form onsubmit="fetchEvent(); return false;">
            <div class="ui-field-contain">
                <label for="texttitle">Title</label>
                <input type="text" id="texttitle">
                <label for="select-native-2">Location</label>
                <select name="select-native-2" id="select-native-2" data-mini="true">
                    <option value="" disabled selected>Select your option</option>
                    <option value="1">Tower Hamlets</option>
                    <option value="2">Greenwich</option>
                    <option value="3">Islington</option>
                    <option value="4">Bromley</option>
                    <option value="4">Hackney</option>
                    <option value="4">Lewisham</option>
                </select>
                <br>
                <label for="dateD" data-position="left">Date</label>
                <input type="date" id="dateD"   />
                <br>
                <input type="submit" value="Display Results">
            </div>
            <div id="responsediv">
            </div>
        </form>
    </div>
</div>

How To encrypt SQLite database in ionic

I am programming the hybrid application using ionic. To store the data on the device i am using sqlite plugin of ngcordova. Can somebody give me advice, how to encrypt the database file of sqlite ?

thank you!

Inserting an API data to the SQliteDatabase

I have an JSON API of Catelog Website. I am fetching the data with AsyncTask and inserting it to the sqlitedb. I made two tables in my db 1. category 2.products I fetched all the data separately for both table. Now I want to display category table data to gridView of mainActivity and onItemClick this will go to the class productList. for this productList class, should be display a listview of the product array data for the clicked item. One more query is when I close the app and reOpen the app, the data is again fetched and inserted into db. How to remove Data duplication.

My JSON Data is like:

[
{
id: 12,
name: "Electronices",
slug: "electronic",
description: "All Kind Of Electronic Devices",
parent_id: 0,
lft: null,
rgt: null,
depth: null,
created_at: "2016-03-07 13:14:23",
updated_at: "2016-03-07 13:14:23",
products: [
{
id: 14,
name: "samsung fame 2",
slug: "samsung_fame_2",
short_description: "",
has_offer: 0,
has_prescription: 0,
offer_description: "",
description: "",
price: "8000.00",
old_price: null,
shipping: null,
status: "",
stock_status: "",
weight: "",
meta_title: "",
meta_keywords: "",
meta_description: "",
created_at: "2016-03-07 13:27:06",
updated_at: "2016-03-07 13:27:06",
pivot: {
categorie_id: 12,
product_id: 14
},
photos: [
{
id: 14,
product_id: 14,
cover: 0,
image: "images/products/14/download.jpg",
label: "download.jpg",
sort_order: 1,
created_at: "2016-03-07 13:27:10",
updated_at: "2016-03-07 13:27:10"
},
{
id: 15,
product_id: 14,
cover: 0,
image: "images/products/14/chair.jpg",
label: "chair.jpg",
sort_order: 2,
created_at: "2016-03-07 13:27:20",
updated_at: "2016-03-07 13:27:20"
}
]
},
{
id: 16,
name: "Television sets",
slug: "Tv",
short_description: "",
has_offer: 0,
has_prescription: 0,
offer_description: "",
description: "",
price: "15000.00",
old_price: null,
shipping: null,
status: "",
stock_status: "",
weight: "",
meta_title: "",
meta_keywords: "",
meta_description: "",
created_at: "2016-03-07 13:27:56",
updated_at: "2016-03-07 13:27:56",
pivot: {
categorie_id: 12,
product_id: 16
},
photos: [
{
id: 18,
product_id: 16,
cover: 0,
image: "images/products/16/tv.jpg",
label: "tv.jpg",
sort_order: 2,
created_at: "2016-03-07 13:28:07",
updated_at: "2016-03-07 13:28:07"
}
]
}
]
},
{
  "Data for Furniture, like aboove"
}
]

Core Data: SQLite not being updated immediately

There are two Entities- Document and Page. Document has a one-to-many relationship with Page.

I save the managed object context when I add document. At this point, there are no pages in them. While debugging I found that the writer context's save method does get called and is executed without error. I close and reopen the app and I can't find the previously saved Document objects. But, if I add a page in one of the document, then, the Document object appear in the table. I use a tool to view the SQLite file but my observation is not based on what I see in the tool. Even when I debug and see the number of documents present, I get 0 back when there is no page in them.

I am guessing that the Persistent Store Coordinator is doing some kind of optimization to write in batch. Can I force it to write and update the persistent store immediately? Is there a option that I can add while calling addPersistentStoreWithType on the persistent store object?

Note: Just FYI, I use this pattern to organize the Managed Object Context(s)

Android SQLiteException parameter

I'm working very well with the SQLite database, but now I have a problem while using a query. For example, if use a query like this:

SQLiteDatabase db = mHelper.getReadableDatabase();

    String parameter = mypar;
    String sql = SELECT color, name FROM table WHERE name = '" + parameter + "';
    Cursor c = db.rawQuery(sql, null);
   while (c.moveToNext()) {
   String color = c.getString(0);
   String name = c.getString(1);
}
        c.close();
        db.close();

Everything works fine

But if the parameter has an apex

String parameter = mypar';

I get an exception

Caused by: android.database.sqlite.SQLiteException: near "r": syntax error (code 1):

How can I solve this problem? Thank you

How can custom order the sqlite database?

I have 6700 records in sqlite database and when I load them in my phone ListView it simply displays them as respect to their row_ids. what I want is it first display the records from 2700 to 6700 and then the remaining first 2699.

How can I do that?

I can add another column with the name say OrderBy an add values Int 1 - 4000 to records from 2700 to 6700 and then 4001 to 6700 for the first 2699 records but how can I do the dynamically?

Thanks

Repeated message like this [duplicate]

This question already has an answer here:

You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings.

Why am I getting amessage like this while loading data to sqlite from python

Sqlite: Fetching records where 1 column exists more than once

I have a table that looks like this:

+---------+--------+
|  Food   | Color  |
+---------+--------+
| apple   | green  |
| banana  | yellow |
| salad   | green  |
| lemon   | yellow |
| coconut | brown  |
+---------+--------+

Based on the Color column, I would like to fetch those records where the Color column exists more than once.

In my example, the record apple, banana, salad and lemon should be fetched, but not coconut (because the color brown exists only once).

But I am not sure what the select statement would be.

I was thinking about something like SELECT * FROM mytable WHERE COUNT(color) > 1, but this is not right, I think.