dimanche 31 janvier 2016

Is there any way to delete the sqlite.wal while application crashes

One of our pen tester has raised the security concern. He wants us to remove the sqlite.wal when application crashes and when application goes to background. We have writen one function in appdelgate class which will remove the wal file.

Please find the code snippet below.

void uncaughtExceptionHandler(NSException *exception)
{
    id appdelegate = [[UIApplication sharedApplication] delegate];

    //Clear cache
    for(NSPersistentStore *store in [appdelegate persistentStoreCoordinator].persistentStores)
    {

        NSLog(@"\n\nUNCAUGHT EXCEPTION --- %@\n\n",[exception description]);
        NSError *error;
        NSURL *storeURL = store.URL;

        NSPersistentStoreCoordinator *storeCoordinator = [appdelegate persistentStoreCoordinator];
        [storeCoordinator removePersistentStore:store error:&error];
        [[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:&error];
    }

    [appdelegate setPersistentStoreCoordinator:nil];
    [appdelegate setManagedObjectContext:nil];
    NSManagedObjectModel *managedObjectModel = [appdelegate managedObjectModel];
    managedObjectModel = nil;
}

Our pen tester is using iExplorer tool to access sqlite.wal file. same tool I have installed in mac and tested. What I found was weird. same code is working fine in mac matchie. But in window still we can see the wal file.

Please suggest me to solve this issue. Thanks in advance.

Load SQLite Table Items into a ReyclerView

I am trying to load some items from a table into a RecyclerView on my Android application. Some of the methods cause my application to crash and I have struggled to find a solution.

Here is my code for my function that sets the items:

public void loadItems() {
    List<ListsRecyclerViewList> list = Arrays.asList(new ListsRecyclerViewList("item", "item"));
    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview_activity_lists_view_all_lists);
    LinearLayoutManager linearLayoutManager = new    LinearLayoutManager(this);
    ListsRecyclerViewListAdapter adapter = new ListsRecyclerViewListAdapter(list);

    recyclerView.setLayoutManager(linearLayoutManager);
    recyclerView.setAdapter(adapter);
}

Here is my adapter:

List<ListsRecyclerViewList> list;

public ListsRecyclerViewListAdapter(List<ListsRecyclerViewList> list) {
    this.list = list;
}

@Override
public ListsRecyclerViewListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_recyclerview_view_list, parent, false);
    ListsRecyclerViewListViewHolder viewHolder = new ListsRecyclerViewListViewHolder(view);

    return viewHolder;
}

@Override
public void onBindViewHolder(ListsRecyclerViewListViewHolder holder, int position) {
    holder.name.setText(list.get(position).getName());
    holder.date.setText(list.get(position).getDate());
}

@Override
public int getItemCount() {
    return list.size();
}

public static class ListsRecyclerViewListViewHolder extends RecyclerView.ViewHolder {
    TextView name;
    TextView date;

    public ListsRecyclerViewListViewHolder(View view) {
        super(view);

        this.name = (TextView) view.findViewById(R.id.layout_recyclerview_view_list_name);
        this.date = (TextView) view.findViewById(R.id.layout_recyclerview_view_list_date);
    }
}

Also, this is the code for the RecyclerView items:

public String name;
public String date;

public ListsRecyclerViewList(String name, String date) {
    this.name = name;
    this.date = date;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getDate() {
    return name;
}

public void setDate(String date) {
    this.date = date;
}

And finally, this is what I am trying to implement but throws errors:

public void loadItems() {
    List<ListsRecyclerViewList> list = Arrays.asList(new ListsRecyclerViewList("item", "item"));
    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview_activity_lists_view_all_lists);
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    ListsRecyclerViewListAdapter adapter = new ListsRecyclerViewListAdapter(list);

    ListsDatabaseClass database = new ListsDatabaseClass(this);
    database.open();

    Cursor cursor = database.loadLists();
    list.add(new ListsRecyclerViewList(cursor.getString(1), cursor.getString(2)));
    database.close();

    recyclerView.setLayoutManager(linearLayoutManager);
    recyclerView.setAdapter(adapter);
}

Thanks for any suggestions.

Show my data to listview in Android

I am new android programmer and don't know many things about listview. By the way , I have two ArrayList of database entities;

first is country and properties are : Id , Name. second is city and properties are : Id , Name , CountryId

All data are stored in database (and coming from there and I put them in ArrayList such as ArrayList<City> and ArrayList<Country>).

I want to bind ArrayList<Country> to a listview and when user click on an item then show cities that are related to that country(By the Id of the Country).

so how to bind my ArrayList<Country> to listview that show the name , and store Id in any thing such as attribute of item of listview then when user click on item then I can fetch the Id and show ArrayList<City>.

Right way to store `JSON` object in a `sqlite`, nodejs

I don't know the right way to store JSON object in a sqlite text field, using nodejs sqlite3 driver. I have tried the following ways:

  1. I simply write JSON object without any conversion. When I look into the table, jstr value looks like {"melicode":9876543210} but after retrieve it JSON.parse(jstr) fails with SyntaxError: Unexpected token m
  2. Then before write it to the table I tried JSON.stringify(jobj), now jstr value looks like {\"melicode\":9876543210} but when I try to convert it, JSON.parse(jstr) fails with SyntaxError: Unexpected token \

    It looks like sqlite3 omits double quotes when retrieve TEXT, no matter it has a '\' char before or not.

How do I access a SQLITE database from HTML and the output thus obtained be a drop down list?

<select>
  <option value="A">A</option>
  <option value="B">B</option>
  <option value="C">C</option>
</select>

The values A, B, C must be obtained from a SQLITE database. How can I do that?

Get rid of a duplicate row from SQL table

I have a reservation table like this

place      day       name1     floor1    name2     floor2
---------  --------  --------- --------- --------- ---------
Anaheim    Monday    Sean      3rd       Jenny     2nd
Anaheim    Monday    Jenny     2nd       Sean      3rd
Cerritos   Saturday  Dennis    4th       Sean      3rd

As you can see, first and second rows are just duplicate with different order. I want to have a final table like

place      day       name1     floor1    name2     floor2
---------  --------  --------- --------- --------- ---------
Anaheim    Monday    Sean      3rd       Jenny     2nd
Cerritos   Saturday  Dennis    4th       Sean      3rd

I was thinking about something like this

SELECT t1.place, t1.day, t1.name1, t1.floor, t1.name2, t1.floor2
FROM table t1, table t2
WHERE NOT (t1.place = t2.place AND t1.day = t2.day AND
           t1.name1 = t2.name2 AND t1.floor1 = t1.floor2);

But this didn't work :( Maybe my understanding is too short..

How should I approach this?

Automatic Table creation - Hibernate

I am trying to recreate my Oracle database in SQLite using Hibernate. I have used the hbm2ddl tag value as "create". Still my SQLite DB is not getting created. Could someone please help me with this ? I have posted below my cfg.xml file

<!-- language: xml -->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://ift.tt/UNuKEc">
<hibernate-configuration>
<session-factory name="">
<property name="hibernate.connection.driver_class"> org.sqlite.JDBC  </property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.username"></property>
<property name="hibernate.dialect"> org.hibernate.dialect.SQLiteDialect </property>
<property name="connection.url">jdbc:sqlite:resources/newdb.db</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.order_updates">true</property>
<property name="hibernate.order_inserts">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>
</session-factory>
</hibernate-configuration>

Why is the cursor never null?

I am making an android app where I am storing some id's in a sqlite database. Depending upon user's action I'm either adding the id if not already added or removing the id if already added. But the problem is the cursor in my method getExhibitor(int id) is always returning true. I dont understand why. Can anybody help?

public class Interests extends SQLiteOpenHelper {

    private Context context;
    private static final int DATABASE_VERSION=1;
    private static final String DATABASE_NAME="userInterests";
    private static final String TABLE_EXHIBITORS="exhibitors";
    // Column Names //
    private static final String KEY_ID="id";

    public Interests(Context context) {
        super(context,DATABASE_NAME,null,DATABASE_VERSION);
        this.context=context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
         final  String createQuery="CREATE TABLE IF NOT EXISTS "+TABLE_EXHIBITORS+"( "
                +KEY_ID+" INTEGER PRIMARY KEY)";
        db.execSQL(createQuery);

    }

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

        db.execSQL("DROP TABLE IF EXISTS"+TABLE_EXHIBITORS);
        onCreate(db);
    }

    public void addExhibitor(int id){
        SQLiteDatabase db=this.getWritableDatabase();
        ContentValues values=new ContentValues();
        values.put(KEY_ID,id);
        db.insert(TABLE_EXHIBITORS,null,values);
        db.close();
        Toast.makeText(context,"Exhibitor added",Toast.LENGTH_SHORT).show();
    }

    //This method is faulty//
    public boolean getExhibitor(int id){
        SQLiteDatabase db=this.getReadableDatabase();
        Cursor c=db.query(TABLE_EXHIBITORS,new String[]{KEY_ID},KEY_ID+" = ? ",new String[]{String.valueOf(id)},null,null,null);
        c.close();
        return (c!=null);    //Always true
    }

    public void removeExhibitor(int id){
        SQLiteDatabase db=this.getWritableDatabase();
        db.delete(TABLE_EXHIBITORS,KEY_ID+" = ?",new String[]{String.valueOf(id)});
        Toast.makeText(context,"Exhibitor removed",Toast.LENGTH_SHORT).show();
        db.close();
    }
}

Comparing words in an sqlite database to a user made string

I have an sqlite database with a variety of words and different values assigned to those words based on the type of activity the word is. Im trying to find a way to query that database for words that match the words in a user inputed string. Once a matching word is found i will then have that words values be assigned to another object i have made.

The problem i i cant figure out how to do the query. I have found plenty of awesome info on searching for a single word in a database, and doing the query by comparing each word in the database to the string one by one, but I've had no luck with any thing i have tried.

My most recent attempt was trying to split the user string into an array of substrings and compare like that but to no avail. Im also trying to keep from dumping the words into an array list as im expecting to expand the database a ton, and imagine that it will cause some memory issues.

Sorry if this turns out to be a repeat question but i am really at a loss for a solution. Thanks a ton for any help!!!

How to populate Android Spinner from SQLite Database Table

I have a SQLite database in which I have 2 Tables (there will soon be more) I am trying to populate a spinner from on 1 of those tables and cant find the resources to target a specific table.

So my current situation is I have to tables 'Menu Item' and 'Menu Category' ... I have spinner in 'Menu Item' that I would like populated with the items in 'Menu Category'.

Here is my MenuItem Activity

public class SettingsMenuItem extends AppCompatActivity {


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

    countRecords();
    readRecords();

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    Button buttonCreateLocation = (Button) findViewById(R.id.btnAdd);
    buttonCreateLocation.setOnClickListener(new OnClickListenerCreateMenuItem());
}

public void countRecords() {

    int recordCount = new TableControllerMenuItem(this).count();
    TextView textViewRecordCount = (TextView) findViewById(R.id.textViewRecordCount);
    textViewRecordCount.setText(recordCount + " records found.");

}

public void readRecords() {

    LinearLayout linearLayoutRecords = (LinearLayout) findViewById(R.id.linearLayoutRecords);
    linearLayoutRecords.removeAllViews();

    List<ObjectMenuItem> menuitem = new TableControllerMenuItem(this).read();

    if (menuitem.size() > 0) {

        for (ObjectMenuItem obj : menuitem) {

            int id = obj.id;
            String menuitemName = obj.name;
            String menuitemDescription = obj.description;
            Float menuitemPrice = obj.price;
            Float menuitemCost = obj.cost;

            String textViewContents = menuitemName;

            TextView textViewMenuItem= new TextView(this);
            textViewMenuItem.setPadding(0, 10, 0, 10);
            textViewMenuItem.setText(textViewContents);
            textViewMenuItem.setTag(Integer.toString(id));
            textViewMenuItem.setTextSize(20.0f);

            textViewMenuItem.setOnLongClickListener(new OnLongClickListenerMenuItem());


            linearLayoutRecords.addView(textViewMenuItem);
        }

    }

    else {

        TextView locationItem = new TextView(this);
        locationItem.setPadding(8, 8, 8, 8);
        locationItem.setText("No records yet.");

        linearLayoutRecords.addView(locationItem);
    }

}

And here is my MenuItem xml

<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<EditText
    android:id="@+id/editTextItemName"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:hint="Item Name"
    android:singleLine="true" >

    <requestFocus />
</EditText>

<EditText
    android:id="@+id/editTextItemDesc"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/editTextItemName"
    android:hint="Item Description"
    android:singleLine="true" />

<EditText
    android:id="@+id/editTextItemPrice"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/editTextItemDesc"
    android:hint="Item Price"
    android:singleLine="true"
    android:inputType="numberDecimal"/>

<EditText
    android:id="@+id/editTextItemCost"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/editTextItemPrice"
    android:hint="Item Cost"
    android:singleLine="true"
    android:inputType="numberDecimal"/>

<Spinner
    android:id="@+id/spinnerCategory"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/editTextItemCost"></Spinner>

How to getPosition in sqlite database knowing a column's item value (Android)

I have a static SQLite database with a table of 10 columns and 70+ rows, where the "Description" column populates a Spinner.

When the user select a description from the spinner I'd like to getPosition of it inside the database's table using cursor, in order to accordingly get other columns' values of the same row.

This is my Activity code:

public class FoodActivity extends Activity implements AppCompatCallback {

Spinner sp;
ArrayList<Map<String, String>> names = new ArrayList<Map<String, String>>();
//ArrayAdapter<String> adapter;
Toolbar toolbar;
private AppCompatDelegate delegate;
String name;
SimpleAdapter adapter;
Cursor c;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //TOOLBAR
    delegate = AppCompatDelegate.create(this, this);
    delegate.onCreate(savedInstanceState);
    delegate.setContentView(R.layout.items_activity);
    toolbar = (Toolbar) findViewById(R.id.toolbar_six);
    delegate.setSupportActionBar(toolbar);
    toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });

    sp = (Spinner) findViewById(R.id.spinnerItems);

    // database read
    DatabaseConnectorItems db = new DatabaseConnectorItems(this);
    db.open();
    c = db.getAllItems();

    while(c.moveToNext()) {
        Map<String, String> data = new HashMap<String, String>(2);
        data.put("Description", c.getString(c.getColumnIndex("Description")));
        data.put("Size", c.getString(c.getColumnIndex("Size")));
        names.add(data);
    }
    db.close();

    adapter = new SimpleAdapter(this, names, R.layout.items_list,
            new String[] {"Description", "Size"},
            new int[] {R.id.itemTextOne, R.id.itemTextTwo});

    // set to spinner
    sp.setAdapter(adapter);
    sp.setBackgroundColor(getResources().getColor(R.color.TextColor_White));
    sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
            name = sp.getSelectedItem().toString();

            //c.getPosition();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parentView) {
            // nothing
        }

    });

}

@Override
public void onSupportActionModeStarted(ActionMode mode) {

}

@Override
public void onSupportActionModeFinished(ActionMode mode) {

}

}

I'm trying with c.getPosition( different methods here ) but with no results

Writing my first app for Andriod and I have a few questions

Thanks in advance for taking the time to read this.

I am a developer with 17 years of code experience. I have some code that I've written over the past few years in my spare time and it's heavily dependent on a postgres database. I want to port this program into a smart phone app and have a ton of questions but the most glaring questions are:

  1. I can organize the app to use a local database on the smart phone but I am wondering if it would be better to keep the large database data on a server with only the users access credentials stored in the phone app.
  2. I am just an independent developer, Is it possible to set up a server to host this database at my house serve up it's contents in response to requests from the apps on phones? Are there any web hosting solutions that are affordable that also allow a developer to customize the database easily?
  3. Is the sqlite database that comes with an Android robust enough to handle multiple tables some of which holding thousands of rows of data?

I could invest in a small server and set the database up on it.. and even configure it to use my existing network connections but I am not sure this is the best approach.

ANY suggestions or advice you can offer on this topic will be appreciated a great deal. I really want to do this right from the start.

How to open Windows Phone sqlite files?

I've copied an sqlite file from a folder of a windows phone application (WP 8.1). I've tried to open with sqlite browser, but it said the file format was invalid. How can I open these sqlite files?

SQLite insert turns inserted values into 1, 2, 3 when they should be String like qpzMH7

I use the following code to insert data into a table

    SQLiteDatabase db = this.getWritableDatabase();
    String CREATE_FOLLOWING_TABLE = "CREATE TABLE IF NOT EXISTS " + FOLLOWING_TABLE_NAME + "("
        + KEY_ID + " INTEGER PRIMARY KEY,"
        + KEY_USER_ID + " TEXT)";
    db.execSQL("DROP TABLE IF EXISTS " + FOLLOWING_TABLE_NAME);
    db.execSQL(CREATE_FOLLOWING_TABLE);


    String sql = "INSERT INTO " + FOLLOWING_TABLE_NAME + " (" + KEY_USER_ID + ") VALUES(?)";
    db.beginTransaction();
    SQLiteStatement stmt = db.compileStatement(sql);
    for(String id : userIds) { // userIds is ArrayList<String>
        stmt.bindString(1, id);
        stmt.execute();
        stmt.clearBindings();
    }
    db.setTransactionSuccessful();
    db.endTransaction();
    db.close();

I confirmed that the userIds ArrayList contains String values which are like qWz17mh. However, after running the above code, I get the following in the table

_id    userid
  1    1
  2    2
  3    3
  4    4
  5    5
  6    6

I don't know why this is happening. My suspicion lies in the insert syntax. What do you think is wrong? Thanks in advance!

How to create an unkown number of SQLite tables in Android based on user input

I am trying to create tables based on new categories that are created in my Android app. I have a Table that keeps track of the category that the user entered and the perspective table name for that category, but I cannot figure out how to actually create new tables based on the perspective table names. I am new to SQLite and I am wondering if this is even possible

How to send data to the cloud database using SQLite and android studios

I have a local SQLite database for my app in android studios. I would like the user to have an option to save to a cloud database. But i have no idea how to send data to a cloud or how to create a cloud database that i can interact with in my app. I have an Azure account but that is it. Any help would be great. Even to point me in the right direction. A simple step by step either Thanks in advance.

javaFX - tableview getting selected items

How can I get a selected item in a row from tableview in javaFX with Sqlite Database.

I am now using this to get the Index of the row:

(...)

@FXML
    private ObservableList<UserData> data;

@FXML
    private TableView table;

@FXML
    private void pressTableAction() {
        System.out.println("Selected index: " +table.getSelectionModel().getSelectedIndex());
    }

(...)

 public void initialize (URL url, ResourceBundle rb) {
        try {
            con = DataBaseConnection.getConnected();
            stat = con.createStatement();
            data = FXCollections.observableArrayList();
            ResultSet rs = con.createStatement().executeQuery("SELECT * FROM person");
            while (rs.next()) {
                data.add(new UserData(rs.getInt("p_id"), rs.getString("Name")));
            }
            column1.setCellValueFactory(new PropertyValueFactory("p_id"));
            column2.setCellValueFactory(new PropertyValueFactory("Name"));
            table.setItems(null);
            table.setItems(data);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Error on Building Data");
        }






Public static class UserData {

        private IntegerProperty p_id;
        private StringProperty Name;


        private UserData(Integer p_id, String Name) {
            this.p_id = new SimpleIntegerProperty (p_id);
            this.Name = new SimpleStringProperty(Name);

        }

        public IntegerProperty p_idProperty() {
            return p_id;
        }

        public StringProperty NameProperty() {
            return Name;
        }
}

My db looks like this:

CREATE TABLE person (p_id INTEGER PRIMARY KEY AUTOINCREMENT, Name VARCHAR(30) NOT NULL);

How can I get the p_id or the Name of the row I clicked?

@FXML
    private void pressTableAction() {
    System.out.println("Selected index: " + table.getSelectionModel().getSelectedIndex());
    System.out.println("Selected p_id: " + ????)
    }

Android Searching Database with Empty Where Clause

I am trying to do a search function in android that will allow the user search with different filters. I am able to create a simple select statement with multiple where clauses. My issue arises when the user doesnt use the filter options, is there a way to continue the select statement but use blank values in the where clause?

For example, the user will want to search for all the cars and add a filter looking for specific green cars made in the year 2011.

"Select * from cars where colour = 'green' AND year = 2011"

Example where the user searches without filters for all cars

"Select * from cars where colour = '' AND year = "

I dont want to have to use two statements I would just like to use the one and have blanks in the where clause is nothing is selected in the filter, is this possible?

how to delete not a specific row but a specific field in a row SQLITE

like if table has three columns

  1. columnA
  2. columnB
  3. columnC

just to delete the data of columnA and columnB but not the columnC

since where clause only allows to select a specific row not data in various columns of that row

Spinner Value not working

I am running into some trouble with my spinners. When every I select a value from them the spinner only takes the first value in the list.

For example I have a spinner with vales 1,2,3,4,5. When I select 4 the value taken from the spinner 1, this is the same if I select any of the other values.

Am I implementing the Spinner wrong? Or taking the values from the spinner wrong?

Spinner

<Spinner
    android:id="@+id/heatSpinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/heat_title"
    android:entries="@array/heat"/>

Array/Heat

    <string-array name="heat">
    <item>1</item>
    <item>2</item>
    <item>3</item>
    <item>4</item>
    <item>5</item>
</string-array>

Taking Values from Spinner

                Spinner heat = (Spinner) dialog.findViewById(R.id.heatSpinner);
            final String heatValue = heat.getSelectedItem().toString();
            final int finalHeat = Integer.parseInt(heatValue);

Accessing historical app usage database in Android

What is the best way to access the app usage database on Android, without using the API?

In particular, I would like to make a local copy of the database behind this API:

http://ift.tt/1KiXTBE

Delete database entries swift SQLite

Is anyone able to show me how i can automatically delete all database entries after closing the simulation in Xcode Swift? The database i am using is SQLite.

My code is as follows;

import Foundation import SQLite

class DBHQ {

func StartDB(InputFirstName: String, InputLastName: String, InputEmail: String){
    let path = NSSearchPathForDirectoriesInDomains(
        .DocumentDirectory, .UserDomainMask, true
        ).first!

    let id = Expression<Int64>("id")
    let FirstName = Expression<String>("FirstName")
    let LastName = Expression<String?>("LastName")
    let Email = Expression<String?>("Email")
    let User = Table("User")

    //CREATING DATABASE
    do {
        let db = try Connection("\(path)/db.sqlite3")
        try db.run(User.create { t in
            t.column(id, primaryKey: true)
            t.column(FirstName, unique: true)
            t.column(LastName, unique: true)
            t.column(Email, unique: true)
            })

    } catch {

        do {
            let db = try Connection("\(path)/db.sqlite3")
                //INPUT DATA
                try db.run(User.insert(FirstName <- InputFirstName, LastName <- InputLastName, Email <- InputEmail))
            for user in try db.prepare(User) {
                print("id:\(user[id]), FirstName: \(user[FirstName]), LastName: \(user[LastName]), Email: \(user[Email])")
            }
        } catch {
            print("Failiure")

    }
}

} }

Cheers

How to keep changes made on sqlite database

I have a Django app with a SQLite database. This app is deployed on Heroku.

When someone uses the app and add data into the database, the sqlite database is modified. But when I make a code change on Github and then deploy this new version of my app, I also deploy the sqlite database (which doesn't have the new changes made by the users) and so I remove the changes.

What is the best process to prevent this ?

Android Studio get data from sqlite

I had some problem about get data from sqlite different database.One database that save user's name and phone and they can update as they like. While another is house information but also contain user's name and phone. My problem is i just realize that the phone that had been update in user database is not same with phone that previous store in house database. So i wanna call the user's phone from user database and use for phone call function and message function. But it does not work.And i trying to match the fullname that in user database with house database to call the phone data but still cant.

here is my call and message function

public class HouseDetail extends AppCompatActivity {
EditText etAddress,etDetail,etPhone;
TextView txType,txProperty,txPrice,txState,txTitle,txOther,txSize,txFullname;
ImageButton bPhone,bMessage;
String type,property,price,state,address,title,other,size,detail,fullnames,fullname,phone;
HousesDB db = new HousesDB(this);
Houses houses;
DatabaseOperations Udb = new DatabaseOperations(this);
PersonalData profileInfo;

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

    txType = (TextView) findViewById(R.id.txTypes);
    txProperty = (TextView) findViewById(R.id.txProperty);
    txPrice = (TextView) findViewById(R.id.txPrice);
    txState = (TextView) findViewById(R.id.txState);
    etAddress = (EditText) findViewById(R.id.etAddress);
    txTitle = (TextView) findViewById(R.id.txTitle);
    txOther = (TextView) findViewById(R.id.txOther);
    txSize = (TextView) findViewById(R.id.txSize);
    txFullname = (TextView) findViewById(R.id.txFullname);
    etPhone = (EditText) findViewById(R.id.etPhone);
    etDetail = (EditText) findViewById(R.id.etDetail);
    bPhone = (ImageButton) findViewById(R.id.bPhone);
    bMessage = (ImageButton) findViewById(R.id.bMessage);

    fullnames = txFullname.getText().toString();
    type = txType.getText().toString();
    property = txProperty.getText().toString();
    price = txPrice.getText().toString();
    state = txState.getText().toString();
    address = etAddress.getText().toString();
    title = txTitle.getText().toString();
    other = txOther.getText().toString();
    size = txSize.getText().toString();
    detail = etDetail.getText().toString();
    phone = etPhone.getText().toString();


    Intent i = getIntent();
    property = i.getStringExtra("house_property");
    txProperty.setText(property);

    houses = db.getInfo(property);

    txType.setText(houses.getTypes());
    txFullname.setText(houses.getFullname());
    txPrice.setText(houses.getPrice());
    txState.setText(houses.getState());
    etAddress.setText(houses.getAddress());
    txTitle.setText(houses.getTitle());
    txOther.setText(houses.getOther());
    txSize.setText(houses.getSize());
    etDetail.setText(houses.getDetail());


    this.fullnames = fullname;
    profileInfo = Udb.getNumber(fullname);
    etPhone.setText(profileInfo.get_phone());


    bPhone.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent callIntent =new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse("tel:" + etPhone));
            startActivity(callIntent);

        }
    });

    bMessage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("sms:" + etPhone)));
        }
    });
}

Here is my user database that get the phone number

  public PersonalData getNumber(String fullname)
{
    SQLiteDatabase SQ = this.getWritableDatabase();
    String query = "select FullName,Phone from "+ Table_NAME;
    Cursor CR = SQ.rawQuery(query,null);
    String a;
    PersonalData info = new PersonalData();

    if (CR.moveToFirst())
    {
        do {
            a = CR.getString(0);
            if (a.equals(fullname)) {
                info._phone = CR.getString(1);
                break;
            }
        }while (CR.moveToNext());
    }
    return info;
}

Mount an archive and write to (and read from) it on-the-fly on Linux

Is there a tool available that supports mounting of an archive into a folder and on-the-fly writing to it?

I've tried avfs (which seems to support read-only) and mountarchive (which seems to support writing, but it only seems to put the written data into the archive when I sudo umount.

My main use-case right now is that I have an SQLite database that has highly redundant and also somewhat irregular data. I don't wish to change the schema and de-normalize it by hand, and so I am looking into automatic solutions. E.g. deflating it by putting it into an archive and reading and writing to it on the fly.

That said, I'm not yet sure this is a good way to achieve SQLite compression; there might be others that I don't know about -- I haven't used SQLite much yet. But even if it isn't the best way, I'd still be curious to know of a good read+write archive mounting solution that I might use in a different situation.

Edit: Since someone is voting to close this question on these grounds:

Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.

I can phrase it like this: I have an SQLite database (accessed programmatically) with highly redundant data. De-normalization by hand might be time consuming, because much of the data is varchar where some parts of the strings overlap with other rows' contents, others don't. How can I reduce the size of this database? Putting it into a mounted archive is one thing I can think of, and I've tried to do that with avfs and mountarchive so far without success.

Alarm message for every action from sqlite

In my project i will save 100+ students details in sqlite. Each student can give action spinner (task and homework). i want display alarm before 30mins to student from sqlite local database for each student.

Android studio delete function but no update

I got problem in delete function there.When I click on delete, it works and delete the record in sqlite. But the problem is after it delete, it jump back to previous activity that using listview. But the deleted records still appear at there. I need to go out from the listview activity and go back again it just disappear. How should I do?

Here my delete function in database

public Integer deleteData (String property)
{
    SQLiteDatabase db = this.getReadableDatabase();
    return db.delete(houseContract.houseEntry.table2_name,"Property = ?",new String[] {property});
}

Here is my delete button works at the activity

public class SellerHouseDetail extends AppCompatActivity {
EditText etAddress,etDetail,etShowID;
TextView txType,txProperty,txPrice,txState,txTitle,txOther,txSize,txFullname;
Button bDelete;
String type,property,price,state,address,title,other,size,detail,fullname;
HousesDB db = new HousesDB(this);
Houses houses;

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

    txType = (TextView) findViewById(R.id.txTypes);
    txProperty = (TextView) findViewById(R.id.txProperty);
    txPrice = (TextView) findViewById(R.id.txPrice);
    txState = (TextView) findViewById(R.id.txState);
    etAddress = (EditText) findViewById(R.id.etAddress);
    txTitle = (TextView) findViewById(R.id.txTitle);
    txOther = (TextView) findViewById(R.id.txOther);
    txSize = (TextView) findViewById(R.id.txSize);
    txFullname = (TextView) findViewById(R.id.txFullname);
    etDetail = (EditText) findViewById(R.id.etDetail);
    etShowID = (EditText) findViewById(R.id.etShowID);
    bDelete = (Button) findViewById(R.id.bDelete);

    fullname = txFullname.getText().toString();
    type = txType.getText().toString();
    property = txProperty.getText().toString();
    price = txPrice.getText().toString();
    state = txState.getText().toString();
    address = etAddress.getText().toString();
    title = txTitle.getText().toString();
    other = txOther.getText().toString();
    size = txSize.getText().toString();
    detail = etDetail.getText().toString();

    Intent i = getIntent();
    property = i.getStringExtra("house_property");
}

public void onResume()
{
    super.onResume();
    txProperty.setText(property);

    houses = db.getInfo(property);

    txType.setText(houses.getTypes());
    txFullname.setText(houses.getFullname());
    txPrice.setText(houses.getPrice());
    txState.setText(houses.getState());
    etAddress.setText(houses.getAddress());
    txTitle.setText(houses.getTitle());
    txOther.setText(houses.getOther());
    txSize.setText(houses.getSize());
    etDetail.setText(houses.getDetail());

    DeleteData();
}
public void DeleteData() {
    bDelete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Dialog dialog = new Dialog(SellerHouseDetail.this);
            dialog.setTitle("Delete Record");
            dialog.setContentView(R.layout.activity_delete_layout);
            dialog.show();

            Button bYes = (Button) dialog.findViewById(R.id.bYes);
            Button bNo = (Button) dialog.findViewById(R.id.bNo);

            bYes.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Integer deletedRows = db.deleteData(txProperty.getText().toString());
                    if(deletedRows > 0)
                    {
                        Toast.makeText(SellerHouseDetail.this,"House Deleted",Toast.LENGTH_LONG).show();
                        finish();
                    }
                    else
                    {
                        Toast.makeText(SellerHouseDetail.this,"House not Deleted",Toast.LENGTH_LONG).show();
                    }
                }
            });

            bNo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.cancel();
                }
            });
        }
    });
    }
}

here is my listview activity that had problem

public class SellerHouses extends ListActivity {
TextView house_property;
String fullname;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_seller_houses);
    Intent i = getIntent();
    fullname = i.getStringExtra("fullname");
}
public void onResume()
{
    super.onResume();
    HousesDB list = new HousesDB(this);
    // list.insertProduct();
    ArrayList<HashMap<String, String>> houseList =  list.getSellerHouseList(fullname);
    if(houseList.size()!=0) {
        ListView lv = getListView();
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,int position, long id) {

                house_property = (TextView) view.findViewById(R.id.shouse_property);
                String houseproperty = house_property.getText().toString();

                //Go to House Detail

                Intent objIndent = new Intent(getApplicationContext(),SellerHouseDetail.class);
                objIndent.putExtra("house_property",houseproperty);
                startActivity(objIndent);
            }
        });
        ListAdapter adapter = new SimpleAdapter( SellerHouses.this,houseList, R.layout.activity_seller_house_info, new String[] { "id","property","type","state"}, new int[] {R.id.shouse_Id, R.id.shouse_property, R.id.shouse_type, R.id.shouse_state});
        setListAdapter(adapter);
    }else{
        Toast.makeText(this, "No Houses is found!", Toast.LENGTH_SHORT).show();
    }

    }
}

Visual Studio Dataset Save unexpected fail

When a Dataset on a sqlite database is configured with wizard, some times show weird behavior. Any edit to dataset designer may result to dataset fail (automatically being removed from datasources pane) when try to save.

Android Text displayed on TextView is not coming properly from SQLite

Using this Java class to print data retrieved from SQLite db.
We just need to enter data in an Edittext and then print it back to a TextView.
However the display is not corect , please refer attached code.

package maptest.com.mapstest;

import android.app.Activity;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.view.MenuItem;

public class userdetails extends Activity implements View.OnClickListener {

EditText username;
TextView username1;
    TextView try2;

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

        username = (EditText) findViewById(R.id.username);
        username1 = (TextView) findViewById(R.id.username1);
        username.getText().clear();
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        username.setText("");
    }

    public void adddetails(View view){
        db1 = new dbdetails(this);
        user user = new user(username.getText().toString());
        db1.userdetails1(user);
        printdb();
                }
    public void printdb(){
        String dbst = db1.dbtostring();
        username1.setText(dbst);
username.getText().clear();
    }

    @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_userdetails, menu);
        return true;
    }

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

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

        return super.onOptionsItemSelected(item);
    }
}

enter image description here

conflict that may occur when adding column to a table

Currently i have a database in android sqllite with many tables of the following column, column A and column B.

Now i am required to have table of column A , column B and column C for subsequent future table created in database. It is alright for me to keep old table of column A and B without changing anything.

so i have the following concern.

1 Let say i have the following code

rssiDB.execSQL("CREATE TABLE IF NOT EXISTS "  + rssiTableName + " (ssid VARCHAR, bssid VARCHAR , rssi INTEGER )" );

What is the meaning of if not exists. If i am trying to create a table with a table name that already exists but different number of column, will the creation of table be successful? What will happen actually.

for example i have this table of the table name testing20 with column value of a743954759 , -40

and now i want to create a table of the table name testing20 with column value of peterwifi,a7954759 , -60

will the above code create a table with the same name but different number of column.

2 In a database, is it allowed for database to have many table of different column or is it compulsory for database to have every table to have the exact number of column or column name.

Let say i have a database with one table of table name testing1 with column A and column B. can i now add a table with table name testing2 with column A, column B and column C to the database.

I know i can try this out to find out myself. However i am afraid that it will affect my existing table if i try it out. Hope someone can answer my question. Thank you

samedi 30 janvier 2016

How to get first and last record of every month in Sqlite

in my java application I have stored candlestick data in a sqlite database (I'm new in sqlite language). The database contains one table for each stock with columns: date,open,high,low,close. In order to display monthly candles I need a ResultSet storing first and last value for every month, max value of high and min value of low. I was able to retrieve last two data by:

SELECT STRFTIME("%Y-%m", date/1000,'unixepoch', 'localtime') AS Date, max(high) AS High, min(low) AS Low

For the first needed data I tried to reach records :

where strftime('%m', date/1000, 'unixepoch', 'localtime')<>strftime('%m', date/1000, 'unixepoch', 'localtime','+1 day')

but if the last record in month stops for example in 2015-10-29 the query skips obviously this month because +1 day is 2015-10-30

How can I make it correctly? Thanks to all

whoosh search after database migration

I migrated my database from sqlite3 to postgresql with the following three steps

  1. I create a sqlite dump file with

    sqlite3 app.db .dump > app_dump.sql

  2. I create a postgresql database and initialized it with my models.py file as

    python manage.py db init

where manage.py is

SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://appuser:777@localhost/app_db' 
migrate = Migrate(app, db)

manager = Manager(app)
manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
    manager.run()

  1. I used only the insert lines in the dump file to populate the new database.

This worked well, however I do want to have a whoosh search in my User table.

My models.py looks like this

if sys.version_info >= (3, 0):
    enable_search = False
else:
    enable_search = True
    import flask.ext.whooshalchemy as whooshalchemy

class User(db.Model):
    __searchable__ = ['username','id'] 

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(100), index=True)

if enable_search:
    whooshalchemy.whoosh_index(app, User)

However, the search does not seem to work at all. I fear that the table has not been properly indexed? Anybody know how I can fix this? thanks carl

Does sqlite bind by reference or by value?

When I bind in sqlite, what actually happens, or essentially am I passing by reference or by value? If I bind a variable, does sqlite see changes in the value of the variable or is it a one-shot deal? Binding within the loop tells me I'm misusing the library, even if I clear the bindings at the end of the loop contents with sqlite3_clear_bindings. Binding first gets me no rows at all, even though the bind returns SQLITE_OK. (Is it binding a 0?)

    int cat;
    sql = "select x,y,z from table where q = ?"
    bind cat (to ?) here
    for (cat=0; cat<topcat; cat++) {
      //  I want (multiple) results for each cat value here
      rslt = 0;
      while ((rslt != SQLITE_DONE) && (rslt != SQLITE_ERROR)) {
        rslt = sqlite3_step(stmt2);
        // do column stuff here to fetch values
      }
    }

Another part of the program fetches all the rows from another table OK with no where clause in the SQL. If I take the where and bind out of this I can get all the rows. If I bind to a constant value like 3 instead of cat, that works.

How to query with `sqlite-simple` without having to specify a concrete return type?

Anyone knows if http://ift.tt/1nvgZdm can run a query or query_ where the rows can be printed without explicitly specifying a return type tuple, for debugging purposes?

Or if not with this package, maybe with another?

Insert default value for single field with SQLite

Given the following table in SQLite:

CREATE TABLE users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name VARCHAR NOT NULL,
    hair_color VARCHAR NOT NULL DEFAULT 'Green'
)

I'm attempting to perform a batch insert, using the default value for hair_color for only some of the rows. For example, in PostgreSQL or MySQL, it might look like:

INSERT INTO users (name, hair_color) VALUES
    ('Sean', 'Black'),
    ('Tess', DEFAULT)

However, SQLite does not provide a DEFAULT keyword in any other context beyond DEFAULT VALUES. I know that I can do this in two queries as

INSERT INTO users (name, hair_color) VALUES ('Sean', 'Black');
INSERT INTO users (name) VALUES ('Tess');

However, I can't imagine that SQLite doesn't provide some mechanism to execute this in a single query. Is there any equivalent to the DEFAULT keyword from other backends for SQLite?

Rails - pull attribute value from table using two conditions

I have two tables in my rails application: a user table and an activity table. The user has many activities. Right now, I am trying to find out how to print out the activity_name where the activity_type = :personal AND where user_id = current_user.id.

In my activities index file i have the following:

<% @activities.where(:user_id => current_user.id).where(:activity_type => :personal).each do |activity| %>
<%= activity.activity_name %>
<% end %>

Nothing prints out on the page - I definitely have added users and activities to the database, as I have checked the rails consoler. Have I set up the each do loop incorrectly? Is there a different way to query this data?

sqlite studio user defined function

sqlite studio does not support square root function, so i have defined it in function editor as

    proc SqrtA {num} {  set ans [expr {sqrt($num)}] return $ans }

with function name SqrtA and one input argument, lang. tcl but when i am using it in query editor, i am not getting the square root.

for example i had tried for -

    select SqrtA(9);

can anyone please help me, in how to include square root function in sqlite studio?

No such table SQLiteException [duplicate]

This question already has an answer here:

I have a pre-populated database containing one table that is located in my assets folder which I'm having trouble reading. All I want to do is a couple of SELECT queries on the database.

It was all previously working fine then I decided to add some more data to the .db file (I just used DB browser for SQLite to achieve this) ever since I added more data I get the error android.database.sqlite.SQLiteException: no such table: SOULS (code 1) even though the table SOULS exists and had previously worked fine. I see this error is fairly common but nothing I have looked up seems to help me.

Database:

enter image description here

Code:

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

public class DBHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "BB2Database.db";
    private static final int DATABASE_VERSION = 2;
    public static final String TABLE_NAME = "SOULS";
    public static final String SOUL_COLUMN_THUMBNAIL = "thumbnail";
    public static final String SOUL_COLUMN_NAME = "name";
    public static final String SOUL_COLUMN_TYPE = "type";


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


    @Override
    public void onCreate(SQLiteDatabase db) {
    }

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

    public Cursor getItem(String id) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res =  db.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " +
                SOUL_COLUMN_NAME + "=?", new String[]{id});
        return res;
    }

    public Cursor getAllItems() {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res =  db.rawQuery( "SELECT * FROM " + TABLE_NAME, null );
        return res;
    }
}

Logcat:

> 01-31 10:16:32.209  12321-12321/com.delm959.daniel.bb2sng W/dalvikvm﹕ VFY: unable to resolve virtual method 395: Landroid/content/res/Resources;.getDrawable (ILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
01-31 10:16:32.209  12321-12321/com.delm959.daniel.bb2sng D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
01-31 10:16:32.209  12321-12321/com.delm959.daniel.bb2sng I/dalvikvm﹕ Could not find method android.content.res.Resources.getDrawableForDensity, referenced from method android.support.v7.internal.widget.ResourcesWrapper.getDrawableForDensity
01-31 10:16:32.209  12321-12321/com.delm959.daniel.bb2sng W/dalvikvm﹕ VFY: unable to resolve virtual method 397: Landroid/content/res/Resources;.getDrawableForDensity (IILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
01-31 10:16:32.209  12321-12321/com.delm959.daniel.bb2sng D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
01-31 10:16:32.339  12321-12321/com.delm959.daniel.bb2sng E/SQLiteLog﹕ (1) no such table: SOULS
01-31 10:16:32.339  12321-12321/com.delm959.daniel.bb2sng D/AndroidRuntime﹕ Shutting down VM
01-31 10:16:32.339  12321-12321/com.delm959.daniel.bb2sng W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x418eeda0)
01-31 10:16:32.349  12321-12321/com.delm959.daniel.bb2sng E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.delm959.daniel.bb2sng, PID: 12321
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.delm959.daniel.bb2sng/com.delm959.daniel.bb2sng.MainActivity}: android.database.sqlite.SQLiteException: no such table: SOULS (code 1): , while compiling: SELECT * FROM SOULS
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
            at android.app.ActivityThread.access$900(ActivityThread.java:161)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5356)
            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:1265)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: android.database.sqlite.SQLiteException: no such table: SOULS (code 1): , while compiling: SELECT * FROM SOULS
            at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
            at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1121)
            at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:694)
            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:1436)
            at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1375)
            at com.delm959.daniel.bb2sng.DBHelper.getAllItems(DBHelper.java:39)
            at com.delm959.daniel.bb2sng.MainActivity.updateList(MainActivity.java:79)
            at com.delm959.daniel.bb2sng.MainActivity.onCreate(MainActivity.java:53)
            at android.app.Activity.performCreate(Activity.java:5426)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
            at android.app.ActivityThread.access$900(ActivityThread.java:161)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5356)
            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:1265)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
            at dalvik.system.NativeStart.main(Native Method)
01-31 10:16:35.252  12321-12321/? I/Process﹕ Sending 

signal. PID: 12321 SIG: 9

sqlite configuring with django

I have been assigned the task of setting up an online database with sqlite via django- where it will contain columns of information. My problem is that I can't figure out which is establishing table where the information will go- my models.py script or should I do it with a "CREATE TABLE" command? An example of the code in my models.py script is below:

    class Person(models.Model):
       firstname=models.CharField(max_length=100)
       lastname=models.CharField(max_length=100)

The tutorial that I was given recommended this command:

    insert into freezer_person (firstname,lastname)

However upon executing this command I naturally got an error saying "table does not exist" i.e. I have to use the "CREATE TABLE" command. so when I tried:

           "CREATE TABLE in freezer_person(...)" 

It returned that "in" was syntactically incorrect. So my question is how do I go about creating a table that will intake info from models.py?- I can't seem to find any info on this...

Sqlite database doesn't work on Unity games build to Android Devices

I'm using the Sqlite as Unity Game database and works on Unity Editor, but when I build to Android Devices the Game can't access the database, what can I do to make the script works also on Android Devices ?

Programs/Versions used:
- Unity 5.3.1f1
-Sqlite Precompiled Binaries for Windows 64 (sqlite-dll-win64-x64-3100200.zip (688.01 KiB))

Folder Structure:

-- Assets/Database/MyDataBase.db
-- Assets/Scripts/PerguntaScript.cs
-- Assets/Plugins/Mono.Data.Sqlite.dll
-- Assets/Plugins/sqlite3.def
-- Assets/Plugins/sqlite3.dll
-- Assets/Plugins/System.Data.dll

PerguntaScript.cs (Script that access the Sqlite database)

using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System;
using System.Data;
using Mono.Data.Sqlite;

public class PerguntaScript : MonoBehaviour {

    private string connectionString;

    void Start () {
        connectionString = "URI=file:" + Application.dataPath + "/Database/DoencasDB.db";
    }

    private void GetPergunta(){
        using(IDbConnection dbConnection = new SqliteConnection(connectionString)){
            dbConnection.Open();

            using(IDbCommand dbCommand = dbConnection.CreateCommand()){
                string sqlQuery = "SELECT * FROM " + sqliteTabelasPerguntas[sqliteIndexTabelaPergunta] + " WHERE doenca_id=@id LIMIT 1";
                dbCommand.Parameters.Add(new SqliteParameter("@id", doencaId));
                dbCommand.CommandText = sqlQuery;

                using(IDataReader reader = dbCommand.ExecuteReader()){
                    while(reader.Read()){
                        pergunta = reader.GetString(1);
                        alternativasId[0] = reader.GetInt32(3);
                        alternativasId[1] = reader.GetInt32(4);
                        alternativasId[2] = reader.GetInt32(5);
                        alternativasId[3] = reader.GetInt32(6);
                        alternativaCorretaId = reader.GetInt32(7);
                    }
                    dbConnection.Close();
                    reader.Close();
                }
            }
        }
    }

IS there a way TO transform the following SQLite query USING ActiveAndroid query?

This is my code:

SELECT USER.userName, COUNT(reservation.userID), SUM(price) PricePerUser FROM USER 
      JOIN reservation ON reservation.userID = USER.userID 
      JOIN venue ON venue.venueID = reservation.venueID 
      JOIN TIME ON reservation.timeID = TIME.timeID GROUP BY USER.[userName]

Java org.sqlite.jdbc not found exception

I have a problem with executing my maven-java program outside of NetBeans. The program uses a SQLite database, so I added the maven-dependency for it

    <dependency>
        <groupId>org.xerial</groupId>
        <artifactId>sqlite-jdbc</artifactId>
        <version>3.8.11.2</version>
    </dependency>

Now, if I execute the program inside of NetBeans, everything works fine. But as soon as I export the jar-file and execute it, I get this error:

C:\Users\benes\Desktop>java -jar DataConverter-1.0.jar
JΣn 30, 2016 7:23:02 PM repository.DbController initDBConnection
SEVERE: null
java.lang.ClassNotFoundException: org.sqlite.JDBC
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at repository.DbController.initDBConnection(DbController.java:50)
    at repository.DbController.<init>(DbController.java:36)
    at repository.DbController.getInstance(DbController.java:44)
    at repository.Repository.initialize(Repository.java:55)
    at repository.Repository.<init>(Repository.java:45)
    at repository.Repository.getInstance(Repository.java:50)
    at rs232emulator.RS232Emulator.main(RS232Emulator.java:19)



Exception in thread "main"java.lang.RuntimeException:
java.sql.SQLException:The url cannot be null
    at repository.DbController.initDBConnection(DbController.java:63)
    at repository.DbController.<init>(DbController.java:36)
    at repository.DbController.getInstance(DbController.java:44)
    at repository.Repository.initialize(Repository.java:55)
    at repository.Repository.<init>(Repository.java:45)
    at repository.Repository.getInstance(Repository.java:50)
    at rs232emulator.RS232Emulator.main(RS232Emulator.java:19)
Caused by: java.sql.SQLException: The url cannot be null
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at repository.DbController.initDBConnection(DbController.java:58)
    ... 6 more

Thanks in advance, Benedikt

mvvmcross sqlite-PCL iOS security

Hi I have been using the MVVMCross-SQLite plugin link. Using this I could use the SQLiteOpenFlags to enable the database to use the iOS platform security option of ProtectionComplete.

This plugin has been deprecated, so I want to upgrade to the SQLite-PCL plugin. However I cannot see a way to set an iOS security option with this plugin. Does anyone know if this is possible?

Thanks in advance

I created signup-login app. Sign up is working fine but as I click on login button, my app is getting terminated

I am using searchPass() method which is defined in my code below, to check username and password and I think that error is in this searchPass() method only. When I ran my project in debug mode, I found that error is in line "Cursor cursor = db.rawQuery(query, null);". Please help me to debug this code.

This is my DatabaseHelper class:

package com.example.admin.loginregistraionusingsqlite;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "contacts.db";
    private static final String TABLE_NAME = "contacts";
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_NAME = "name";
    private static final String COLUMN_EMAIL = "email";
    private static final String COLUMN_UNAME = "uname";
    private static final String COLUMN_PASSWORD = "password";

    SQLiteDatabase db;

    private static final String TABLE_CREATE = "create table contacts(id integer primary key,name text,email text,uname text,password text)";


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

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

    public void insertContact(Contact c)
    {
        db = this.getWritableDatabase();
        ContentValues values = new ContentValues();

        String query = "select * from contacts";
        Cursor cursor = db.rawQuery(query, null);
        int count = cursor.getCount();

        values.put(COLUMN_ID, count);
        values.put(COLUMN_NAME, c.getName());
        values.put(COLUMN_EMAIL, c.getEmail());
        values.put(COLUMN_UNAME, c.getUname());
        values.put(COLUMN_PASSWORD, c.getPassword());

        db.insert(TABLE_NAME, null, values);
        //cursor.close();
        db.close();
    }

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

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

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

comparing values of textfields with values rendered by a function (not working)

I have a function that renders 2 columns: date and time for upcoming appointments. When the user enter date and time in the textfields, I want to avoid conflict time, so I want to compare those values with values of dates and times rendered by the function. If he entered date and time similar to a record from the rendered function, I want to show a toast message to tell him to change the date and time since this appointment is booked.

Here is my code that I inserted in the OnCreateView of the class that extends fragment :

Cursor res = myDB.getUpcomAp();

StringBuffer buffer = new StringBuffer();
while (res.moveToNext()){

if( (res.getString(0)).equals(chosdate.getText().toString())&&(res.getString(1)).equals(chostime.getText().toString()))

Toast.makeText(getActivity(), "This appointment is booked, please choose another one", Toast.LENGTH_LONG).show();


};

But nothing is rendered when the user choose the same date and time of a booked appointment. Please help

Populating SQLite table with Tcl script in SQLiteStudio

I'm trying to populate two INTEGER fields of a table in SQLite Studio with Tcl script feature of SQLiteStudio. The table itself is a representation of a m✕n rectangular matrix, where those two fields represent elements' indices.

I've tried to recreate a surrogate for loop with the following script for the first field:

set i 0
set i [expr {$i==100?1:$i+1}]

and this script for the second one:

set j 0
set j [expr {$i==100?$j+1:$j}]

While the first script populates field i normally, the second one displays Error while executing populating code: can't read "i": no such variable error message, and the j field is populated with null values.

Is there any way to use SQLiteStudio's population mechanism this way (i.e. accessing field's new value from scope of another field's population Tcl script)?

Getting the nth record with where condition in Sqlite - Android [duplicate]

This question already has an answer here:

I have database that looks like this:

_id | isHistory | text  |
1   |   0       |   any |
2   |   0       |   txt |
3   |   1       |   he  |
4   |   1       |   re  |
5   |   0       |   sa  |
6   |   1       |   sa  |
7   |   0       |   rn  |

I am trying to get the 3rd record where the isHistory is 1:

_id | isHistory | text  |
3   |   1       |       |
4   |   1       |       |
6   |   1       |       | <- I want this

so it is the nth record where isHistory is 1

and the Nth record will be chosen by user, so it may be not existed in the table.

How can this be done with sqlite on Android ?

and How can I check if the Nth record is exists in the table with Where condition?

Max value with ALL operator in sqlite

There are two tables:

Movie(mID int, title text, year int, director text);
Rating(rID int, mID int, stars int, ratingDate date);

I want to make a query with ALL operator where I get the title of the movie and max stars that this movie received.

I have tried the following:

SELECT Title, Stars
FROM Movie m, Rating rt
WHERE m.mID=rt.mID AND stars>=all(SELECT stars FROM rating rt, movie m WHERE m.mid=rt.mid);

I get the error:

Error: near "all": syntax error

I can't understand what I am doing wrong here.

Database Helper error upon using custom function on a cursor

This is my main application. I am trying to get the userID so that I can save it in my application so that when I save User's data, in another table, I can use the user Id to make the link in databases.

However, my getUID() function is giving an error. I checked the cursor count and it's giving 1 which means there is a cursor. I also programmed the signup such that there will only be one cursor for email search. As email is unique.

But I'm getting this error

android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1 
                                                                               at android.database.AbstractCursor.checkPosition(AbstractCursor.java:426)
                                                                               at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
                                                                               at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
                                                                               at com.mycompany.jotyourlife.DatabaseHelper.getUID(DatabaseHelper.java:160)
                                                                               at com.mycompany.jotyourlife.LoginActivity.HomeScreenAccess(LoginActivity.java:71)
                                                                               at com.mycompany.jotyourlife.LoginActivity$1.onClick(LoginActivity.java:59)

WHERE THE ERROR IS:HomeScreenAccess function helper.getUID(cursor)

package com.mycompany.jotyourlife;

import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

public class LoginActivity extends AppCompatActivity {

EditText email;
EditText password;
Button login;

DatabaseHelper helper;

TextView registerLink;
String email_txt;
String password_txt;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);

    registerLink=(TextView) findViewById(R.id.link_to_register);
    registerLink.setOnClickListener(myListener);

    email =(EditText) findViewById(R.id.login_email);
    password = (EditText) findViewById(R.id.login_password);

    helper = new DatabaseHelper(LoginActivity.this);

    login = (Button) findViewById(R.id.btnLogin);

    login.setOnClickListener(myListener);

}

View.OnClickListener myListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        email_txt = email.getText().toString();
        password_txt = password.getText().toString();

        if(v.getId() == R.id.link_to_register){
            Intent i = new Intent(LoginActivity.this,RegisterActivity.class);
            startActivity(i);
        } else if(v.getId() == R.id.btnLogin) {
            //login attempt
            if(validateFields(email_txt, password_txt)) {
                if(helper.Login(email_txt , password_txt)){
                    HomeScreenAccess();
                }
            }
        }
    }
};

void HomeScreenAccess() {

    Intent i = new Intent(LoginActivity.this,MainActivity.class );
    Cursor cursor = helper.getAll(email_txt);
    Log.d("MYAPP" , "CURSOR SIZE: " + cursor.getCount());
    String user_ID = helper.getUID(cursor);
    Log.d("MYAPP" , " EMAIL: " + user_ID) ;
    i.putExtra("USERID" , "SRIJAN");
    startActivity(i);
}

boolean validateFields(String email, String password) {

    if (email.matches("")) {
        Log.d ("MYAPP", "email is empty");
        Toast.makeText(getApplicationContext(), "Email Field Empty", Toast.LENGTH_LONG).show();
        return false;
    } else if (password.matches("")) {
        Toast.makeText(getApplicationContext(), "Password Field Empty", Toast.LENGTH_LONG).show();
        Log.d("MYAPP" , "PASSWORD EMPTY");
        return false;
    } else {
        Log.d("MYAPP" , email + " " + password) ;
        return true;
    }
}

};

CODE FOR DATABASE HELPER: package com.mycompany.jotyourlife;

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;
import android.widget.Toast;

import java.sql.SQLException;

/**
 * Created by Shristi on 1/22/2016.
 */
public class DatabaseHelper extends SQLiteOpenHelper {


    private static final String DATABASE_NAME = "volleyball.db";
    private static final int SCHEMA_VERSION = 1;
    private static final String LOGIN_TABLE = "loginTable";
    private static final String ITEM_TABLE = "itemTable";

    //columns in LOGINTABLE
    private static final String KEY_UID = "_uid";
    private static final String KEY_NAME = "name";
    private static final String KEY_EMAIL = "email";
    private static final String KEY_PASS = "password";

    //columns in item table
        private static final String TABLE_ITEM = "itemTable";
        private static final String KEY_ITEM_ID = "_item_id";
        private static final String KEY_USER_ID = "user_id";
        private static final String KEY_TEXT = "text";
        private static final String KEY_URL = "photo_URL";
        private static final String KEY_DATE = "date_time";



    private SQLiteDatabase db;


    private static final String CREATE_LOGIN_TABLE = "CREATE TABLE loginTable ( " + KEY_UID + "  INTEGER PRIMARY KEY AUTOINCREMENT , " +
            "name TEXT , " +
            "email TEXT NOT NULL , " +
            "password TEXT NOT NULL);";

    private static final String CREATE_USER_TABLE = "Create TABLE itemTable ( " +
            "_item_id INTEGER PRIMARY KEY AUTOINCREMENT , " +
            " user_id INT  , " +
            " text LONGTEXT, " +
            " photo_URL VARCHAR(100), " +
            " date_time DATETIME ); ";


    public DatabaseHelper(Context context){
        super(context, DATABASE_NAME, null, SCHEMA_VERSION);
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w("MYAPP" , "Upgrade from version " + oldVersion + " to " + newVersion );

        db.execSQL("DROP TABLE IF EXISTS" + LOGIN_TABLE);
        onCreate(db);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL(CREATE_LOGIN_TABLE);
//        db.execSQL(CREATE_USER_TABLE);
    }

    public void clearDB () {

        Log.d("MYAPP" , "CLEARDB ");
        getWritableDatabase().execSQL("DROP TABLE IF EXISTS " + LOGIN_TABLE);
        getWritableDatabase().execSQL("DROP TABLE IF EXISTS " + ITEM_TABLE);
        Log.d("MYAPP", "Database Successfull Cleared");
        getWritableDatabase().execSQL(CREATE_LOGIN_TABLE);
        getWritableDatabase().execSQL(CREATE_USER_TABLE);
        Log.d("MYAPP", "Database Created ");
    }

    public long AddEntry(int user_id , String jourText , String photoURL ) {

        SQLiteDatabase db = getWritableDatabase();
        Log.d("MYAPP" , "Database created ");

        ContentValues contentValues = new ContentValues();
        contentValues.put(KEY_USER_ID, user_id);
        contentValues.put (KEY_TEXT , jourText);
        contentValues.put(KEY_URL , photoURL);
        contentValues.put(KEY_DATE , getDateTime());

        Log.d("MYAPP" , "ENTERY SAVED") ;


        return getWritableDatabase().insert(TABLE_ITEM , null, contentValues);
    }

    private String getDateTime() {
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();
        return dateFormat.format(date);
    }

    public long AddUser(String name, String email, String password) {
        ContentValues cv = new ContentValues();
        cv.put(KEY_NAME, name);
        cv.put(KEY_EMAIL, email);
        cv.put(KEY_PASS, password);

        Log.d("MYAPP", "USER SAVED");
        return getWritableDatabase().insert(LOGIN_TABLE, null, cv);
    }

    public boolean Login (String email ,String password) {
        Cursor mCursor = getReadableDatabase().rawQuery("SELECT * FROM " +
                LOGIN_TABLE +
                " WHERE email =? AND password=?"
                , new String[]{email, password});

        if(mCursor!=null) {
            if(mCursor.getCount()>0) {
                Log.d("MYAPP" , "cursor not null");
                return  true;
            }

        }
        Log.d("MYAPP", "cursor null") ;
        return false;
    }

    public Cursor getAll(String email) {
        return(getReadableDatabase()
                .rawQuery("SELECT * " +
                        " FROM " +
                        LOGIN_TABLE +
                        " WHERE " +
                        KEY_EMAIL+
                        " =? "
                        ,new String[]{email}));
    }

    public String getEmail(Cursor c){
        return  c.getString(c.getColumnIndex(KEY_EMAIL));
    }
    public String getPassword (Cursor c) {
        return  c.getString(c.getColumnIndex(KEY_PASS));
    }
    public String getName (Cursor c) {
        return  c.getString(c.getColumnIndex(KEY_NAME));
    }
    public String getUID(Cursor c) { return  c.getString(c.getColumnIndex(KEY_UID)); }



    //methods to access second database

    public String getMeDate(Cursor c) {
        return c.getString(c.getColumnIndex(KEY_DATE));
    }

    public String getMeJournalEntry(Cursor c) {
        return c.getString(c.getColumnIndex(KEY_TEXT));
    }




}

Replacement for SQLite in android

Which is best Mobile database a replacement for SQLite. I have googling and get this three name but any one have use any other.

Error in SQlite tablequery in android

I am a new android developer and am using SQlite for first time. I have a NullPointerException while creating Table and tried a lot to sort out the answer but was not able to. Am thanking in advance for your valuable time and help. Please find the code below:

 package com.example.kannan.football_manager;

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

    /**
     * Created by kannan on 25/1/16.
     */
    public class Admin_Database_Operations extends SQLiteOpenHelper
    {
        public static final String ADMIN_DB="admin_info";
        public static final String ADMIN_TB="abmin_table";
        public static final String ADMIN_NAME="admin_name";
        public static final String ADMIN_PASS="admin_pass";
        public static  final String COLUMN_ID="column_id";

        public  static final  int database_version=1;

        //creating database

        public Admin_Database_Operations(Context c)
        {
            super(c, ADMIN_DB,null,database_version);
            Log.d("database creation","database created");
        }




        @Override
        public void onCreate(SQLiteDatabase sqls) {

            String CREATE_PRODUCTS_TABLE = "CREATE TABLE " +
                    ADMIN_TB + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + ADMIN_NAME
                    + " TEXT," + ADMIN_PASS + " TEXT" + ")";

            sqls.execSQL(CREATE_PRODUCTS_TABLE);


            Log.d("Database Operation","TABLE CREATED IN DATABASE");
        }

        @Override
        public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

        }

         public SQLiteDatabase sq;
        public void putInformation(Admin_Database_Operations ado,String name,String pass)
        {

            sq=ado.getWritableDatabase();
            ContentValues cv=new ContentValues();

            cv.put(ADMIN_NAME,name);
            cv.put(ADMIN_PASS,pass);

            sq.insert(ADMIN_TB,null,cv);
            sq.close();

        }
    }



  package com.example.kannan.football_manager;

    import android.content.Context;
    import android.database.sqlite.SQLiteDatabase;
    import android.os.Bundle;
    import android.support.design.widget.FloatingActionButton;
    import android.support.design.widget.Snackbar;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.util.Log;
    import android.view.View;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;

    public class LoginActivity extends AppCompatActivity {

        public Button btn_Admin;
        public  Button btn_Cancel;
        public Button btn_Login;
        public Button btn_cngepsw;

        public EditText edttxt_name;
        public EditText edttxt_pass;

        public SQLiteDatabase sqldb;
        public Context ctx;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);
            //Declaring Nodes

          btn_Admin=(Button) findViewById(R.id.btn_Admin);
            btn_Cancel=(Button) findViewById(R.id.btn_Cancel);
            btn_Login=(Button) findViewById(R.id.btn_Login);
            btn_cngepsw=(Button) findViewById(R.id.btn_cngepsw);

            edttxt_name=(EditText) findViewById(R.id.edttxt_name);
            edttxt_pass=(EditText) findViewById(R.id.edttxt_pass);


            btn_Login.setOnClickListener(
                    new Button.OnClickListener()
                    {
                        public void onClick(View v)
                        {
                            String name="kannan";
                            String pass="pass";
                            Admin_Database_Operations ado=new Admin_Database_Operations(ctx);

                            ado.onCreate(sqldb);

                            ado.putInformation(ado, name, pass);

                            Log.d("Database operation", "INSERT ONE RAW");


                        }

                    }

            );


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

            FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
            fab.setOnClickListener(new View.OnClickListener()

            {
                @Override
                public void onClick(View view) {
                    Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();
                }
            });
        }

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

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

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

            return super.onOptionsItemSelected(item);
        }
    }

//Error

01-30 17:06:15.253 3677-3677/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: com.example.kannan.football_manager, PID: 3677
                                                 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.database.sqlite.SQLiteDatabase.execSQL(java.lang.String)' on a null object reference
                                                     at com.example.kannan.football_manager.Admin_Database_Operations.onCreate(Admin_Database_Operations.java:40)
                                                     at com.example.kannan.football_manager.LoginActivity$1.onClick(LoginActivity.java:54)
                                                     at android.view.View.performClick(View.java:4761)
                                                     at android.view.View$PerformClick.run(View.java:19767)
                                                     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:5312)
                                                     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:901)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)

Search Query and Update method bug in sqlite

So, here's my simple app. Whenever someone comes to my restaurant, they will enter their number on a tab set on the booth, if they are new here then it will be a new entry in the database, if they ate here before, then it will get the point from the database using the username and add the new points with the prev points and update the customer's points. Somehow it's not working when an existing username is searched. The keeps foreclosing

Here's my code in MainActivity

   //When the submit button is clicked
public void onButtonClick(View v) {

    if (v.getId() == R.id.bSubmit) {
        EditText uNum = (EditText) findViewById(R.id.number);
        String numstr = uNum.getText().toString();
        EditText uPoints = (EditText) findViewById(R.id.pnts);
        String pontstr = uPoints.getText().toString();
        int i = Integer.parseInt(pontstr);
        //takes in the customer's number and the purchase amount

        //search for the customer's number in database
        String user = helper.searchUname(numstr);

        if (numstr.equals(user)) {
            //if found then add the amount as new points
            int row = helper.searchRow(user);
            int point = helper.searchPoint(user);
            int pnt =  point + i;
            helper.updatePoint(pnt,user);

        }

        else {
            //create a new customer and add the info to database
            customer c = new customer();
            c.setuNum(numstr);
            c.setPoint(i);
            helper.insertcustomer(c);
        }

    }
}

And here's my database codes

public class DatabaseHelper extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "customers.db";
private static final String TABLE_NAME = "customers";
private static final String COLUMN_ID = "id";
private static final String COLUMN_UNUM = "uNum";
private static final String COLUMN_POINT = "Point";
SQLiteDatabase db;
private static final String TABLE_CREATE = "create table customers (id integer primary key not null , " +
        "uNum text not null , Point integer not null );";

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

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

public void insertcustomer(customer c) {
    db = this.getWritableDatabase();
    ContentValues values = new ContentValues();

    String query = "select * from customers";
    Cursor cursor = db.rawQuery(query , null);
    int count = cursor.getCount();

    values.put(COLUMN_ID , count);
    values.put(COLUMN_UNUM, c.getuNum());
    values.put(COLUMN_POINT, c.getPoint());
    db.insert(TABLE_NAME, null, values);
    db.close();
}

public String searchUname (String numstr){

    db = this.getReadableDatabase();
    String query = "select uNum from "+TABLE_NAME;
    Cursor c = db.rawQuery(query , null);
    String a = "not found";
    String b;

    c.moveToFirst();

    do{
        b = c.getString(0);
        if (b.equals(numstr)){
            a = b;

            break;
        }

    }
    while (c.moveToNext());

    return a;
}

public void updatePoint (int pnt, String user)
{
    db= this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(COLUMN_POINT, pnt);
    String [] whereargs = {user};

    db.update(TABLE_NAME, values, COLUMN_UNUM+" =?", whereargs);
}

public void deleteUser (String user){
    db = this.getWritableDatabase();
    String whereArgs [] = new String[1];
    whereArgs [0]= user;
    db.delete(TABLE_NAME, COLUMN_UNUM+"=?", whereArgs);
}


public int searchRow (String user){

    db = this.getReadableDatabase();
    String query = "select uNum, id from "+TABLE_NAME;
    Cursor c = db.rawQuery(query , null);
    int a = 0;
    String b;

    c.moveToFirst();

    do{
        b = c.getString(0);
        if(b.equals(user))
        {
            a = c.getInt(1);
            break;
        }

    }
    while (c.moveToNext());

    return a;
}






public int searchPoint(String uNum)
{
    db = this.getReadableDatabase();
    String query = "select uNum, Point from "+TABLE_NAME;
    Cursor cursor = db.rawQuery(query , null);
    String a;
    int b = 0;
    if(cursor.moveToFirst())
    {
        do{
            a = cursor.getString(0);

            if(a.equals(uNum))
            {
                b = cursor.getInt(1);
                break;
            }
        }
        while(cursor.moveToNext());
    }

    return b;
}


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

}

EF6 is using the wrong key when eager loading

I have successfully set up EF6 on Chinook database using SqlLite .NET provider.

Now, Playlists and Tracks is a many-many relationship mapped through the junction table PlaylistTracks.

The following query generates the wrong SQL statement where Track is mapped to PlaylistId (It should be TrackId) on the junction table.

var result = context.Playlists
    .Where(p => p.Name == "Brazilian Music")
    .SelectMany(pt => pt.PlaylistTracks)
    .Include(pt => pt.Track).OrderBy(pt => pt.TrackId);

SQL trace:

SELECT 
[Extent1].[PlaylistId] AS [PlaylistId], 
[Extent2].[PlaylistId] AS [PlaylistId1], 
[Extent2].[TrackId] AS [TrackId], 
[Extent3].[TrackId] AS [TrackId1], 
[Extent3].[Name] AS [Name], 
[Extent3].[AlbumId] AS [AlbumId], 
[Extent3].[MediaTypeId] AS [MediaTypeId], 
[Extent3].[GenreId] AS [GenreId], 
[Extent3].[Composer] AS [Composer], 
[Extent3].[Milliseconds] AS [Milliseconds], 
[Extent3].[Bytes] AS [Bytes], 
[Extent3].[UnitPrice] AS [UnitPrice]
FROM   [Playlist] AS [Extent1]
INNER JOIN [PlaylistTrack] AS [Extent2] ON [Extent1].[PlaylistId] = [Extent2].[PlaylistId]
INNER JOIN [Track] AS [Extent3] ON [Extent2].[PlaylistId] = [Extent3].[TrackId]
WHERE 'Brazilian Music' = [Extent1].[Name]
ORDER BY [Extent2].[TrackId] ASC

Somewhere towards the end of the last INNER JOIN I get

[Extent2].[PlaylistId] = [Extent3].[TrackId]

It should be [Extent2].[TrackId] = [Extent3].[TrackId] where [Extent2] is the junction table.

How can I make EF6 map to the correct foreign key?

Appreciate any help.

See my original question Linq query returns the same names even though they should be different

Using an alias defined in `FROM` part, instead of a column result sub‑query: is it possible?

Question

For readability mainly, while I know I could achieve the same with a TEMPORARY TABLE, I would like to avoid the latter (personal preference to have the whole in a single query).

The question is asked in the context of standard SQL.

Abstract case

Say I have something about like this:

SELECT a, (a IN (SELECT … )) as b,
FROM t

Is there any way to have something like this instead:

SELECT a, (a IN u) as b,
FROM t, (SELECT … ) as u

If I do this, the database engine (which is actually SQLite, for the anecdote), complains the table u is unknown. I though is would be visible, as it would be possible to use u as a column prefix.

I know I can do this:

CREATE TEMPORARY TABLE IF NOT EXISTS u AS SELECT … ;
SELECT a, (a IN u) as b,
FROM t

However, as I said above, I would like to avoid it, as I want a monolithic query (due to personal preferences).

That's mainly for readability when the sub‑query is a bit large, and it does not need to be a lot large, to prevent good readability.

I want use swiftdata (ryanfowler) for using sqlite in swift 2 but there is 120 errors ,what shouild i do?

i try using SwiftData [1]: http://ift.tt/1qJGsu3 ,when import it to my project i have 120 errors that some of them is for println ,how i can resolved another errors?i add string extensions but errors still remains

Querying the database passing multiple parameters rails

I have a user table and an activity table. The user has many activities. This is what i have in my users table:

class SorceryCore < ActiveRecord::Migration
  def change
create_table :users do |t|
    t.string :first_name
    t.string :surname
    t.integer :previous_award
    t.integer :chosen_award
  t.string :email,            :null => false
  t.string :crypted_password
  t.string :salt

  t.timestamps
end

add_index :users, :email, unique: true
end

This is what I have in my activities table:

class CreateActivities < ActiveRecord::Migration
  def change
create_table :activities do |t|
  t.integer :activity_type
  t.string :activity_name
  t.string :approver_email
  t.references :users, index: true, foreign_key: true

  t.timestamps null: false
end
end

In my view I want to show the activity_name, where user_id = the current user's id, and where the the activity_type = 1. I'm not sure where to write this method or how to call it either. I have read through the following link but can't seem to get anything working. http://ift.tt/Mfyo5w

I think I need to use something along the lines of this:

Activity.where("activity_type <= ?", 1).where("user_id <= ?", current_user.id)

But I'm not sure if this is supposed to go into a method in the controller or the model, and I'm not sure which controller or model it's supposed to go into