mercredi 1 juillet 2015

I am getting wrong value from sqlite table in swift

I am getting wrong value from sqlite table. this is my code

code :

    var arrtribute_Mast_List : NSMutableArray = []
    var querySQL = String(format:"SELECT * FROM %@ ORDER BY %@", TABLE_ATTRIBUTE_MASTER, ATTRIBUTE_MASTER_ATTR_ID)
    var statement:COpaquePointer = nil
    //querySQL =   querySQL.String(NSUTF8StringEncoding, allowLossyConversion: false)

    if (sqlite3_prepare_v2(database, querySQL, -1, &statement, nil) == SQLITE_OK) {
        while(sqlite3_step(statement) == SQLITE_ROW) {
            let name  = sqlite3_column_text(statement, 2)
            let attributeName = String.fromCString(UnsafePointer<CChar>(name))
            println("Attribute value = \(attributeName)")
         }
        sqlite3_finalize(statement);

    }

I am getting output:

   Attribute value = Optional("Shamitabh")

Need Output :

   Attribute value = "Shamitabh"

How to make an pdo_sqlite connection from binary stream in PHP

Having a .sqlite file in a memory stream (php://memory), I want to pipe it to pdo_sqlite driver to create a connection. Is this possible?

Its for testing purposes, I want to recreate DBs quickly without recreate schema at each time nor using tmpfs.

PyQt Python : how to insert text which on the QlineEdit?

I have an error when I insert data which form QlinEdit .
You can see the button1Clicked(self) method ,
I can't execute q.exec_("insert into COMPANY (id, name, age, address, salary) values (self.IDEdit.text(),self.NameEdit.text(),self.AgeEdit.text(),self.AddressEdit.text(),self.SalaryEdit.text())") this code .
But I can get the text when I use print(self.IDEdit.text()).
I don't understand why . I hope someone can help me.

#-*- coding: utf-8 -*- 
import sys
import sqlite3
from PyQt4 import QtCore, QtGui
from PyQt4.QtSql import * 

def createConnection(): 
    db=QSqlDatabase.addDatabase("QSQLITE") 
    db.setDatabaseName("test.db")
    db.open()

def createTable(): 
    q=QSqlQuery() #
    q.exec_("create table if not exists COMPANY (ID INT PRIMARY KEY NOT NULL,NAME TEXT NOT NULL,AGE INT NOT NULL,ADDRESS CHAR(50),SALARY REAL)") 
    q.exec_("commit") 

class Model(QSqlTableModel): 
    def __init__(self,parent): 
        QSqlTableModel.__init__(self,parent) 
        self.setTable("COMPANY") 
        self.select() 
        self.setEditStrategy(QSqlTableModel.OnManualSubmit) 

class TestWidget(QtGui.QWidget): 
    def __init__(self): 
        QtGui.QWidget.__init__(self)

        vbox=QtGui.QVBoxLayout(self) 
        self.view=QtGui.QTableView() 
        self.model=Model(self.view) 
        self.view.setModel(self.model) 
        vbox.addWidget(self.view)

        self.resize(900,300)

        self.component()


    def component(self):
        ID = QtGui.QLabel('ID :', self)
        ID.move(30, 180)

        self.IDEdit = QtGui.QLineEdit(self) 
        self.IDEdit.move(70, 180)
        self.IDEdit.setFocus()

        Name = QtGui.QLabel('NAME :', self)
        Name.move(180, 180)
        self.NameEdit = QtGui.QLineEdit(self)
        self.NameEdit.move(230, 180)

        Age = QtGui.QLabel('AGE :', self)
        Age.move(340, 180)
        self.AgeEdit = QtGui.QLineEdit(self)
        self.AgeEdit.move(380, 180)

        Address = QtGui.QLabel('ADDRESS :', self)
        Address.move(500, 180)
        self.AddressEdit = QtGui.QLineEdit(self)
        self.AddressEdit.move(560, 180)

        Salary = QtGui.QLabel('SALARY :', self)
        Salary.move(670, 180)
        self.SalaryEdit = QtGui.QLineEdit(self)
        self.SalaryEdit.move(730, 180)

        button1= QtGui.QPushButton('submit', self)
        button1.setGeometry(730, 240, 70, 30) 
        self.connect(button1, QtCore.SIGNAL('clicked()'),self.button1Clicked)




    def button1Clicked(self):
        q=QSqlQuery()
        q.exec_("insert into COMPANY (id, name, age, address, salary) values (self.IDEdit.text(), self.NameEdit.text(),self.AgeEdit.text(),self.AddressEdit.text(),self.SalaryEdit.text())")

        q.exec_("commit")

        print (self.IDEdit.text()) 
        print (self.NameEdit.text()) 
        print (self.AgeEdit.text()) 
        print (self.AddressEdit.text()) 
        print (self.SalaryEdit.text()) 


if __name__=="__main__": 
    app=QtGui.QApplication(sys.argv) 
    createConnection()
    createTable() 
    w=TestWidget() 
    w.show() 
    sys.exit(app.exec_())

SQLiteException: CannotOpen file

Sometimes a user report this error:

[Type]:[SQLiteException]
[Message]:[Could not open database file: AppSettings.db (CannotOpen)]
[StackTrace]:[   at Community.SQLite.SQLiteConnection..ctor(String databasePath, SQLiteOpenFlags openFlags, Boolean storeDateTimeAsTicks)
                 at Cirrious.MvvmCross.Community.Plugins.Sqlite.WindowsPhone.MvxWindowsPhoneSQLiteConnectionFactory.CreateSQLiteConnection(String databasePath, Boolean storeDateTimeAsTicks)
                 at Cirrious.MvvmCross.Community.Plugins.Sqlite.MvxBaseSQLiteConnectionFactory.CreateFileDb(SQLiteConnectionOptions options)
                 at Cirrious.MvvmCross.Community.Plugins.Sqlite.MvxBaseSQLiteConnectionFactory.CreateEx(SQLiteConnectionOptions options)
                 at Cirrious.MvvmCross.Community.Plugins.Sqlite.MvxBaseSQLiteConnectionFactory.CreateEx(String address, SQLiteConnectionOptions options)
                 at Cirrious.MvvmCross.Community.Plugins.Sqlite.MvxBaseSQLiteConnectionFactory.Create(String address)
                 at Timokids.Core.Services.AppSettingsService..ctor(ISQLiteConnectionFactory factory)]

My problem is, this error don't show always so I cannot debug it.

In most of the times the code run with no errors.

The error occurs when I call factory.Create().

Here is my code:

public class AppSettingsService : IAppSettingsService
{
    private readonly ISQLiteConnection _connection;

    public AppSettingsService(ISQLiteConnectionFactory factory)
    {
        _connection = factory.Create("AppSettings.db");
    }
}

Is there anything I can do for solve this?

Access SQLite from BaseAdapter

I have a Base Adapter Class and want to acces an SQLite Table from it with a Cursor, but I have trouble with the context. Am I getting the context the right way?

public class GetAllEntrysListViewAdapter extends BaseAdapter {

private JSONArray dataArray;
private Activity activity;
private static LayoutInflater inflater = null;
public Cursor cursor;
private SQLiteDatabase dbase;
DbHelper dbh;
private Context context;
String pos;

public GetAllEntrysListViewAdapter(JSONArray jsonArray, Activity a) {
    this.dataArray = jsonArray;
    this.activity = a;
    inflater = (LayoutInflater)this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

public GetAllEntrysListViewAdapter(Context context) {
    this.context = context;
}
//...
dbh = new DbHelper(context);
        cursor = getLikes(dbh);
        cursor.moveToFirst();
        if (cursor.moveToFirst()) {
            do {
                if (Integer.parseInt(cursor.getString(2)) == 1) {
                    cell.likeImage.setImageResource(R.drawable.heart_filled);
                }
            }
            while(cursor.moveToNext());
        }
        else {
            cursor.close();
        }
        cursor.close();
}
public Cursor getLikes(DbHelper dbh) {
    dbase = dbh.getReadableDatabase();
    String columns[] = {dbh.LIKES_MARKERID, dbh.LIKES_POSITION, dbh.LIKES_LIKE};
    String selection = dbh.LIKES_MARKERID + " LIKE ? AND " + dbh.LIKES_POSITION + " LIKE ? ";
    String args[] = {pinboard.markerID.toString(), pos};
    Cursor cursor = dbase.query(dbh.TABLE_LIKES, columns, selection, args , null, null, null, null);
    return cursor;
}

This is the error message I get:

SQLLITEDATABASE crash-oncreate not called ? db.getreadabledatabase/getwritabledatabase crash

I'm a beginner at android and sqllite as well. I have been trying to build a database which retrieves and shows entries like items ,price and time, Ive looked through the all the other topics but i just cant seem to find why does it crash.. Ive tried a LOT of ways to make it work but this is the code im trying to use

public class data extends SQLiteOpenHelper {
private static final String DATABASE_NAME ="items.db";
private static final String t="database created";
    private static final int DATABASE_VERSION=1;
Context ct;
SQLiteDatabase db;
    public data (Context ctx) {
        super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
ct=ctx;

       }
    @Override
    public void onCreate(SQLiteDatabase db)
    {db.execSQL("CREATE TABLE  record (_id primary key autoincrement,TIME text,ITEM text,TYPE text,AMT text)");
        int duration = Toast.LENGTH_LONG;
        Toast toast = Toast.makeText(ct, t, duration);
        toast.show();
    }

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

}

here is the class which I use to run the data class object

public class mainscreen extends Activity {
    private data Data;
    private static String[] cols={"_id","TIME","ITEM","TYPE","AMT"};
    private static String ORDER_BY = TIME + "DESC";
    private static int[] TO={R.id.textView5,R.id.textView3,R.id.textView,R.id.textView4,R.id.textView2};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mainscreen);
      Data = new data(this);



        }

public void tryit(View view)
{
time t=new time();
data test =new data(this);


           add(t.tostring(),"tomato", "200", "Food");



   //Cursor cursor = getd();
   // show(cursor);
}


private void add(String t,String item, String price,String type) {
     SQLiteDatabase db = Data.getWritableDatabase();


    db.execSQL("insert into "+TABLE_NAME+" values(null,'" + t + "','" + item + "','" + type + "','" + price + "')");


    }

As of now Im simply trying to get the database to show some entries i add using add(); 1.It does not seem to run OnCreate at all with the Data class,(i used toast to try and see if the oncreate runs at all) 2.trying to use a SQLLITEDatabase object for getreadabledatabase/getwritabledatabase causes a crash 3.Even the simple execSQL("create******") method above is causing a crash. 4.The worst part is it ACTUALLY worked 2-3 times yesterday.It showed me 5-8 entries using the listview just as I wanted.and is crashing now sob . I just cant seem to find the problem!!

Im not too sure how to get a stackdump/trace so if needed please tell me how to get it . If anyone could tell me what Im doing wrong. Ive marked out the cursor/adapters as theres no point getting that to work if the database doesnt work

I use tryit() by a button to start the insert...and it crashes at SQLiteDatabase db = Data.getWritableDatabase(); I think the whole problem is because for some reason the database is not getting created , but even using the plain db.execSQL statement whether in onCreate or by using a db object in data class and execsql at constructor crashes the app.

Null pointer exception whilst adding to the DB

I'm developing a simple bird-watching log app for one of my classes at college and I seem to not be able to spot what the heck is going wrong, so after spending a few days banging my head against the wall, I suppose it'd make more sense to just ask for someone with a fresh pair of eyes to have a look.

The app is really simple - I have two activities, one with a ListView, that gets populated by the DB (MainActivity) and another, that takes the arguments to create a new entry (AddActivity). Besides these I have a DBHelper (MySQLiteHelper) to handle my DB calls, a simple class to describe how my object should look like (Sighting), a DataSource class (SightingDataSource) to handle facilitate the calls to the helper and a bunch of non-relevant resources (layouts, etc.) The AddActivity blows up with null pointer exceptions whilst calling the addSighting method. It also for whatever reason doesn't like the int typecast of the bCount field, so for testing purposes I've set a static int, just whilst I figure out the exception portion of my problem.

Here's my source: AddActivity:

package com.vladislavtachev.cscb763;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class AddActivity extends ListActivity {

    public SightingsDataSource datasource;

    private EditText locFld = null;
    private EditText bNameFld = null;
    private EditText bCountFld = null;
    private Button addSightBtn = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        locFld = (EditText) findViewById(R.id.locFld);
        bNameFld = (EditText) findViewById(R.id.bNameFld);
        bCountFld = (EditText) findViewById(R.id.bCountFld);
        setContentView(R.layout.activity_add);
        addSightBtn = (Button) findViewById(R.id.addSightBtn);
        addSightBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addSight(v);
            }
        });


    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) { return true; }
        return super.onOptionsItemSelected(item);
    }


    public void addSight(View view){
        long time = System.currentTimeMillis()/1000L;
                datasource.addSighting(locFld.getText().toString(),
                        time,
                        bNameFld.getText().toString(),3
//                        Integer.parseInt(bCountFld.getText().toString())
                );
//        datasource.addSighting(sighting);
        setContentView(R.layout.activity_main);

    }
}

SightingDataSource

package com.vladislavtachev.cscb763;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class SightingsDataSource {

    //DB info
    private SQLiteDatabase database;
    private MySQLiteHelper dbHelper;
    private String[] allColumns = { MySQLiteHelper.COL_ID, MySQLiteHelper.COL_LOCATION,
            MySQLiteHelper.COL_TIME, MySQLiteHelper.COL_BNAME, MySQLiteHelper.COL_BCOUNT };

    public SightingsDataSource(Context context){
        dbHelper = new MySQLiteHelper(context);
    }

    public void open(){
        database = dbHelper.getWritableDatabase();
    }

    public void close(){ dbHelper.close(); }

    public void addSighting(String l, long time, String bName, int bCount){
        ContentValues values = new ContentValues();
        values.put(MySQLiteHelper.COL_LOCATION, l);
        values.put(MySQLiteHelper.COL_TIME, time);
        values.put(MySQLiteHelper.COL_BNAME, bName);
        values.put(MySQLiteHelper.COL_BCOUNT, bCount);
        long insertId = database.insert(MySQLiteHelper.TABLE_SIGHTINGS, null, values);
        Cursor cursor = database.query(MySQLiteHelper.TABLE_SIGHTINGS, allColumns, MySQLiteHelper.COL_ID + " = " + insertId, null, null, null, null);
        cursor.moveToFirst();
        Sighting newSighting = cursorToSighting(cursor);
        cursor.close();
    }

    private Sighting cursorToSighting(Cursor cursor){
        Sighting sighting = new Sighting();
        sighting.setId(cursor.getLong(0));
        sighting.setLocation(cursor.getString(1));
        sighting.setTime(cursor.getLong(2));
        sighting.setbName(cursor.getString(3));
        sighting.setbCount(cursor.getInt(4));
        return sighting;
    }

    public List<Sighting> getAllSightings(){
        List<Sighting> sightings = new ArrayList<Sighting>();
        Cursor cursor = database.query(MySQLiteHelper.TABLE_SIGHTINGS, allColumns, null, null, null, null, null);
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            Sighting sighting = cursorToSighting(cursor);
            sightings.add(sighting);
            cursor.moveToNext();
        }
        cursor.close();
        return sightings;
    }
}

MySQLiteHelper

package com.vladislavtachev.cscb763;

import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
import android.content.Context;

public class MySQLiteHelper extends SQLiteOpenHelper{

    public final static String DB_NAME = "sightings.db";
    public final static int DB_VER = 1;
    public final static String TABLE_SIGHTINGS = "sightings";
    public final static String COL_ID = "_id";
    public final static String COL_LOCATION = "_loc";
    public final static String COL_TIME = "_time";
    public final static String COL_BNAME = "_bname";
    public final static String COL_BCOUNT = "_bcount";

    private final static String DB_CREATE = "create table if not exists"
            + TABLE_SIGHTINGS + "("
            + COL_ID + " integer primary key autoincrement, "
            + COL_LOCATION + " text not null, "
            + COL_TIME + " integer not null, "
            + COL_BNAME + " text not null, "
            + COL_BCOUNT + " integer not null);";

    public MySQLiteHelper(Context context){
        super(context, DB_NAME, null, DB_VER);
    }

    @Override
    public void onCreate(SQLiteDatabase database){
        database.execSQL(DB_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase database, int oldVer, int newVer){
        database.execSQL("DROP TABLE IF EXISTS " + TABLE_SIGHTINGS);
        onCreate(database);
    }

}

activity_add.xml layout

<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
    xmlns:tools="http://ift.tt/LrGmb4"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.vladislavtachev.cscb763.AddActivity"
    style="@android:style/Theme.Material">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/lblBName"
        android:id="@+id/lblBName"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/bNameFld"
        android:layout_below="@+id/lblBName"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/lblBCount"
        android:id="@+id/lblBCount"
        android:layout_alignBottom="@+id/bCountFld"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:ems="10"
        android:id="@+id/bCountFld"
        android:layout_below="@+id/bNameFld"
        android:layout_alignRight="@+id/bNameFld"
        android:layout_alignEnd="@+id/bNameFld"
        android:layout_toEndOf="@+id/lblBCount"
        android:layout_toRightOf="@+id/lblBCount" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/lblLocation"
        android:id="@+id/lblLocation"
        android:layout_alignBottom="@+id/locFld"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/locFld"
        android:layout_below="@+id/bCountFld"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_toEndOf="@+id/lblLocation"
        android:layout_toRightOf="@+id/lblLocation" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/addSightBtn"
        android:id="@+id/addSightBtn"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"/>

    <ListView
        android:layout_width="10px"
        android:layout_height="10px"
        android:id="@android:id/list"
        android:layout_alignParentBottom="true"
        android:layout_alignRight="@+id/locFld"
        android:layout_alignEnd="@+id/locFld" />
</RelativeLayout>

Error stack

07-01 18:08:49.131    2384-2384/com.vladislavtachev.cscb763 E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.vladislavtachev.cscb763, PID: 2384
    java.lang.NullPointerException: Attempt to invoke virtual method 'void com.vladislavtachev.cscb763.SightingsDataSource.addSighting(java.lang.String, long, java.lang.String, int)' on a null object reference
            at com.vladislavtachev.cscb763.AddActivity.addSight(AddActivity.java:75)
            at com.vladislavtachev.cscb763.AddActivity$1.onClick(AddActivity.java:38)
            at android.view.View.performClick(View.java:4780)
            at android.view.View$PerformClick.run(View.java:19866)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            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:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

All help is appreciated!

Cheers, V./