lundi 9 mai 2016

Adding button which can create data

i just join my job and the ask me to create an POS app. i did about most of thing but i am stuck in database. and also how to create same pattern they want. and a also a button which can create another button which had multi field.

Application is slow after install on another pc

I have build a WPF application with SQLite. After create setup project in visual studio and install it on my developer machine, app works perfect. But when my client install it on another computer it's works very slow. I added project output and SQLite.Interop.dll for database to setup project. Also one of my .dll is COM dll.

This application communicate only with SQLite database.

I have noticed that application works fine but with admin rights on client computer.

What can be the reason of this?

Would this RESTful iOS login system be secure?

So I have been thinking about a way to make a secure restful API for ios logins.

This is what my teacher and I have come up with:

  1. The Client (swift program) initializes the connection with the server.
  2. The Server returns a "shared secret" (ex. +40) and a hash of a random string of letters and numbers.
  3. The Client then hashes the Username and Password (separate) and sends it back with the hash of: hash + "the shared secret".
  4. After the Server sends data (step 2) the server hashes [hash + "shared secret"] and then updates it in the db
  5. The Server then receives the hashed value from the Client and checks the db to see if it matches
  6. The db will also have a timestamp that if not updated frequently enough there will be a function that runs through the db and drops the items that are no longer used.
  7. For every request after the login the bearer token is sent.

The bearer token will follow this formula: Request verification token = hash [ (original hash) + (shared secret) * (# of requests) ]

Only fetch date from datetime value of db sqlite android? Compare with current date and the then display time of the saved value?

I am trying to fetch date from my db, where its stored with time. I want to compare the date with in my adapter, if the date is equal to the current date then adapter fetch time only of the corresponding date, and if date is not equal to the current date then adapter display the date of the corresponding value,

This is how I am inserting date+time in DB:

long date = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("MMM-dd-yyyy h:mm:a");
String dateString = sdf.format(date);
s.setTime(dateString);
Log.i("result", s.getTime());
DatabaseHandler db = new DatabaseHandler(this);
db.creatScan(new Scan(s.getMsg().toString(), s.getTime().toString()));
db.close();

In my Adapter:

 TextView details = (TextView)convertView.findViewById(R.id.scandetails);

        TextView times = (TextView)convertView.findViewById(R.id.scanTime);

        times.setText(scan.getTime());

This is the Result:

enter image description here

What I want is: It should only display the time, if the date is equal to the current date, else it should only display the date.

I am trying this if/else statement but its not working, Your help would be very appreciated, thanks in advance

long date = System.currentTimeMillis();

SimpleDateFormat sdfDate = new SimpleDateFormat("MMM-dd-yyyy");

String dateString = sdfDate.format(date);

Log.i("date", dateString);

SimpleDateFormat sdfTime = new SimpleDateFormat("h:mm:a");

String timeString = sdfTime.format(date);

Log.i("date", timeString);

if(scan.getTime().equals(dateString)){

            times.setText(dateString);
    Log.i("data", timeString);
}else {
    String time =  scan.getTime().toString();
    Log.i("date", time);
    times.setText(scan.getTime());
}

Removing and creating PersistentStore and sqlite database

I'm working on an app that exchanges data with a server, and the mobile device has an option to wipe the database clean. I've looked around here and I found out I'm using the same code that's been suggested.

BOOL removedPS = [self.persistentStoreCoordinator removePersistentStore:store error:&error];
BOOL removedSqlite = [[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];

I use the two BOOLs to check if the operations have been made correctly and everything seems to be working smooth. Even the double check

[[NSFileManager defaultManager] fileExistsAtPath:[storeURL path]]

says the file has been deleted. After that, I want to re-create Persistent Store and sqlite:

NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                                 [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                                 [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error])
{
   //ouch :/
}

but the addPersistentStoreWithType keeps on returning a "false" flag. Same goes with the sqlite: I try to copy a fresh .sqlite database, but I keep getting a "nil" for the NSString *param variable, and I can't understand why.

NSError* err = nil;
                NSBundle *bundle = [NSBundle mainBundle];
                NSString *path = @"BaseScope";
                NSString *type = @"sqlite";
                NSString *param = [bundle pathForResource:path ofType:type];

                //NSURL *preloadURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"BaseScope" ofType:@"sqlite"]];
                //NSURL *preloadURL = [NSURL fileURLWithPath:[bundle pathForResource:path ofType:type]];
                if (param != nil)
                {
                    NSURL *preloadURL = [NSURL fileURLWithPath:param isDirectory:false];

                    if (![[NSFileManager defaultManager] copyItemAtURL:preloadURL toURL:storeURL error:&err])
                    {

                    }
                }

I always worked in the .NET environment and this is really puzzling me, but knocking the head against the monitor won't work. Any help appreciated. Thanks in advance.

Using multiple cursor OR using same cursor for multiple queries

I want to fetch data from multiple table in my activity having 2 Listviews and some EditTexts.

I want to fetch data in EditText from Table 1 And fetch data in ListView1 from Table 2 and data from Table 3 into ListView2.

Problem is : i can fetch data through cursor from table 1. But I can't fetch data from table2 using same cursor OR new Cursor.

Table have data but Cursor.MoveToFirst returns false.

public class Details extends AppCompatActivity {

TextView name,num,cty,det;
Button btn_debit,btn_credit;
SQLiteDatabase db;
Cursor c;
int id;
ListView dbList,crList;
private ArrayList<HashMap<String,String>> arrayList;

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

    id = Integer.parseInt(getIntent().getExtras().getString("name"));

    name = (TextView)findViewById(R.id.textView6);
    num = (TextView)findViewById(R.id.textView7);
    cty = (TextView)findViewById(R.id.textView8);
    det = (TextView)findViewById(R.id.textView9);

    btn_debit = (Button)findViewById(R.id.jama);
    btn_credit = (Button)findViewById(R.id.udhar);

    dbList = (ListView)findViewById(R.id.ListDebit);
    crList = (ListView)findViewById(R.id.ListCredit);

    arrayList = new ArrayList<HashMap<String, String>>();

    // tv = (TextView)findViewById(R.id.textView6);
    //tv.setText(getIntent().getExtras().getString("name"));
    db = openOrCreateDatabase("AccountsDB", Context.MODE_PRIVATE,null);

    c=db.rawQuery("SELECT c_name , c_mno , c_detail , c_city FROM customers where c_id="+id,null);
    try {
        if (c!=null){
            if (c.moveToFirst()){
                name.setText(c.getString(0));
                num.setText(c.getString(1));
                cty.setText(c.getString(3));
                det.setText(c.getString(2));
            }
        }
    }catch (Exception e){

    }finally {
        c.close();
    }

    Cursor cursor = db.rawQuery("SELECT * FROM debit_master",null);
    try{
        if (cursor!=null){
            if (cursor.moveToFirst()){
                Map<String,String> tem  = new HashMap<String ,String>();
                tem.clear();
                arrayList.clear();
                dbList.setAdapter(null);
                int cnt = cursor.getCount();
                Toast.makeText(getApplicationContext(),""+cnt,Toast.LENGTH_SHORT).show();
                do {

                    tem = new HashMap<String,String>();
                    tem.clear();

                    tem.put(FIRST_COLUMN, cursor.getString(0));
                    tem.put(SECOND_COLUMN,cursor.getString(1));
                    tem.put(THIRD_COLUMN,cursor.getString(2));
                    arrayList.add((HashMap<String, String>) tem);
                }while (cursor.moveToNext());
            }
        }

    }catch (Exception ex){
        Toast.makeText(getApplicationContext(),""+ex,Toast.LENGTH_LONG).show();
    }


    ListViewAdapter adapter = new ListViewAdapter(this,arrayList);
    dbList.setAdapter(adapter);


    btn_debit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Details.this,Debit.class);
            intent.putExtra("cid",id);
            Details.this.startActivity(intent);
        }
    });

}

}

What's meaning of this my code?

I hope your help the coding. Now i connect the android studio in database. But start a coding don't know error in my program. So I check a php file and check the programming coding isn't not error and Execute a program. enter image description here

Show the picture, Can you see the blue text code? Execute a program and writing a code in select part. But, alert a this word in my program

"05-09 13:32:44.533 325-333/? W/genymotion_audio: out_write() limiting sleep time 46802 to 39909".

What's meannig this code???

IN clause in objective c

Hi i am using "IN" clause in objective c but this is not able to get data.

SELECT * FROM database WHERE colum1!=0 AND colum2!=0 AND colum3 IN ('Allah','is');

for this query code is i am using

NSArray* serch = [NSArray arrayWithObjects:@"Allah",@"is",nil];
    str1=[NSString stringWithFormat:@"SELECT * FROM database WHERE colum1!=0 AND colum2!=0 AND colum3 IN ('%@')",[serch componentsJoinedByString:@"','"]]

FMResultSet return nil;

Update sqlite not working on android

I have a login and reset password activity. When I enter the new updated password and try to login again, I cannot do so with the new password. Logging in with the old password works fine. Basically, the password field is not getting updated/overwritten.

There is no error in the logcat. Just that the password is not updated.

Please help as I am new to android development.

Code for update( DataRegister is the class with GET AND SET functions):

public int updatePassword(DataRegister dataregister) {

db = dbHelper.getWritableDatabase();
ContentValues updated = new ContentValues();
updated.put("PASSWORD", dataregister.getPASSWORD());

return db.update(DataRegister.TABLE, updated, "EMAIL=?" , new String[]   {dataregister.getEMAIL()});

}

Code for retrieval:

public String getPass(DataRegister dataRegister) {

db = dbHelper.getWritableDatabase();

Cursor cursor = db.query(DataRegister.TABLE, null, "EMAIL=?",
        new String[]{dataRegister.getEMAIL()}, null, null, null, null);
if (cursor != null && cursor.moveToFirst())

{
    pass = cursor.getString(cursor.getColumnIndex("PASSWORD"));
    cursor.close();
}
return pass;


// return contact


}

Code for Login:

  String email = editTextUserName.getText().toString();
        dataRegister.setEMAIL(email);

        String password = editTextPassword.getText().toString();
        dataRegister.setPASSWORD(password);

        String storedPassword = loginDataBaseAdapter.getSinlgeEntry(dataRegister);

        Toast.makeText(Login.this, storedPassword,Toast.LENGTH_LONG).show();
        Boolean a=loginDataBaseAdapter.isExist(dataRegister.getEMAIL());
       validation = getSharedPreferences("myShaPreferences", Context.MODE_PRIVATE);

        if (password.equals(storedPassword)) {

            Toast.makeText(Login.this,
                    "Congrats: Login Successful", Toast.LENGTH_LONG)
                    .show();
        }

        else {

                Toast.makeText(Login.this,
                        "User Name or Password does not match",
                        Toast.LENGTH_LONG).show();


            }



    }
});

Code for reset password:

public class ResetPassword extends AppCompatActivity {


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

 email = (EditText) findViewById(R.id.em2);
 dataRegister=new DataRegister();

loginDataBaseAdapter = new DatabaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();



pass = (EditText) findViewById(R.id.text12);
conpass = (EditText) findViewById(R.id.text13);

email1 = email.getText().toString();
dataRegister.setEMAIL(email1);
pass1 = pass.getText().toString();

conpass1 = conpass.getText().toString();
dataRegister.setPASSWORD(conpass1);

Button btnReset = (Button) findViewById(R.id.btnReset);
btnReset.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {


        if (pass1.equals(conpass1)) {

         loginDataBaseAdapter.updatePassword(email1,pass1);
            String newpass =loginDataBaseAdapter.getPass(dataRegister);

Table with many columns or many small tables?

I created a table where it has 30 columns.

CREATE TABLE "SETTINGS" (
  "column1" INTEGER PRIMARY KEY,
  ...
  ...
  "column30"
)

However, I can group them and create different table where they can have foreign keys to the primary table. Which is the best way to follow? Or the number of the columns is small so it's the same which way I will follow?

android sqlight how to search string in like if string contains ' symbol

following is my query that I am trying to search name contain special character e.g. ' symbol

 SELECT * from  distributor where name like'%jeni's%'

when I tried to add backslash if work in MySQL but wont work in sq light database I also tried following query

SELECT * from distributor where name like'%jeni\'s%' can someone help me to how can i search if string contains ' symbol

what is the use of onUpgrade() in sqlite?

Anybody please help me regarding the correct use of onUpgrade() in sqliteopenhelper class.Thanks in advance.

How to copy displyed text of recent page and share in android?

I created database which is displayed on sliding page one by one like e1 slide e2. Now i want to copy e1 and share it with friends.How to perform this task in android?

green dao update column on play store update has taken place

this is my Generator class

public class Generator {
    public static void main(String[] args) throws Exception {
        Schema schema = new Schema(1, "app.abc.db.dao");
        createAbcDB(schema);

    }
    private static void createAbcDB(Schema schema) throws IOException, Exception {
        Entity abc = schema.addEntity("Abc");
        abc.addIdProperty();
        abc.addShortProperty("name");
    }
}

This is the code where i get abc dao from dao session. This works fine.

DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(SurveyActivity.this, "abc.db", null);
        SQLiteDatabase db = devOpenHelper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        DaoSession daoSession = daoMaster.newSession(IdentityScopeType.None);
        abcDao = daoSession.getAbcDao();

I added one more column

abc.addShortProperty("email");

to createAbcDB in generator to new version of app. Once users get updated they are getting sql exception saying no column found. Because i am calling on new login

dropAllTables(db, true);
onCreate(db); 

But problem is i have given one time login that user will always come to landing screen on upgrade from play store. So i don't know whether the user is upgraded app or not in order to drop and create all tables.

So my question is how to know my table has altered?

Table has no column named xyz while inserting data into SQLite database

It says that the column name bmi does not exist. The resulting Error message is that the system cannot find a column called bmi. I checked it already a couple of times and I couldn't find a mistake in the code. Maybe you guys see one... The full Stack Dump is attached after the code.

public class MyDBHandler extends SQLiteOpenHelper{

private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "bmiwerte.db";

public static final String TABLE_BMIS = "bmis";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_BMI = "bmi";


public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}

private static final String CREATE_TABLE_BMIS = "CREATE TABLE "
        +TABLE_BMIS
        +" ("
        +COLUMN_ID
        +" INTEGER AUTOINCREMENT, "
        +COLUMN_NAME
        +" TEXT PRIMARY KEY"
        +COLUMN_BMI
        +" TEXT"
        +");";

@Override
public void onCreate(SQLiteDatabase db) {

    //Lässt Query in SQL laufen
    Log.i("exxxx", "Creating Check");
    db.execSQL(CREATE_TABLE_BMIS);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXIST " + TABLE_BMIS);
    onCreate(db);
}

public void addValues(BMI_Werte wert){
    ContentValues values = new ContentValues();

    values.put(COLUMN_NAME, wert.get_name());
    values.put(COLUMN_BMI, wert.get_bmiWert().toString());
    Log.i("exxx", wert.get_name());
    Log.i("exxxx", wert.get_bmiWert().toString());

    SQLiteDatabase db = getWritableDatabase();
    db.insert(TABLE_BMIS, null, values);
    db.close();
}

public void deleteValues(String name){
    Log.i("exxxx", "deleteValuse");
    SQLiteDatabase db = getWritableDatabase();
    db.execSQL("DELETE FROM " + TABLE_BMIS + " WHERE " +
            COLUMN_NAME + "=\"" + name + "\";");
}

public String databaseToString(){
    String dbString = "";
    SQLiteDatabase db = this.getWritableDatabase();

    String query = "SELECT * FROM " + TABLE_BMIS;
    String test = "DESCRIBE " + TABLE_BMIS;

    Cursor c = db.rawQuery(query, null);

    c.moveToFirst();

    while(!c.isAfterLast()){
        if(c.getString(c.getColumnIndex("name")) != null){
            dbString += c.getString(c.getColumnIndex("name"));
            dbString += "\n";
        }
        c.moveToNext();
    }

    db.close();
    return dbString;
}

}

Error and Stack Dump:


Error

Android SQLite sending query as an email

I was wondering if it was possible to send a query via email that is created through my app as a text file, or similar format that can be viewed on a pc. The query i want to send is

public Cursor getExpiryData (){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor expiry = db.rawQuery("select * from " + TABLE_NAME + " WHERE " + COL_4 + " BETWEEN datetime('now', 'localtime') AND datetime('now', '+30 days')", null );
    return expiry;
}

Unable to set data into database

In this below code im trying get and set data from the data base but during execution im unable set data in the data base ...

SettingUp

mWirelessRouters = WalletWirelessRouter.get(getActivity()).getWirelessRouter(uuid);

onTextChanged Listner

 mBaseStationName = (EditText) v.findViewById(R.id.base_station_name);
    mBaseStationName.setText(mWirelessRouters.getBaseStationName());
    mBaseStationName.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged
                (CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged
                (CharSequence s, int start, int before, int count) {
           mWirelessRouters.setBaseStationName(s.toString());
        }

        @Override
        public void afterTextChanged
                (Editable s) {

        }
    });

Note:- In the above code im trying take the base station name from the user and update it in database..There is no issue related view

getWirelessRouter(UUID uuid)

 public WirelessRouter getWirelessRouter(UUID id)
{
    WalletCursorWrapper cursor = queryWireless(
            WalletDbSchema.WirelessRouter.Cols.UUID + " =? "
            , new String[]
                    {
                            id.toString()
                    }
    );

    try {
        if (cursor.getCount() == 0) {
            return null;
        }

        cursor.moveToFirst();
        return cursor.getWirelessRouter();
    } finally {
        cursor.close();
    }
}

queryWireless

 private WalletCursorWrapper queryWireless (String whereClause, String[] whereArgs)
{
    Cursor cursor = mDatabase.query(
            WalletDbSchema.WirelessRouter.NAME,
            null, // Colums - null select all colums
            whereClause,
            whereArgs,
            null, //groupBy
            null, //having
            null // order

    );

    return new WalletCursorWrapper(cursor);
}

If you need any more data please let me know

Assign ID numbers according to groups

Button blue can add blue item, red button adding red button, etc. one button can be clicked more than once, hence there can be more than one blue or red item.

the table is as below

item     id      details    size
blue             cheap      small
blue             expensive  big
blue             cheap      small
red              cheap      small
red              ok         average

how can i assign the id for each of them so that the table is as below

item     id      details    size
blue      1      cheap      small
blue      2      expensive  big
blue      3      cheap      small
red       1      cheap      small
red       2      ok         average

Android sync text and audio notes

In one activity the user will get quotes from him daily in text format. I am thinking the older quotes should be stored in his mobile whereas the user should be able to download new quotes as an when available. The same requirement with audio quotes in the second activity.

I want someone to point me the right direction. Currently, my confusion are:

  1. As in website do I need to make a purchase for the database space online. If yes provider recommendations please.
  2. How should I store the quote in text and audio format in the user mobile.
  3. How will I do the syncing with my online database and user database.
  4. What are the options which I can give my friend to upload new text and audio files.

SQLITE strftime() function issue

SELECT strftime('%W', 'Week'), sum(income) FROM tableOne GROUP BY Week;

Format for date is a simple date: YYYY-MM-DD

PROBLEM: When run no value for the Week column is provided. Any suggestions?

There is data in the table and when the query is run the income is summarized by the date in the week column. Thing is, this column contains a date that may be any day of the week and often multiple different days of the same week. I need to summarize the income by week.

dimanche 8 mai 2016

How to save the sqlite file in the local folder or nsbundle programatically in iOS?

I already have an sqlite file in my application. But in one of my application settings page there are two options restore and backup. The idea which is to be implemented is that a) On clicking backup the sqlite file which is already there must be saved in another folder inside the application by creating a new folder. b) On clicking restore the datas must be fetched from the sqlite file present in the newly created folder.

Any idea how to achieve this? Thanks

Block updates in a table SQLite Android

I wish to know if there a way to block updates in a table from SQLite android database. I am developing an app. Certain table has two foreign keys that are a unique constraint. Once inserted a row this row should not be updated. It can be only deleted if necessary. This make sense for you? Can I create my tables in this way? Do you know a better way to code this?

How to store and process result of a query in PHP array?

My SQLite query in PHP goes like this:

function getTableData($l_name) {
   $db = new PDO("sqlite:../db/mydb.sqlite");
   $results = $db->exec("SELECT * FROM Locations WHERE L_ID = '" . $l_name; . "');";
   .......
}

My questions are:

  • How can I get an array of Locations based on the $results? Could I just write $results[0] or $results[$results.length] to reference first and last records respectively?
  • How would I use a foreach loop to loop through all records? Could I have foreach ($results as $record), where $record is supposed to be a single record of Location in the current iteration?
  • If I were to have a reference to an individual record, say using an array like this records[0], how would I access this record's field (such as L_Name or L_ID)?

Thank you.

Sqlite query on uwp

How to code the UWP for sqlite query below:

Select word, translation 
from ind_dict 
where word like '?%'

I try to enter the code below, but the error message as shown below:

enter image description here

Code:

using (var statement = _connection.Prepare("SELECT word, translation FROM " + TABLE_NAME_IND + " WHERE word like '?%'"))
{
    //Ind.Word = inputText.Text;
    statement.Bind(1, Ind.Word);
    SQLiteResult result = statement.Step();

    if (SQLiteResult.ROW == result)
    {
        value = statement[Ind.Word] as String;
        value = statement[Ind.Translation] as String;
        indDatasource.Add(Ind);

        if (indDatasource.Count > 0)
        {
            translation.ItemsSource = indDatasource;
        }
    }
}

How to solve this?

Populating a list view with from a Database

So my question is I created a listview and populated it using a simple cursor adapter. So now when I click an item on my listview it takes me to another activity which suppose to show me the details of the item I clicked. What is the best approach on going about this? Here is my function of populating the list view. What exactly should I be sending to the next activity? I was thinking about sending the position but then that wouldnt work because in the next activity I would have to access the database using the position but that wouldnt be accurate because the database could have rows deleted which can return me a different row of data. Any ideas would be truly appreciated.

private void populateListView(){

    Cursor cursor = myDatabase.getAllData();
    String[] fromfieldNames = new String[]{StudentDBOpenHelper.ITEM_NAME_COLUMN};
    int[] toViewIDs = new int[] {R.id.textView_itemName};
    SimpleCursorAdapter myCursorAdapter;
    myCursorAdapter = new SimpleCursorAdapter(getActivity(),
            R.layout.indvidualview_layout,cursor,fromfieldNames,toViewIDs,0);
    ListView myList = (ListView) getActivity().findViewById(R.id.courseListXML);
    myList.setAdapter(myCursorAdapter);


    myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


            Intent nextActivity = new Intent(getActivity(), CourseWorkItemActivity.class);

            nextActivity.putExtra("Item", position);

            startActivity(nextActivity);

        }
    });
}

Invalid syntax errror on SQLite execute command

I've got the following python 3 code:

import sqlite3
import json

conn = sqlite3.connect('data.db')
c = conn.cursor()

types = json.load(open('marketTypes.json'))

for data in types['items']:
    c.execute('INSERT INTO marketTypes (id, name, href) VALUES (?, ?, ?)', 
            (data['id_str'], data['type']['name'], data['type']['href'])

conn.commit()
conn.close()

The database has already been created with a marketTypes table and 3 fields; id, name and href.

The json file looks like so, the first two fields that is, it is quite a long file.

{'items': [{'id': 18,
        'id_str': '18',
        'marketGroup': {'href': 'http://ift.tt/1Oa7htg',
                        'id': 516,
                        'id_str': '516'},
        'type': {'href': 'http://ift.tt/21MY1xB',
                 'icon': {'href': 'http://ift.tt/1Oa7eNW'},
                 'id': 18,
                 'id_str': '18',
                 'name': 'Plagioclase'}},
       {'id': 19,
        'id_str': '19',
        'marketGroup': {'href': 'http://ift.tt/21MXZpz',
                        'id': 517,
                        'id_str': '517'},
        'type': {'href': 'http://ift.tt/1Oa7eNY',
                 'icon': {'href': 'http://ift.tt/21MXZpB'},
                 'id': 19,
                 'id_str': '19',
                 'name': 'Spodumain'}},

When I run the python file I get:

File "sqlite.py", line 13
conn.commit()
   ^
SyntaxError: invalid syntax

Any ideas on how to solve the issue? I apologize if the title is not as specific/helpful.

Thanks.

android: 1M records to lookup in database

I'm going to develop a phonebook-like application which is going to lookup among one million records for specified name. One of my main concerns is performance of lookups. So my questions are:

1- Is it feasible to have a SQLite database in android with 1M records?

2- Are there any know solutions to speed up database queries?

About 2nd question it comes to my mind to use Indexing and also breaking up database to several smaller databases. In case it is not feasible are there any know methods to handle this?

NullPointerException in android sqlite [duplicate]

This question already has an answer here:

I am trying to create an action that gets a string value and returns String array of the items with the keyword in their name.

This is my code:

public String[] getList(String st) {

   SQLiteDatabase database = myDBHelper.getReadableDatabase();

   String query = "Select * from " + TASKS_TABLE + " WHERE name LIKE '%" + st + "%'";
   Cursor cursor = database.rawQuery(query,null);
   //String[] columns = {TASK_IMAGE};
   // cursor = database.query(TASKS_TABLE,columns, TASK_NAME + "='" + st + "'",null, null, null, null, null);
   String[] array = new String[cursor.getCount()];
   int i = 0;
   while(cursor.moveToNext()){
       String uname = cursor.getString(cursor.getColumnIndex("name"));
       array[i] = uname;
       i++;
   }

   return array;
}

When I run it I get:

05-08 18:18:28.353 6637-6637/? E/AndroidRuntime: FATAL EXCEPTION: main
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime: Process: com.sahar.wave,   PID: 6637
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{http://ift.tt/1rBQmWz}: java.lang.NullPointerException
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime:     at android.app.ActivityThread.access$800(ActivityThread.java:135)
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:102)
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:136)
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5001)
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:515)
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method)
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime:  Caused by: java.lang.NullPointerException
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime:     at com.sahar.wave.Results.onCreate(Results.java:26)
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime:     at android.app.Activity.performCreate(Activity.java:5231)
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233) 
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime:     at android.app.ActivityThread.access$800(ActivityThread.java:135) 
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:102) 
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:136) 
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5001) 
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method) 
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime:     at  java.lang.reflect.Method.invoke(Method.java:515) 
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) 
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) 
05-08 18:18:28.353 6637-6637/? E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method) 

This is the Activity code:

private SiteDBMngr dbMngr;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.results);

    String st = "c";//-------------------------------put here the search key

   // String[] sites = new String[2];
    String[] sites = dbMngr.getList(st);
    ListAdapter Adapter = new CustomAdapter(this, sites);
    ListView listView = (ListView) findViewById(R.id.sitesListView);
    listView.setAdapter(Adapter);

    listView.setOnItemClickListener(
            new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                }
            }
    );
}

inserting records in a sqlite database does not change its size but

I have a SQLite database with about 100 records inserted in it. the size of the file on my disk is about 65 KB. It was the same before and after the insertion of data. I compressed the file to .tar.7z format. As I keep adding data the size of the database file stays the same but when I compress it I see the size of archive file growing. Why is that so? Could someone please explain the reason for this behavior I am observing.

SQLite LEFT JOIN Usage is Not Working Correctly

I have 3 TABLES. Costumer, Product and Stats. When user select a user and a product, i increase Stats->count by 1. Stats table has id, cid, pid and count values. My purpose is sort products by count and they should be alphabetic. This is my sql request;

SELECT * FROM product AS p
         LEFT JOIN stat AS s
         ON p._id = s.stats_product_id
         WHERE s.stats_customer_id = 'customerId'
         ORDER BY s.stats_count desc , p.product_name COLLATE NOCASE;

The problem is; because i create Stats values after i create some order, at the beginning i can't see all of products. Because some of products that i've never used are not in my Stats table. I know that LEFT JOIN should give me all of products values but it doesn't... Please help me. Thanks in advice.

Ex: I have a,b,c,d,e,f products. Let's think that a,b bought 3 times (their counts are 3), e,f bought 2 times (their counts are 2) and c,d never bought (they are not in stats table because they never bought by anyone and that's the problem tho!). Output order should be: a b e f c d HANDLED: Solution on answer #1.

Data loss with SQLite database in Delphi

I am trying to save binary encoded data in SQLite database and I am able to save the values but there are few characters that are getting lost after saving and closing the dataset.

The inserted data looks like this.

enter image description here

The highlighted text is getting lost when I load the saved record in a grid or table.

Create SQLite connection:

procedure CreateSQLiteDB(ASQLiteDB: string);
begin
  FDConnection1.Params.Values['Database'] := 'DB_MOBILE';
  FDConnection1.Connected := true;
end;

Copy table schema from an existing dataset:

procedure CopyTableSchemaFrom(ADataset: TDataset;
  ATableNm: string);
var
  i: Integer;
  AField: TField;

  procedure L_CopyFieldDefToSQLiteTable(AName: string; aType: TDataType;
    ASize: Integer; AIsRqrd: Boolean);
  var
    LFldSz: Integer;
  begin
    LFldSz:= 0;
    case aType of
      ftString, ftWideString, ftBCD, ftBytes, ftVarBytes, ftBlob, ftMemo, ftGraphic: LFldSz:= ASize;
    end;

    tblSQLite.FieldDefs.Add(AName, aType, LFldSz, AIsRqrd);
  end;

begin
  if ADataset = nil then
    Assert(false, 'Unassigned argument supplied in ADataset.');
  if Trim(ATableNm) = '' then
    Assert(false, 'Empty argument supplied in ATableNm.');

  // SQLite Table name should be same as .DBF file name
  tblSQLite.TableName := ATableNm;

  { Loop through the field in source dataset and copy them to SQLite table. }
  for i := 0 to ADataset.FieldCount - 1 do
  begin
    AField := ADataset.Fields[i];
    if AField = nil then
      Continue;

    L_CopyFieldDefToSQLiteTable(AField.FieldName, AField.DataType,
      AField.DataSize, AField.Required);
  end;

  tblSQLite.CreateDataSet;
end;

Copy value from existing dataset to SQLite;

procedure CopyDataFrom(ASrc: TDataset;
  ASQLiteTblNm: string);
var
  i: Integer;
begin
  if ASrc = nil then
    Assert(false, 'Unassigned argument supplied in ASrc.');
  if Trim(ASQLiteTblNm) = '' then
    Assert(false, 'Empty argument supplied in ASQLiteTblNm.');

  tblSQLite.Close;
  tblSQLite.CachedUpdates := true;
  tblSQLite.Active := true;

  ASrc.First;
  while not ASrc.Eof do
  begin
    tblSQLite.Insert;

    for i := 0 to ASrc.FieldCount - 1 do
    begin
      tblSQLite.Fields[i].Value := ASrc.Fields[i].Value;
    end;

    ASrc.Next;
  end;

  tblSQLite.ApplyUpdates;
  tblSQLite.CommitUpdates;
end;

How to delete an item by its id?

here I delete an item in my RecyclerView, but I need to delete also the item with that id in the db

     @Override
       public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
           itemTouchHelperAdapter.onItemRemoved(viewHolder.getAdapterPosition());

       }

Get information from Sqlite and create Object 'message' returns null [duplicate]

This question already has an answer here:

I have a problem trying to collect data from a SQLite database, for some reason when you insert the item to the list (RecyclerView) returns null assuming error:

java.lang.RuntimeException: Unable to start activity ComponentInfo{beta.unomasenlafamilia/beta.unomasenlafamilia.PM_MessagesActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void beta.unomasenlafamilia.adapter.MessageAdapter.addListItem(beta.unomasenlafamilia.domain.Message, int)' on a null object reference
                                                                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2406)
                                                                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2466)
                                                                        at android.app.ActivityThread.access$1200(ActivityThread.java:152)
                                                                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1341)
                                                                        at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                        at android.os.Looper.loop(Looper.java:135)
                                                                        at android.app.ActivityThread.main(ActivityThread.java:5538)
                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                        at java.lang.reflect.Method.invoke(Method.java:372)
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                                                                     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void beta.unomasenlafamilia.adapter.MessageAdapter.addListItem(beta.unomasenlafamilia.domain.Message, int)' on a null object reference
                                                                        at beta.unomasenlafamilia.PM_MessagesActivity.mostrarChatLocal(PM_MessagesActivity.java:457)
                                                                        at beta.unomasenlafamilia.PM_MessagesActivity.onCreate(PM_MessagesActivity.java:120)

MainActivity.class

public void showChatLocal(String userfrom,String userto) {

    //Show total num records
    int limite = h_sql.showMsgNum();
    Cursor cursor = h_sql.fetchMessages(String.valueOf(mUserFrom.getId()), String.valueOf(mUserTo.getId()));
    MessageAdapter adapter = (MessageAdapter) mRecyclerView.getAdapter();
    List<Message> messageList = new ArrayList<Message>();

    for(int i =0;i<limite;i++){

        Message m = new Message();

        m.setUserFrom(cursor.getString(cursor.getColumnIndex("id_user_from")));
        m.setUserTo(cursor.getString(cursor.getColumnIndex("id_user_to")));
        m.setMessage(cursor.getString(cursor.getColumnIndex("message")));
        m.setRegTime(Long.parseLong(cursor.getString(cursor.getColumnIndex("regtime"))));
        m.setWasRead(Integer.parseInt(cursor.getString(cursor.getColumnIndex("wasRead"))));

        messageList.add(m);
        adapter.addListItem(messageList.get(i),0);
        mRecyclerView.smoothScrollToPosition(0);
        cursor.moveToNext();
    }

    cursor.close();
}

//MessageAdapter

public void addListItem(Message m, int position) {
    mList.add(position, m);
    notifyItemInserted(position);
}

Thank you very much to all, regards!

android.database.sqlite.SQLiteException: no such table: USER_DATA_TABLE (code 1): , while compiling: SELECT * FROM USER_DATA_TABLE WHERE id=? LIMIT 1

I'm facing a very strange error during running android app in Android Studio on emulator. Error is pasted below.

I'm not using SQLite for db. I'm using Shared performances. There is no reference to USER_DATA_TABLE or SQLite in the code.

The only place where I could see reference to USER_DATA_TABLE & SQLite is in /build/generated/mockable-android-23.jar file which is obviously generated by the build process. I deleted entire build folder before building the app and running.

Can any of you experts give me some clue on how to fix it?

The code snippet which access SugarORM is this:

   public void redrawNavMenu() {
    UserDataTable user = UserDataTable.findById(UserDataTable.class, 1L);

findById method used is in SugarORM

public static <T extends SugarRecord<?>> T findById(Class<T> type, Long id) {
    List<T> list = find( type, "id=?", new String[]{String.valueOf(id)}, null, null, "1");
    if (list.isEmpty()) return null;
    return list.get(0);
}

I'm lost here. So where does USER_DATA_TABLE is accessed from if it's not anywhere in the code at all?

Log:

java.lang.RuntimeException: Unable to start activity ComponentInfo{http://ift.tt/23zI0uk}: android.database.sqlite.SQLiteException: no such table: USER_DATA_TABLE (code 1): , while compiling: SELECT * FROM USER_DATA_TABLE WHERE id=? LIMIT 1
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
     Caused by: android.database.sqlite.SQLiteException: no such table: USER_DATA_TABLE (code 1): , while compiling: SELECT * FROM USER_DATA_TABLE WHERE id=? LIMIT 1
        at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
        at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
        at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
        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:1316)
        at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1163)
        at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1034)
        at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1240)
        at com.orm.SugarRecord.find(SugarRecord.java:208)
        at com.orm.SugarRecord.findById(SugarRecord.java:138)
        at com.matt.quiz.activities.QuizActivity.redrawNavMenu(QuizActivity.java:461)
        at com.matt.quiz.activities.QuizActivity.onCreate(QuizActivity.java:194)
        at android.app.Activity.performCreate(Activity.java:6237)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
        at android.app.ActivityThread.-wrap11(ActivityThread.java) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:148) 
        at android.app.ActivityThread.main(ActivityThread.java:5417) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

Swift 2 sqlite - library routine called out of sequence

I am using below code to insert records to sqlite. SQLite DB is already created and sqlite file exists in the right place. However, when i run my test it gives an error: Any help on this is appreciated. Already spent some time on this. By the way, am new to SWIFT :(

"sqlite3_errmsg(carParkDB) UnsafePointer 0x000000010f44a863 "library routine called out of sequence"

Error appears at the first bind statement

sqlite3_bind_text(insertStmt, 1, carParkData.dataSource.rawValue, -1, SQLITE_TRANSIENT)

Below is my DAOImpl

import Foundation

class CarParkDaoImpl : CarParkDao{

var carParkDB : COpaquePointer = nil
var insertStmt: COpaquePointer = nil

let SQLITE_TRANSIENT = unsafeBitCast(-1, sqlite3_destructor_type.self)

func initializeDB(){
    let carParkDataSQ = Constants.Paths.path + "/CarParkData.sqlite"
    print("Sqlite file: \(carParkDataSQ)")

    if(sqlite3_open(carParkDataSQ, &carParkDB) == SQLITE_OK){
        let ret:Int32 = sqlite3_exec(carParkDB, Constants.CAR_PARK_SQL.createSql, nil, nil, nil);
        if ( ret != SQLITE_OK){
            print("Failed to create table: \(Constants.CAR_PARK_SQL.createSql)")
            print("Error:  \(sqlite3_errmsg(carParkDB))")
            closeDB()
        }
    }else{
        print("Falied to open : \(carParkDataSQ)")
        print("Error:  \(sqlite3_errmsg(carParkDB))")
        closeDB()
    }
}

func closeDB(){
    sqlite3_close(carParkDB)
}


init(){
    initializeDB()
}

/**
 Responsible to insert the car park data

 - Parameter carParkData: CarParkData.
 - returns Bool
 */
func insert(carParkData: CarParkData) -> Bool{
    prepareInsStatments()
    var ret: Bool = false
    sqlite3_bind_text(insertStmt, 1, carParkData.dataSource.rawValue, -1, SQLITE_TRANSIENT)
    sqlite3_bind_text(insertStmt, 2, carParkData.address, -1, SQLITE_TRANSIENT)
    sqlite3_bind_double(insertStmt, 3, carParkData.latitude)
    sqlite3_bind_double(insertStmt, 4, carParkData.longitude)
    sqlite3_bind_int(insertStmt, 5, Int32(carParkData.ltaCarParkID))
    sqlite3_bind_text(insertStmt, 6, carParkData.ltaArea, -1, SQLITE_TRANSIENT)
    sqlite3_bind_int(insertStmt, 7, Int32(carParkData.ltaLots))
    sqlite3_bind_double(insertStmt, 8, carParkData.ltaPrice)
    sqlite3_bind_text(insertStmt, 9, carParkData.hdbShortTermParking, -1, SQLITE_TRANSIENT)
    sqlite3_bind_text(insertStmt, 10, carParkData.hdbCarParkType, -1, SQLITE_TRANSIENT)
    sqlite3_bind_text(insertStmt, 11, carParkData.hdbFreeParking, -1, SQLITE_TRANSIENT)
    sqlite3_bind_text(insertStmt, 12, carParkData.hdbNightParking, -1, SQLITE_TRANSIENT)
    sqlite3_bind_int(insertStmt, 13, Int32(carParkData.hdbId))
    sqlite3_bind_text(insertStmt, 14, carParkData.hdbAdHocParking, -1, SQLITE_TRANSIENT)
    sqlite3_bind_text(insertStmt, 15, carParkData.hdbCarParkNo, -1, SQLITE_TRANSIENT)
    let rc:Int32 = sqlite3_bind_text(insertStmt, 16, carParkData.hdbTypeOfParking, -1, SQLITE_TRANSIENT)

    if (rc != SQLITE_OK) {
        print(stderr, "failed to prepare statement: %s\n",
                sqlite3_errmsg(carParkDB));
        sqlite3_close(carParkDB);
        return ret;
    }

    if(sqlite3_step(insertStmt) == SQLITE_DONE){
        ret = true;
    }
    sqlite3_reset(insertStmt)
    sqlite3_clear_bindings(insertStmt)
    return ret
}


/**
 Responsible to finalize all the prepared statements
 */
func finalize(){
    sqlite3_finalize(insertStmt)
    sqlite3_finalize(updateStmt)
    sqlite3_finalize(deleteStmt)
    sqlite3_finalize(selectAllStmt)
    sqlite3_finalize(selectByIdStmt)
    sqlite3_finalize(selectByDataSourceStmt)
}




func prepareInsStatments(){
    let stmt = Constants.CAR_PARK_SQL.insertSql.cStringUsingEncoding(NSUTF8StringEncoding)
    let ret:Int32 = sqlite3_prepare_v2(carParkDB, stmt!, -1, &insertStmt, nil)
    if (ret != SQLITE_OK) {
        print(stderr, "failed to prepare statement: %s\n",
                sqlite3_errmsg(carParkDB));
        sqlite3_close(carParkDB);
    }
}

}

Here is my insert sql

   static let insertSql:String =
        "INSERT INTO CAR_PARK_DATA ( DATASOURCE, ADDRESS, LATITUDE, LONGITUDE "
            + " , LTA_CAR_PARK_ID, LTA_AREA, LTA_LOTS, LTA_PRICE, HDB_SHORT_TERM_PAKING "
            + " , HDB_CAR_PARK_TYPE, HDB_FREE_PARKING, HDB_NIGHT_PARKING, HDB_ID "
            + " , HDB_ADHOC_PARKING, HDB_CAR_PARK_NO, HDB_TYPE_PARK_SYSTEM ) "
            + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) "

Here is my test method

func testInsert(){
    carParkData = CarParkData(dataType: DataSourceType.LTA.rawValue, address: "This is Test address", latitude: 100.0, longitude: 200.0, carParkID : 10, ltaCarParkID : 20, ltaArea: "LTA Area", ltaLots: 20, hdbShortTermParking: "Test HDB Short Praking", hdbCarParkType: "HDB Car Park Type", hdbFreeParking: "HDB Free Parking", hdbNightParking: "HDB Night Parking", hdbId : 30, hdbAdHocParking: "HDB Ad Hoc Parking", hdbCarParkNo: "HDB Car Park No", hdbTypeOfParking: "HDB Parking type", ltaPrice: 10.96778, favourite: true)
    var val:Bool = carParkDao.insert(carParkData);
    XCTAssertTrue(val)

Linking two SQLDatabases together

I am making an application that basically holds categories of questions (and, needless to mention, questions within each category). The users are able to add/remove categories and add/remove questions within those categories. I need to now capture this structure in SQLDatabase and I am kind of stuck.

I have realized that I will need two tables to capture this relationship but I have absolutely no clue to how to go about it.

So, should I make two different SQLiteOpenHelpers for the two tables? If so, how do I go about creating a link between them? Each Category object has an ID,a title and a list of Question objects and each Question object has a Category object, ID, String (the actual question). So which fields should I include in both the tables?

I am really confused and a little guidance will help a lot. I am just a beginner so a little explanation would be appreciate a lot.

Updating password field is not working in sqlite android

I have a login and reset password activity. When I enter the new updated password and try to login again, I cannot do so with the new password. Logging in with the old password works fine. Basically, the password field is not getting updated/overwritten.

There is no error in the logcat. Just that the password is not updated.

Please help as I am new to android development.

Code for update( DataRegister is the class with GET AND SET functions):

 public int updatePassword(String email, String paa) {

  db = dbHelper.getWritableDatabase();



    ContentValues updated = new ContentValues();
    updated.put("PASSWORD", paa);
  // db.execSQL(" UPDATE " + DataRegister.TABLE  +
           // " SET PASSWORD = '" + password + "'" + " WHERE EMAIL = ? " , new String[]{email});

return db.update(DataRegister.TABLE, updated, "EMAIL=?" , new String[]{email});

}

Code for retrieval:

 public String getPass(DataRegister dataRegister) {

    db = dbHelper.getWritableDatabase();

    Cursor cursor = db.query(DataRegister.TABLE, null, "EMAIL=?",
            new String[]{dataRegister.getEMAIL()}, null, null, null, null);
    if (cursor != null && cursor.moveToFirst())

    {
        pass = cursor.getString(cursor.getColumnIndex("PASSWORD"));
        cursor.close();
    }
    return pass;


    // return contact


}

Code for Login:

 String email = editTextUserName.getText().toString();
            dataRegister.setEMAIL(email);

            String password = editTextPassword.getText().toString();
            dataRegister.setPASSWORD(password);

            String storedPassword = loginDataBaseAdapter.getSinlgeEntry(dataRegister);

            Toast.makeText(Login.this, storedPassword,Toast.LENGTH_LONG).show();
            Boolean a=loginDataBaseAdapter.isExist(dataRegister.getEMAIL());
           validation = getSharedPreferences("myShaPreferences", Context.MODE_PRIVATE);

            if (password.equals(storedPassword)) {

                Toast.makeText(Login.this,
                        "Congrats: Login Successful", Toast.LENGTH_LONG)
                        .show();
            }

            else {

                    Toast.makeText(Login.this,
                            "User Name or Password does not match",
                            Toast.LENGTH_LONG).show();


                }



        }
    });

Code for reset password:

public class ResetPassword extends AppCompatActivity {


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

    email = (EditText) findViewById(R.id.em2);
    dataRegister=new DataRegister();

    loginDataBaseAdapter = new DatabaseAdapter(this);
    loginDataBaseAdapter = loginDataBaseAdapter.open();



    pass = (EditText) findViewById(R.id.text12);
    conpass = (EditText) findViewById(R.id.text13);

    email1 = email.getText().toString();
    dataRegister.setEMAIL(email1);
    pass1 = pass.getText().toString();

    conpass1 = conpass.getText().toString();
    dataRegister.setPASSWORD(conpass1);

    Button btnReset = (Button) findViewById(R.id.btnReset);
    btnReset.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {


            if (pass1.equals(conpass1)) {

             loginDataBaseAdapter.updatePassword(email1,pass1);
                String newpass = loginDataBaseAdapter.getPass(dataRegister);



                Toast.makeText(ResetPassword.this, newpass, Toast.LENGTH_LONG).show();
                Intent intent = new Intent(ResetPassword.this, Login.class);
                startActivity(intent);


                finish();

            }

            else {
                Toast.makeText(ResetPassword.this,
                        "Password does not match",
                        Toast.LENGTH_LONG).show();

            }


        }

    });

SQLite Key Property Issue Using Mvvm Windows Universal

This is my Model called "ChallengeItem" for the SQLite table:

   [AutoIncrement]
    private int _key { get; set; }

    public int Key
    {
        get { return _key; }
        set { _key = value; OnPropertyChanged("Key");}
    }

    private bool _done;

    public bool Done
    {
        get { return _done; }
        set { _done = value; OnPropertyChanged("Done"); }
    }

I created a class called "DatabaseManager" which includes this line of Code:

  conn.CreateTable<Models.ChallengeItem>();

  • After checking the Key property it turns out that it doesn't increment, the key value is staying 0 for every Challengeitem in the table. How can I fix this?
  • How can I get the last Item in the table where the Done Property of the challengeitem equals true?

E/SQLiteLog: (1) near "-": syntax error when insert data in android app

I'm getting this error in my app when I try to write to database E/SQLiteLog: (1) near "-": syntax error please can you help me... Here is my code for SQLite databse. I am attaching the complete code for database class here

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * Created by TOSHIBA on 01/05/2016.
 */

// CREATION DATABASE

public class DatabaseHelper extends SQLiteOpenHelper {
    private SQLiteDatabase db;

    private static final String DATABASE_NAME = "QuickTowing.db";

    private static final String QUERY =
           "CREATE TABLE "+ TablesDB.NewClientInfo.TABLE_NAME+"("+ TablesDB.NewClientInfo.COL_1+" INTEGER PRIMARY KEY AUTOINCREMENT,"
                   + TablesDB.NewClientInfo.COL_2+" TEXT,"+ TablesDB.NewClientInfo.COL_3+" TEXT,"+ TablesDB.NewClientInfo.COL_4+" TEXT,"
                  + TablesDB.NewClientInfo.COL_5+" INTEGER,"+ TablesDB.NewClientInfo.COL_6+" TEXT,"+ TablesDB.NewClientInfo.COL_7+" TEXT,"
                   + TablesDB.NewClientInfo.COL_8+" TEXT);";

    //CREATE DATABASE
    public DatabaseHelper(Context context) {

        super(context, DATABASE_NAME, null, 1);
        Log.e("Database operations","database created / opened... ");
   }

    //CREATE TABLECLIENT
    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL(QUERY);
        Log.e("Database operations","Table created...");
    }

    //ADD CLIENT
    public void addClientInformations (Integer CIN,String name, String surname,String email,Integer phone,String password, String vehType,String vehModel, SQLiteDatabase db){

        ContentValues contentValues = new ContentValues();
        contentValues.put(TablesDB.NewClientInfo.COL_1,CIN );
        contentValues.put(TablesDB.NewClientInfo.COL_2,name );
        contentValues.put(TablesDB.NewClientInfo.COL_3,surname );
        contentValues.put(TablesDB.NewClientInfo.COL_4,email );
        contentValues.put(TablesDB.NewClientInfo.COL_5,phone );
        contentValues.put(TablesDB.NewClientInfo.COL_6,password );
        contentValues.put(TablesDB.NewClientInfo.COL_7,vehType );
        contentValues.put(TablesDB.NewClientInfo.COL_8,vehModel );
        db.insert(TablesDB.NewClientInfo.TABLE_NAME,null,contentValues);

        Log.e("Database operations","One row inserted..."); 

    }

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

    }
}

c# ListBox From SQLite Database

First of all i am very embarrassed to be asking because it seems so simple but ive been scouting the forums and just haven't got my head around how this works.

I am trying to populate my list box from a table from SQLite, But i need the actual value to be the id from the database and not the shown value. Now i know there are alot of already answered questions on here but none of the answers ive read seem to work for me.

I am coming over from php programming and it was very simple to do there.

The code i am using is

    private void fillTheColours(ListBox colourListBox)
    {
        colourListBox.Items.Clear();
        con.Open();
        SQLiteCommand command = new SQLiteCommand(con);
        command.CommandText = "SELECT colourId,suffix FROM colours ORDER BY suffix ASC";
        command.ExecuteNonQuery();

        SQLiteDataReader reader = command.ExecuteReader();

        while (reader.Read())
        {
            colourListBox.Items.Add(reader["suffix"]);
        }
        con.Close();
    }

That is my function and it works nice to put the visible values into the listbox but that value is useless in the next step of the application.

First of all how would i add the id. Second how would i then access that id ? To set it to a variable ?

Just so its known im using c# in a windows form application in visual studio 2015

Cheers in advance Ryan

User Unable to open application after update [duplicate]

This question already has an answer here:

I have one quotes application with local database from assets. I am not developer of android,but I know basic modification only. My some of user have told me that they are unable to install application after update....Many user have not any issue. I have also checked on my 3 device but never faced any issue. But some user have reported that they can not use application because whenever they try to open application they get crashed. I think there some wrong in my database helper class. I have attached it here....Please look and let me know if you find any bug in it.

public class DataBaseHandler extends SQLiteOpenHelper {

    private static String DB_PATH;
    private static String DB_NAME = "TestData";
    private SQLiteDatabase myDataBase;
    private static int DATABASE_VERSION = 9;
    private final Context myContext;
    public DataBaseHandler(Context context) {

        super(context, DB_NAME, null, DATABASE_VERSION);
        this.myContext = context;
        DB_PATH = context.getDatabasePath(DB_NAME).toString();
        Log.e("path", DB_PATH);
    }

    public void createDataBase() throws IOException {

        boolean dbExist = checkDataBase();
        if(dbExist)
        {
        if(DATABASE_VERSION == 1)
        {


            try {

                copyDataBase();
                DATABASE_VERSION = 9;


            } catch (IOException e) {

                throw new Error("Error copying database");

            }
        }
            else if (DATABASE_VERSION == 2)
            {


                try {

                    copyDataBase();
                    DATABASE_VERSION = 9;

                } catch (IOException e) {

                    throw new Error("Error copying database");

                }
            }
                else if (DATABASE_VERSION == 3)
                {


                    try {

                        copyDataBase();
                        DATABASE_VERSION = 9;

                    } catch (IOException e) {

                        throw new Error("Error copying database");

                    }
                }
                    else if (DATABASE_VERSION == 4)
                    {


                        try {

                            copyDataBase();
                            DATABASE_VERSION = 9;

                        } catch (IOException e) {

                            throw new Error("Error copying database");

                        }
                    }
                        else if (DATABASE_VERSION == 5)
                        {


                            try {

                                copyDataBase();
                                DATABASE_VERSION = 9;

                            } catch (IOException e) {

                                throw new Error("Error copying database");

                            }
                        }
                            else if (DATABASE_VERSION == 6)
                            {


                                try {

                                    copyDataBase();
                                    DATABASE_VERSION = 9;

                                } catch (IOException e) {

                                    throw new Error("Error copying database");

                                }
                            }
                                else if (DATABASE_VERSION == 7)
                                {


                                    try {

                                        copyDataBase();
                                        DATABASE_VERSION = 9;

                                    } catch (IOException e) {

                                        throw new Error("Error copying database");

                                    }
                                }
                                    else if (DATABASE_VERSION == 8)
                                    {


                                        try {

                                            copyDataBase();
                                            DATABASE_VERSION = 9;

                                        } catch (IOException e) {

                                            throw new Error("Error copying database");

                                        }


        }
                                    else
        {
        SQLiteDatabase database = null;
        database = this.getWritableDatabase();
        String query_count = "SELECT version FROM users";

        Cursor c_count = database.rawQuery(query_count, null);


        c_count.moveToFirst();
        Integer count = c_count.getInt(c_count.getColumnIndex("version"));
    if(count == DATABASE_VERSION)
    {

    }else
    {
        this.getReadableDatabase();

        try {

            copyDataBase();

        } catch (IOException e) {

            throw new Error("Error copying database");

        }
    }

    }
        }else
        {
            this.getReadableDatabase();

            try {

                copyDataBase();
                DATABASE_VERSION  = 9;

            } catch (IOException e) {

                throw new Error("Error copying database");

            }

        }

    }

    private boolean checkDataBase() {

        SQLiteDatabase checkDB = null;

        try {
            String myPath = DB_PATH;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

        } catch (SQLiteException e) {

            // database does't exist yet.

        }

        if (checkDB != null) {

            checkDB.close();

        }

        return checkDB != null ? true : false;
    }

    private void copyDataBase() throws IOException {

        // 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;

        // 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;
        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) {



    }

}

PDO query returns no result when querying the mysql database

Im developing an Android app which uses mysql database to store information. When I have the following function in my php code:

/*
 * Get User details
 * 
 */
public function getUserDetailsEse($email)
{
   $stmt = $this->conn->prepare("
SELECT u.title
     , u.name
     , u.surname
     , s.reg_num
     , s.barcode
     , s.prog
     , s.yos
     , s.sem
     , s.nat_id
     , s.dob
     , s.mobile
     , s.email
     , s.addr
     , s.registad_courses 
  FROM `users` u
     , `students` s 
 WHERE u.id=s.uza_id 
   AND s.email= ?
");

$stmt->bind_param("s", $email);

$stmt->execute();

if ($stmt->num_rows > 0) {
        // user existed 
        echo 'Query ran but nun';
        $stmt->close();
        return true;
    } else {
        // user not existed
        echo 'Query ddnt run';
        $stmt->close();
        return false;
    }

$stmt->close();
}

In which I want to fetch those details from the mysql database,then display them in my sqlite database to be used inside the app. I then call the function using:

$details = $db->getUserDetailsEse($email);

if ($details!=FALSE){
    $response1["error"] = FALSE;
    $response1["id"] = $details["id"];
    $response1["details"]["title"] = $details["title"];
    $response1["details"]["name"] = $details["name"];
    $response1["details"]["surname"] = $details["surname"];
    $response1["details"]["reg_num"] = $details["reg_num"];
    $response1["details"]["barcode"] = $details["barcode"];
    $response1["details"]["prog"] = $details["prog"];
    $response1["details"]["yos"] = $details["yos"];
    $response1["details"]["sem"] = $details["sem"];
    $response1["details"]["nat_id"] = $details["nat_id"];
    $response1["details"]["dob"] = $details["dob"];
    $response1["details"]["mobile"] = $details["mobile"];
    $response1["details"]["email"] = $details["email"];
    $response1["details"]["addr"] = $details["addr"];
    $response1["details"]["registad_courses"] = $details["registad_courses"];
    echo json_encode($response1);
}  else {
    $response1["error"] = TRUE;
    $response1["error_msg"] = "Failed to fetch details. Login credentials are wrong. Please try again!";
    echo json_encode($response1);
}

When i run the query in phpmyadmin it works fine: enter image description here

But when i try to run it on Postman, i get the following error: enter image description here

Here are the 2 table I'm querying: enter image description here

enter image description here

EDIT:TRYING TO PRINT $DETAILS enter image description here

Add the values of items with same name in the table

I have heater, lamp, tv and so on in a table. the table records their details. There will be some items with more than one entry. such as below.


device watt watt used

heater 220 2000

heater 220 2000

heater 220 2500

tv 1000 3000

tv 1000 5000


I wan to total up all watt used for heater and tv respectively for display in the pie chart, such as heater=6500 W, tv=8000 W. Also, there are many more items that can be added. so how can i do this so that it total up the watt used of every items in the list only.

Thank you

Opening a sqlite database connection from asp

This is just test code but I am trying to just read and display information from an sqlite database.

<table>
    <tr><th>Name</th><th>Surname</th></tr>

    <%

          var dbaseConnection = Server.CreateObject("ADODB.Connection");


          var connectionString = "DRIVER=SQLite3 ODBC Driver; Database= path to test.db; LongNames=0; Timeout=1000; NoTXN=0; SyncPragma=NORMAL; StepAPI=0;";
          dbaseConnection.Open(connectionString);

          var query = "Select * from test order by name asc";
          var recordSet = dbaseConnection.Execute(query);


          while (!recordSet.Eof) {
             Response.write("<tr><td>" + recordSet("name") + '</td><td>' + recordSet("surname") + "</td></tr>");
             recordSet.moveNext();
          }

          recordSet.Close();
          dbaseConnection.Close();

    %>

</table>

I am getting this error Microsoft OLE DB Provider for ODBC Drivers error '80004005' connect failed. Any thoughts? I've activated 32 bit apps in IIS.

Trouble with full joins in SQLite3

I have a schema in SQLite 3 that looks like the following:

CREATE TABLE tags(id INTEGER PRIMARY KEY, tag TEXT NOT NULL, UNIQUE(tag));
CREATE TABLE files(id INTEGER PRIMARY KEY, name TEXT NOT NULL, UNIQUE(name));
CREATE TABLE filetags(file_id INT NOT NULL, tag_id INT NOT NULL, UNIQUE(file_id, tag_id), FOREIGN KEY(file_id) REFERENCES files(id), FOREIGN KEY(tag_id) REFERENCES tags(id));

I've been trying to write a query that, for a given file id, shows every single tag and if that tag is set for that ID. The closest I can get is something like the following:

SELECT * FROM tags t 
LEFT OUTER JOIN filetags ft ON ft.tag_id=t.id 
LEFT OUTER JOIN files f ON f.id=ft.file_id WHERE f.id=@0 OR 
f.id IS NULL

That will work for a file that has 1 or more tag, but for a file with no tags, it excludes all the tags that have at least one file. I've tried several variations of this, but seem to be limited by having to work around sqlite's lack of full and right joins.

How to update android local sqlite database from web using internet connection?

I have developed an educational android application. I have also developed a web application to insert questions on the web and download in android sqlite database. And also the test result is uploaded to the web. The application is working locally without internet when its database is updated. My Problem: I want to update my android application's sqlite database from my website using internet and to upload test result after someone completed the test. So, give me information programmatilly as soon as possible to update my android app from my website and to upload test result from android app to my website. I will be highly thankful!

SQLite onUpgrade() frustration

I'm working with a prepopulated database. Using SQLite Manager in Mozilla, right now I have a dummy database and just wanted to test out the onUpgrade method, so I altered a string in one of the columns, exported it as a new database and as you'll see in my code, tried to open the newly updated version. Also important note, I'm updating the version number by one manually in the code

private static final int DB_VERSION = 3;

and in the onUpgrade

if (newVersion == 3) {
        Log.e("WORKED!!", "onUpgrade executed");

so next time I would update these two numbers to 4. Not sure if I'm doing this right or what's wrong but I'm getting the log message, just not seeing the data updated in the app.

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.util.Log;

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


public class DataBaseHelper extends SQLiteOpenHelper {
    private static String DB_PATH;
    private static final String DB_NAME = "DummyTestOne.sqlite";
    private static final int DB_VERSION = 3;
    private static final String DB_NAME2 = "DummyTestFive.sqlite";
    private SQLiteDatabase mDataBase;
    private final Context mContext;

public static final String DBTABLENAME = "questiontable";
public static final String DBATABLENAME = "answertable";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "question";
public static final String COLUMN_CATEGORY = "category";
public static final String COLUMN_FID = "fid";

public static final String COLUMN_ANSWER = "answer";

public DataBaseHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
    this.mContext = context;

    DB_PATH = context.getDatabasePath(DB_NAME).getPath();


}

public void createDataBase() {
    boolean dbExist = checkDataBase();

    if (dbExist) {

    } else {
        this.getReadableDatabase();
        try {
            copyDataBase();
        } catch (IOException e) {
            throw new Error("Error copying database");
        }
    }
}

private boolean checkDataBase() {
    SQLiteDatabase checkDB = null;

    try {
        checkDB = SQLiteDatabase.openDatabase(DB_PATH, null, SQLiteDatabase.OPEN_READWRITE);
    } catch (SQLiteException e) {
        Log.e(this.getClass().toString(), "Error while checking db");
    }

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

    return checkDB != null ? true : false;
}

private void copyDataBase() throws IOException {
    InputStream externalDbStream = mContext.getAssets().open(DB_NAME);
    OutputStream localDbStream = new FileOutputStream(DB_PATH);

    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = externalDbStream.read(buffer)) > 0) {
        localDbStream.write(buffer, 0, bytesRead);
    }


    localDbStream.flush();
    localDbStream.close();
    externalDbStream.close();
}

public void openDataBase() throws SQLException {


    mDataBase = this.getWritableDatabase();

}

@Override
public synchronized void close() {
    if (mDataBase != null) {
        mDataBase.close();
    }
    super.close();
}

public Cursor getCursorForAllQs() {
    SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
    queryBuilder.setTables(DBTABLENAME);

    String[] asColumnsToReturn = new String[]{COLUMN_ID, COLUMN_NAME, COLUMN_CATEGORY, COLUMN_FID};

    Cursor mCursor = queryBuilder.query(mDataBase, asColumnsToReturn, null,
            null, null, null, "_id");

    return mCursor;
}

public List<String> getAnswersForQ(int questionFid) {
    List<String> answers = new ArrayList<>();
    SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
    queryBuilder.setTables(DBATABLENAME);
    String[] tableColumns = new String[]{DataBaseHelper.COLUMN_ANSWER};
    String where = "fid = ?";
    String[] selectionArgs = new String[]{String.valueOf(questionFid)};
    String orderBy = DataBaseHelper.COLUMN_ID;


    Cursor c = queryBuilder.query(mDataBase, tableColumns, where, selectionArgs, null, null, orderBy);
    if (c.moveToFirst()) {
        do {
            try{
                answers.add(c.getString(c.getColumnIndex(DataBaseHelper.COLUMN_ANSWER)));
            } catch (Exception e) {
                Log.e("FAILED", c.getString((c.getColumnIndex(DataBaseHelper.COLUMN_ANSWER))));
            }

        } while (c.moveToNext());
    }
    Log.d("getAnswersForQ", answers.toString());
    return answers;

}

public String getName(Cursor c) {
    return (c.getString(1));
}



@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    if (newVersion == 3) {
        Log.e("WORKED!!", "onUpgrade executed");
    }
    if (newVersion > oldVersion) {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        String dbFilePath = DB_PATH + DB_NAME;


        try {
            inputStream = mContext.getAssets().open(DB_NAME2);

            outputStream = new FileOutputStream(dbFilePath);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }

            outputStream.flush();
            outputStream.close();
            inputStream.close();
        } catch (IOException e) {
            throw new Error("Problem copying database from resource file.");
        }
    }
}
}

QT QSqlDatabase open() function creates a sqlite database

I'm trying to open a sqlite database file in QT using .open() function and if the file doesn't exit, .open() doesn't return a false, it just creates a new file in the given directory. My code:

QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("C:/sqlite/newDB.db");

    if(!db.open()){
        ui->test->setText("Fail");
    }
    else{
        ui->test->setText("Success");
    }

How to make it return a true or false ?

RuntimeException - java.lang.IllegalArgumentException: column '_id' does not exist [duplicate]

In my app I'm trying to read data from a table in my DB, which is created as follows:

public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
    String createDreamTable = String.format("CREATE TABLE IF NOT EXISTS %s" +
            "( %s INTEGER PRIMARY KEY AUTOINCREMENT, " +
            "%s VARCHAR, " +
            "%s TEXT);",
            DreamContract.Dream.DREAM_TABLE_NAME,
            DreamContract.Dream._ID,
            DreamContract.Dream.COLUMN_NAME_DREAM_TITLE,
            DreamContract.Dream.COLUMN_NAME_DREAM_CONTENT);
    Log.d("avirankatz", createDreamTable);
    db.execSQL(createDreamTable);
}

When I try to get data from DB using GetDreamTitles, as seen below, I get java.lang.IllegalArgumentException: column '_id' does not exist

public Cursor getDreamTitles() {
    return getReadableDatabase().rawQuery(String.format("SELECT %s FROM %s", DreamContract.Dream.COLUMN_NAME_DREAM_TITLE, DreamContract.Dream.DREAM_TABLE_NAME), null);
}

EDIT:

DreamContract.Dream:

public static abstract class Dream implements BaseColumns {
    public static final String DREAM_TABLE_NAME = "dreamDiary";
    public static final String COLUMN_NAME_DREAM_TITLE = "title";
    public static final String COLUMN_NAME_DREAM_CONTENT = "dreamContent";
}

android app crash when touch login button with volley [duplicate]

This question already has an answer here:

i'm a beginner in developing android app. my reference web is android hive. i'm trying to combine these two projects. http://ift.tt/1gfNOBZ and with http://ift.tt/1CvjRaY. after the app finished, the registration form and register activity works finely but after i key in all the credentials, the app was forced close. everything's fine until i added the the project of material design.

the error in logcat

FATAL EXCEPTION: main Process: amira.hasnul.feeds, PID: 3718 java.lang.NullPointerException at com.android.volley.Request.(Request.java:136) at com.android.volley.toolbox.StringRequest.(StringRequest.java:43) at amira.hasnul.feeds.activity.LoginActivity$5.(LoginActivity.java:0) at amira.hasnul.feeds.activity.LoginActivity.checkLogin(LoginActivity.java:113) at amira.hasnul.feeds.activity.LoginActivity.access$200(LoginActivity.java:31) at amira.hasnul.feeds.activity.LoginActivity$1.onClick(LoginActivity.java:79) at android.view.View.performClick(View.java:4487) at android.view.View$PerformClick.run(View.java:18746) at android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:149) at android.app.ActivityThread.main(ActivityThread.java:5268) 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:793) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609) at dalvik.system.NativeStart.main(Native Method)

my AndroidManifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://ift.tt/nIICcg"
package="amira.hasnul.feeds">

<uses-permission android:name="android.permission.INTERNET" />

<application
    android:name="amira.hasnul.feeds.app.AppController"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".activity.LoginActivity"
        android:label="@string/app_name"
        android:launchMode="singleTop"
        android:windowSoftInputMode="adjustPan" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".activity.RegisterActivity"
        android:label="@string/app_name"
        android:launchMode="singleTop"
        android:windowSoftInputMode="adjustPan" />
    <activity
        android:name=".activity.MainActivity"
        android:label="@string/app_name"
        android:launchMode="singleTop" />
</application>

</manifest>

LoginActivity.java`

    package amira.hasnul.feeds.activity;

    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;

    import com.android.volley.Request.Method;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.StringRequest;

    import org.json.JSONException;
    import org.json.JSONObject;

    import java.util.HashMap;
    import java.util.Map;

    import amira.hasnul.feeds.R;
    import amira.hasnul.feeds.app.AppConfig;
    import amira.hasnul.feeds.app.AppController;
    import amira.hasnul.feeds.helper.SQLiteHandler;
    import amira.hasnul.feeds.helper.SessionManager;

public class LoginActivity extends Activity {
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    inputEmail = (EditText) findViewById(R.id.email);
    inputPassword = (EditText) findViewById(R.id.password);
    btnLogin = (Button) findViewById(R.id.btnLogin);
    btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);

    // Progress dialog
    pDialog = new ProgressDialog(this);
    pDialog.setCancelable(false);

    // SQLite database handler
    db = new SQLiteHandler(getApplicationContext());

    // Session manager
    session = new SessionManager(getApplicationContext());

    // Check if user is already logged in or not
    if (session.isLoggedIn()) {
        // User is already logged in. Take him to main activity
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    // Login button Click Event
    btnLogin.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            String email = inputEmail.getText().toString().trim();
            String password = inputPassword.getText().toString().trim();

            // Check for empty data in the form
            if (!email.isEmpty() && !password.isEmpty()) {
                // login user
                checkLogin(email, password);
            } else {
                // Prompt user to enter credentials
                Toast.makeText(getApplicationContext(),
                        "Please enter the credentials!", Toast.LENGTH_LONG)
                        .show();
            }
        }

    });

    // Link to Register Screen
    btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            Intent i = new Intent(getApplicationContext(),
                    RegisterActivity.class);
            startActivity(i);
            finish();
        }
    });

}

/**
 * function to verify login details in mysql db
 * */
private void checkLogin(final String email, final String password) {
    // Tag used to cancel the request
    String tag_string_req = "req_login";

    pDialog.setMessage("Logging in ...");
    showDialog();

    StringRequest strReq = new StringRequest(Method.POST,
            AppConfig.URL_LOGIN, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, "Login Response: " + response.toString());
            hideDialog();

            try {
                JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");

                // Check for error node in json
                if (!error) {
                    // user successfully logged in
                    // Create login session
                    session.setLogin(true);

                    // Now store the user in SQLite
                    String uid = jObj.getString("uid");

                    JSONObject user = jObj.getJSONObject("user");
                    String name = user.getString("name");
                    String email = user.getString("email");
                    String created_at = user
                            .getString("created_at");

                    // Inserting row in users table
                    db.addUser(name, email, uid, created_at);

                    // Launch main activity
                    Intent intent = new Intent(LoginActivity.this,
                            MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    // Error in login. Get the error message
                    String errorMsg = jObj.getString("error_msg");
                    Toast.makeText(getApplicationContext(),
                            errorMsg, Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                // JSON error
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
            }

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Login Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(),
                    error.getMessage(), Toast.LENGTH_LONG).show();
            hideDialog();
        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            // Posting parameters to login url
            Map<String, String> params = new HashMap<String, String>();
            params.put("email", email);
            params.put("password", password);

            return params;
        }

    };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}

private void showDialog() {
    if (!pDialog.isShowing())
        pDialog.show();
}

private void hideDialog() {
    if (pDialog.isShowing())
        pDialog.dismiss();
}
}

MainActivity.java

package amira.hasnul.feeds.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment; 
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import java.util.HashMap;

import amira.hasnul.feeds.R;
import amira.hasnul.feeds.helper.SQLiteHandler;
import amira.hasnul.feeds.helper.SessionManager;

public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {

private SQLiteHandler db;
private SessionManager session;

private static String TAG = MainActivity.class.getSimpleName();

private Toolbar mToolbar;
private FragmentDrawer drawerFragment;

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

    //seesion
    // SqLite database handler
    db = new SQLiteHandler(getApplicationContext());
    // session manager
    session = new SessionManager(getApplicationContext());
    if (!session.isLoggedIn()) {
        logoutUser();
    }
    //end session
    // Fetching user details from SQLite
    HashMap<String, String> user = db.getUserDetails();

    mToolbar = (Toolbar) findViewById(R.id.toolbar);

    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayShowHomeEnabled(true);

    drawerFragment = (FragmentDrawer)
            getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
    drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
    drawerFragment.setDrawerListener(this);

    // display the first navigation drawer view on app launch
    displayView(0);
}

@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, 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;
    }

    if(id == R.id.action_search){
        Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onDrawerItemSelected(View view, int position) {
    displayView(position);
}

private void logoutUser() {
    session.setLogin(false);

    db.deleteUsers();

    // Launching the login activity
    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
    startActivity(intent);
    finish();
}

private void displayView(int position) {
    Fragment fragment = null;
    String title = getString(R.string.app_name);
    switch (position) {
        case 0:
            fragment = new HomeFragment();
            title = getString(R.string.title_home);
            break;
        case 1:
            fragment = new FriendsFragment();
            title = getString(R.string.title_friends);
            break;
        case 2:
            fragment = new MessagesFragment();
            title = getString(R.string.title_messages);
            break;
        case 3:
            title = getString(R.string.title_logout);
            //logoutUser();
        default:
            break;
    }

    if (fragment != null) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.container_body, fragment);
        fragmentTransaction.commit();

        // set the toolbar title
        getSupportActionBar().setTitle(title);
    }
}

}