samedi 28 février 2015

Data is not retrieving from android SQLite

I am trying to retrieve data from sq lite database in array list in toast message, but showing


[ util.AllProfileElement @4b0ae658,util.AllProfileElement @4b0a258c,...........]


like something my data is save in database which i confirm through toast message please help me get out of thisenter code here


Database Helper Class:



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

public class DatabaseHeleper extends SQLiteOpenHelper{

// Database Name
private static final String DATABASE_NAME = "profile.db";
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
//table name
public static final String PROFILE_TABLE_NAME = "profile_table";

// Table Columns names
public static final String COL_PROFILE_ID = "id";
public static final String COL_PROFILE_NAME = "name";
public static final String COL_PROFILEE_GENDER = "gender";
public static final String COL_PROFILE_BLOOD = "blood";
public static final String COL_PROFILE_AGE= "age";
public static final String COL_PROFILE_HEIGHT= "height";
public static final String COL_PROFILE_WEIGHT = "weight";

// table information
private static final String DATABASE_PROFILE_TABLE = "create table "+ PROFILE_TABLE_NAME +
"( " + COL_PROFILE_ID + " integer primary key autoincrement, " + " "
+ COL_PROFILE_NAME + " text not null," + " "
+ COL_PROFILEE_GENDER + " text not null," + " "
+ COL_PROFILE_BLOOD + " text not null," + " "
+ COL_PROFILE_AGE + " text not null," + " "
+ COL_PROFILE_HEIGHT + " text not null," + " "
+ COL_PROFILE_WEIGHT + " text not null);";



public DatabaseHeleper(Context thiscontext) {
// TODO Auto-generated constructor stub
super(thiscontext, DATABASE_NAME, null, DATABASE_VERSION);

}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_PROFILE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(DatabaseHeleper.class.getName(), "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_PROFILE_TABLE);
onCreate(db);
}


}


and ******Database Source code is:******



enter code here



package database;

import java.util.ArrayList;

import util.AllNameList;
import util.AllProfileElement;


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

public class DatabaseSource {

private SQLiteDatabase mDB;
private DatabaseHeleper mHelper;




public DatabaseSource(Context thiscontext) {
// TODO Auto-generated constructor stub
mHelper = new DatabaseHeleper(thiscontext);
}

public void open() throws SQLException {
mDB = mHelper.getWritableDatabase();
}

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


public long insertData(AllProfileElement object) {

try {
open();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


ContentValues values = new ContentValues();

values.put(DatabaseHeleper.COL_PROFILE_NAME, object.getName());
values.put( DatabaseHeleper.COL_PROFILE_AGE, object.getAge());
values.put( DatabaseHeleper .COL_PROFILEE_GENDER, object.getGender());
values.put( DatabaseHeleper .COL_PROFILE_BLOOD, object.getBlood());
values.put( DatabaseHeleper .COL_PROFILE_HEIGHT,object.getHeight());
values.put( DatabaseHeleper .COL_PROFILE_WEIGHT, object.getWeight());

long inserted = mDB.insert( DatabaseHeleper. PROFILE_TABLE_NAME, null, values);
close();

this.close();

return inserted;
}
//public ArrayList<AllProfileElement> getAllProfile() {
public ArrayList<AllProfileElement> getAllProfile()
{
//ArrayList<AllProfileElement> allprofile = new ArrayList<AllProfileElement>();
ArrayList<AllProfileElement> allprofile = new ArrayList<AllProfileElement>();
/* try {
open();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Cursor mCursor = mDB.query(DatabaseHeleper.PROFILE_TABLE_NAME, null, null, null, null,
null, null);*/

try {
open();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Cursor mCursor = mDB.query(DatabaseHeleper.PROFILE_TABLE_NAME, null, null, null, null,
null, null);



// looping through all rows and adding to list
if (mCursor != null && mCursor.getCount() > 0) {
mCursor.moveToFirst();

for (int i = 0; i < mCursor.getCount(); i++) {

int mID = mCursor.getInt(mCursor.getColumnIndex(DatabaseHeleper.COL_PROFILE_ID));
String name = mCursor.getString(mCursor.getColumnIndex(DatabaseHeleper.COL_PROFILE_NAME));
String age = mCursor.getString(mCursor.getColumnIndex(DatabaseHeleper.COL_PROFILE_AGE));
String gender = mCursor.getString(mCursor.getColumnIndex(DatabaseHeleper.COL_PROFILEE_GENDER));
String blood = mCursor.getString(mCursor.getColumnIndex(DatabaseHeleper.COL_PROFILE_BLOOD));
String height = mCursor.getString(mCursor.getColumnIndex(DatabaseHeleper.COL_PROFILE_HEIGHT));
String weight = mCursor.getString(mCursor.getColumnIndex(DatabaseHeleper.COL_PROFILE_WEIGHT));
AllProfileElement mProfile = new AllProfileElement(mID, name,age,gender,blood,height,weight);

allprofile.add(mProfile);
mCursor.moveToNext();
}
}
mCursor.close();
mDB.close();

// return place list
return allprofile;
}

}

SQLite - Insert Trigger on TABLE 1 to conditional update TABLE 2

Background:


My trigger works but is broken. Because of the coding and the UNIQUE value on the target table [tbl_ccc_part], the trigger throws all of the inserted values into the table and silently drops the ones that violate the UNIQUE condition. This causes [tbl_ccc_part] to grow by 2,000 records instead of a couple of hundred.


Question:


How do I effectively limit this trigger so that I get back to the original intent.


Intended Code Walkthrough:


INSERT on [tbl_ccc_inventory] of [tbl_ccc_inventory.[business_level_supplier_id]],[tbl_ccc_inventory.[stock_number]], and other non-relevant records.


TRIGGER looks through [tbl_ccc_part.[business_level_supplier_id]] AND [tbl_ccc_part.[stock_number]]. If there is a match on both, do not INSERT. If there is not a match, INSERT record.


CODE:



CREATE TRIGGER trg_insert_ccc_inventory AFTER INSERT ON tbl_ccc_inventory
/* This trigger automatically updates tbl_ccc_part after entries are
inserted into the tbl_ccc_inventory. These entries make several
assumptions about the values needed for tbl_ccc_part and should
be verified for accuracy by someone. */
BEGIN
INSERT OR IGNORE INTO tbl_ccc_part
(
record_id,
business_level_supplier_id,
stock_number,
oem_part_number,
part_type,
assembly_indicator,
insurer_program,
warranty_type,
warranty_length,
shippable_part
)
VALUES (
"A",
new.business_level_supplier_id,
new.stock_number,
new.stock_number,
"OD",
"N",
"N/A",
"LIMITED",
"LIMITED",
"Y");
END;

How to execute select query in sqlite by android

I have write this code for select filtered data from sqlite db through android. But it says there are some error. Can you help me to correct my code please.



category = data[0];
district = data[1];

SQLiteDatabase db = openOrCreateDatabase("dbumbers", 1, null);

Cursor c = db.rawQuery("SELECT * FROM numbers where [category = '"+category+"'] and [district = '"+district+"']", null);

Android - Database sync, Client and Server, SyncAdapter? ContentProvider?

I have an android client and a arbitrary webb server. The client has a local SQLite database. The server has a MySQL database.


I want to synchronize the client database so that it is always up-to-date with the server database.


My concerns is on how i should do the synchronization on the client side. My current approach is using a syncAdapter and then I'm trying to somehow hook up a contentProvider to change the data in the SQLite database. From my reading on the android developer site i interpreter this is how you should do it. (As new to android development I feel the contentProvider is hard to understand)



  • Is this the best approach or is there some better/easier way to do it?

  • Can I use the sync adapter but exclude using the content Provider? If so how could I make such an approach?




I have set up the sync adapter accordingly to this developer guide: http://ift.tt/1iPZgZz


I guess I have to set up the ContentProvider accordingly: http://ift.tt/1eNYhY6


SQLite multiple values in a column Java

What I want is multiple values in a column in SQLite in Java. I can not seem to find any certain documentation on how to do that. Anyone has a link on how to do it or if you know yourself?.


lag/slowdown when I try to display many images in a listview?

When I have so many images to display in a listview when I flow to the bottom of a picture to another there is a 1 second pause. I save the file path in the sd card in the database sqlite internal adapter and therefore in each element is taken before and after the sqlite database from SD card. How do I not have that annoying lag between an image and another? If I view the image grabbing resources such as (R.drawable.image) this does not bother you, I could make images of sd card reached as to the internal resources to the application? Perhaps accidentally memorize the pictures, I should save them for example in Android / data / com.my.app? (Images except the sd card in pictures folder). How can I improve this?


How to call this shell script to convert mysqldump to SQLite compatible syntax

I need to autonomously convert mysqldump files (.sql file) to SQLite compatible .sql files. I found this script on github which is supposed to be able to do this. If I had an unmodified .sql file from MySQL called test.sql whose database's name was test and the script mysql2sqlite.sh in a directory, how would I call it.


The script says in the comments how to call it. I believe my scenario matches the first one titled usage because I already have the mysqldump file.



# Usage: $ ./mysql2sqlite mysqldump-opts db-name | sqlite3 database.sqlite
# Example: $ ./mysql2sqlite --no-data -u root -pMySecretPassWord myDbase | sqlite3 database.sqlite


I read in the comments on the github page to change the scripts permissions with chmod +x mysql2sqlite.sh so navigated to the directory with the sql and the script and did that. Then I tried:


pi@raspberrypi ~ $ ./mysql2sqlite.sh test.sql test | sqlite3 database.sqlite


It failed with the error: -bash: ./mysql2sqlite.sh: /bin/sh^M: bad interpreter: No such file or directory


I then read online that to call an .sh file you type sh myShellFile.sh


So I tried sh mysql2sqlite.sh test.sql test | sqlite3 database.sqlite and got back:



: not founde.sh: 2: mysql2sqlite.sh:
: not founde.sh: 5: mysql2sqlite.sh:
: not founde.sh: 8: mysql2sqlite.sh:
: not founde.sh: 11: mysql2sqlite.sh:
: not founde.sh: 13: mysql2sqlite.sh:
: not founde.sh: 14: mysql2sqlite.sh:
mysqldump: Got error: 1045: Access denied for user 'pi'@'localhost' (using password: NO) when trying to connect
: not founde.sh: 15: mysql2sqlite.sh:


It appears that its trying to connect to a server rather than reading the mysqldump file that I provided. What is the proper way to call this script. I have some experience with Linux and no experience with unix shells.


It may be of some use to read the background of my problem


Insert into sqlite database

I have search on the other same problem on stackoverflow but I haven't find my problem. When I want to insert values on my SQLite database, I have an error that say I don't know firstName in the table. However, I have create firstName.


I give you my code DatabaseHandler:



public class DatabaseHandler extends SQLiteOpenHelper
{

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "android_project_database_user";

// Login table name
private static final String TABLE_LOGIN = "login";

// Login Table Columns names
private static final String KEY_NAME = "name";
private static final String KEY_FIRSTNAME = "firstName";
private static final String KEY_EMAIL = "mail";
// private static final String KEY_UID = "id";
private static final String KEY_COUNTRY = "country";
private static final String KEY_CITY = "city";


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

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
// + KEY_UID + " INTEGER PRIMARY KEY,"
+ KEY_FIRSTNAME + " TEXT,"
+ KEY_NAME + " TEXT,"
+ KEY_EMAIL + " TEXT UNIQUE PRIMARY KEY,"
+ KEY_COUNTRY + " TEXT,"
+ KEY_CITY + " TEXT" + ")";
db.execSQL(CREATE_LOGIN_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN);

// Create tables again
onCreate(db);
}

/**
* Storing user details in database
* */
public void addUser(String firstName, String name, String mail, String country, String city)
{
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(KEY_FIRSTNAME, firstName); // FirstName
values.put(KEY_NAME, name); // Name
values.put(KEY_EMAIL, mail); // Email
// values.put(KEY_UID, id); // id
values.put(KEY_COUNTRY, country); // country
values.put(KEY_CITY, city); // city

// Inserting Row
db.insert(TABLE_LOGIN, null, values);
db.close(); // Closing database connection
}

/**
* Getting user login status
* return true if rows are there in table
* */
public int getRowCount() {
String countQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int rowCount = cursor.getCount();
db.close();
cursor.close();

// return row count
return rowCount;
}

/**
* Re crate database
* Delete all tables and create them again
* */
public void resetTables(){
SQLiteDatabase db = this.getWritableDatabase();
// Delete All Rows
db.delete(TABLE_LOGIN, null, null);
db.close();
}

}


And my login.java



public class LoginActivity extends Activity implements OnClickListener{

// Edit and Button that the user fill
private EditText mail, pass;
private Button bLogin;
private CheckBox checkBox;

/****************/
/* Réponse JSON */
/****************/
// private static String KEY_UID = "id";
private static String KEY_NAME = "name";
private static String KEY_FIRSTNAME = "firstName";
private static String KEY_EMAIL = "mail";
private static String KEY_COUNTRY = "nationality";
private static String KEY_CITY = "city";

/**********************************/
/* Enregistrement des préférences */
/**********************************/

public static final String PREFS_NAME = ".Preferences";
private static final String PREF_EMAIL = "email";
private static final String PREF_PASSWORD = "password";
private static final String PREF_CHECKED = "checked";


// Progress Dialog
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://ift.tt/1N3GJGv";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mail = (EditText)findViewById(R.id.email);
pass = (EditText)findViewById(R.id.pass);
bLogin = (Button)findViewById(R.id.identify);
checkBox = (CheckBox)findViewById(R.id.cbRememberMe);

/***********************************************************************/
/* Restauration des préférences sauvegardées si la checkbox est cochée */
/***********************************************************************/

SharedPreferences pref = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
String email = pref.getString(PREF_EMAIL, "");
String password = pref.getString(PREF_PASSWORD, "");
String checked = pref.getString(PREF_CHECKED, "");

mail.setText(email);
pass.setText(password);
checkBox.setChecked(Boolean.parseBoolean(checked));

bLogin.setOnClickListener(this);
}

@Override
public void onClick(View v) {

/************************************************************/
/* Enregistrement des préférences si la checkbox est cochée */
/************************************************************/

if(checkBox.isChecked())
{
getSharedPreferences(PREFS_NAME,MODE_PRIVATE)
.edit()
.putString(PREF_EMAIL, mail.getText().toString())
.putString(PREF_PASSWORD, pass.getText().toString())
.putString(PREF_CHECKED,"TRUE")
.commit();
}

/***********************/
/* Sinon on les efface */
/***********************/

else if(!checkBox.isChecked())
{
getSharedPreferences(PREFS_NAME,MODE_PRIVATE).edit().clear().commit();
}

switch (v.getId()) {
case R.id.identify:
new AttemptLogin().execute();
// here we have used, switch case, because on login activity you may //also want to show registration button, so if the user is new ! we can go the //registration activity , other than this we could also do this without switch //case.
default:
break;
}
}

class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;

@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Attempting for login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}

@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
int success;
String email = mail.getText().toString();
String password = pass.getText().toString();
try {

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("mail", email));
params.add(new BasicNameValuePair("password", password));

Log.d("request!", "starting");

//utilise JSON pour renvoyer resultat
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);

// checking log for json response
Log.d("Login attempt", json.toString());

// success tag for json
success = json.getInt(TAG_SUCCESS);
if (success == 1) {

/***************************************/
/* Stocke les infos dans la BDD SQLite */
/***************************************/

DatabaseHandler db = new DatabaseHandler(getApplicationContext());
db.resetTables();
db.addUser(json.getString(KEY_FIRSTNAME), json.getString(KEY_NAME), json.getString(KEY_EMAIL), json.getString(KEY_COUNTRY), json.getString(KEY_CITY));

/***************************************/
/* Lancement de l'Activity "MainMenuActivity" */
/***************************************/

Log.d("Successfully Login!", json.toString());

Intent i = new Intent(LoginActivity.this,MainMenuActivity.class);

startActivity(i);

finish();

return json.getString(TAG_MESSAGE);
}else{

return json.getString(TAG_MESSAGE);

}
} catch (JSONException e) {
e.printStackTrace();
}

return null;
}
/**
* Once the background process is done we need to Dismiss the progress dialog asap
* **/
protected void onPostExecute(String message) {

pDialog.dismiss();
if (message != null){
Toast.makeText(LoginActivity.this, message, Toast.LENGTH_LONG).show();
}
}
}
}


And to finish my login.php



<?php
session_start();

include ('config.php');

// Recup elem to make the login_connection
$password=$_POST["password"];
$mail=$_POST["mail"];

if (!empty($_POST)) {
if (empty($_POST['mail']) || empty($_POST['password'])) {
// Create some data that will be the JSON response
$response["success"] = 0;
$response["message"] = "One or both of the fields are empty .";
die(json_encode($response));
}

//prepare the select statement
$query = $handler->prepare('SELECT id, name, firstName, mail, nationality, city FROM login WHERE mail = :mail AND password= :password');

//bind the parameters
$query->bindParam(':mail', $mail, PDO::PARAM_STR);
$query->bindParam(':password', $password, PDO::PARAM_STR);

//execute the prepared statement
$query->execute();

//create array
$response = array();

//check for a result
$row = $query->fetch(PDO::FETCH_ASSOC);

if (!empty($row)) {
$response["success"] = 1;
$response["message"] = "You have been sucessfully login";
$response["id"]= $row["id"];
$response["firstName"]= $row["firstName"];
$response["name"]= $row["name"];
$response["mail"]= $row["mail"];
$response["nationality"]= $row["nationality"];
$response["city"]= $row["city"];

$_SESSION['mail'] = $mail;
die(json_encode($response));
}
}
else{

$response["success"] = 0;
$response["message"] = " One or both of the fields are empty ";
die(json_encode($response));
}
?>


When I display the value of each elements that I want to put in my dataBase, they take their good value.


Thank you very much for your help.


Mickey74


Getting Nullpointer exception when i try to insert data in sqlite

In my database there are 2 tables. One for login info and another for store some report data. When i try to insert data in login table, it is successful. But when i try to insert report data, i get "NullPointerException" error. In different ways i checked and confirm that i am not sending any null value.


Please check the code below.



public class StoreReport {

public static final String KEY_ROWID = "_uid";
public static final String KEY_NAME = "username";
public static final String KEY_password = "userpassword";

private static final String DATABASE_NAME = "personal.db";
private static final String DATABASE_TABLE1 = "user";
private static final String DATABASE_TABLE2 = "dailyreport";
private static final int DATABASE_VERSION = 1;

private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;

private static class DbHelper extends SQLiteOpenHelper {

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

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE1 + "(" +
KEY_ROWID + " INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_password + " INTEGER NOT NULL " +
");"
);

db.execSQL("CREATE TABLE " + DATABASE_TABLE2 + "(" +
" _rid INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, " +
" reportdate TEXT, " +
" qutelawat INTEGER, " +
" qustudy INTEGER, " +
" hadstudy INTEGER, " +
" bookstudy INTEGER, " +
" namaj_jamat INTEGER, " +
" namaj_kaja INTEGER, " +
" dawahcont INTEGER, " +
" manpcont INTEGER, " +
" progjoin INTEGER, " +
" orgtime INTEGER, " +
" digitaltime INTEGER, " +
" pstudy INTEGER, " +
" family INTEGER, " +
" society INTEGER, " +
" selfrel INTEGER " +
");"
);

}

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

public StoreReport(Context c) {
ourContext = c;
}

public StoreReport open() {
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}

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

public long createEntryUser(String uname, String upass) {
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, uname);
cv.put(KEY_password, upass);
long i = ourDatabase.insert(DATABASE_TABLE1, null, cv);
return i;
}

public long createEntryReport(String data1, int data2, int data3, int data4,
int data5, int data6, int data7, int data8,
int data9, int data10, int data11, int data12,
int data13, int data14, int data15, int data16) {
ContentValues cv1 = new ContentValues();
cv1.put("reportdate", data1);
cv1.put("qutelawat", data2);
cv1.put("qustudy", data3);
cv1.put("hadstudy", data4);
cv1.put("bookstudy", data5);
cv1.put("namaj_jamat", data6);
cv1.put("namaj_kaja", data7);
cv1.put("dawahcont", data8);
cv1.put("manpcont", data9);
cv1.put("progjoin", data10);
cv1.put("orgtime", data11);
cv1.put("digitaltime", data12);
cv1.put("pstudy", data13);
cv1.put("family", data14);
cv1.put("society", data15);
cv1.put("selfrel", data16);

try {
long i = ourDatabase.insert(DATABASE_TABLE2, null, cv1);
return i;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}

public boolean verify_user(String pass) {
String p;
String[] data = new String[]{KEY_ROWID, KEY_NAME, KEY_password};

Cursor cr = ourDatabase.query(DATABASE_TABLE1, data,
KEY_password + " = '" + pass + "'", null, null, null, null);

if (cr.getCount() == 1) {
cr.moveToFirst();
p = cr.getString(2);
return p.equals(pass) ? true : false;
} else {
return false;
}
}


}


Clearing multiple prompts it sqlite3

I have started to play with sqlite3, and using .prompt command for creating multiple prompts, but I can't clear them. I mean to return back to normal "sqlite3>" prompt, except for exiting sqlite3 and starting all over again. Google does not seem to now how xD. I'm using win7/64bit, version SQLite3.


sqlite "General error 1: no such table" when testing with phpunit

I have read all the related questions and answers here on StackOverflow and I have also read the relevant parts in the phpunit manual, and searched the internet etcetera. I am new to unit testing and would like to understand what goes wrong here. I have 2 classes, one for checking uploaded image files and one for saving sanitized filenames and hashed paths in a simple sqlite db table. I have managed to build working tests for most of the methods in the first class. But in the second class I have been stuck for hours now:


When I run a test on this method:




public function saveToDatabase($filename){
$this->initialize();
$this->upload->add([
'0' => $filename,
'1' => $this->imgpath,
]);
}


It calls the method "add" below, to store filename and path in the sqlite table declared in the constructor. When the test comes to the INSERT part in the SQL statement it fails and declares the error "General error 1: no such table". When I run the classes in its normal environment everything works, so there is nothing wrong with paths etc. It is only when trying to run that specific test case, that I get an error. I should also mention that I have read about setting up a sqlite table in memory using the getConnection and getDataSet methods, but I don't understand how that will help me test my class that saves filenames in my sqlite table. I also understand that my question makes it clear that I am a total noob, but I am totally stuck, so I would be appreciate any suggestions.




/**
* Save to database.
*
*/
private $pdo;

public function __construct(){

//for test purpose, replace with wanted db
$this->pdo = new \PDO("sqlite:test_upload.sqlite");
$this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_WARNING); // Display errors

}


public function add($upload) {
$stmt = $this->pdo->prepare("INSERT INTO test_upload (san_filename, path) VALUES(?, ?)");
$stmt->execute($upload);
}

public function findLast()
{
$id = $this->pdo->lastInsertId();
$stmt = $this->pdo->prepare('SELECT * FROM test_upload WHERE rowid = ?;');
$stmt->execute(array($id));
$lastimg = $stmt->fetchAll(\PDO::FETCH_ASSOC);
return $lastimg;
}


Where can I get a better understanding of the overall and indepth understanding of instantiation with Context parameters?

I am trying to resolve the connection between Context and Classes in this code and my understanding of this concept. The MainActivity.this does not work here. It came with the surrounding code.





package com.Table;


import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.tablefreezepane.DatabaseHandler;
import com.example.tablefreezepane.MainActivity;

import java.util.ArrayList;
import java.util.List;

public class AsyncInsertData extends AsyncTask<String, String, String> {

DatabaseHandler databaseHandler;
String type;
long timeElapsed;

protected AsyncInsertData(String type){
this.type = type;
this.databaseHandler = new DatabaseHandler(MainActivity.this);
}

// @type - can be 'normal' or 'fast'
//@Override
//protected void onPreExecute() {
// super.onPreExecute();
// tvStatus.setText("Inserting " + editTextRecordNum.getText() + " records...");
//}

@Override
protected String doInBackground(String... aurl) {

try {

// get number of records to be inserted
int insertCount = 20;

// empty the table
databaseHandler.deleteRecords();

// keep track of execution time
long lStartTime = System.nanoTime();

if (type.equals("normal")) {
databaseHandler.insertNormal(insertCount);
} else {
databaseHandler.insertFast(insertCount);
}

// execution finised
long lEndTime = System.nanoTime();

// display execution time
timeElapsed = lEndTime - lStartTime;

} catch (Exception e) {
e.printStackTrace();
}
return null;
}

protected void onPostExecute(String unused) {
Toast.makeText(getApplicationContext(),"This is an Android Toast Message", Toast.LENGTH_LONG).show();
//tvStatus.setText("Done " + choice + " inserting " + databaseHandler.countRecords() + " records into table: [" + this.databaseHandler.tableName + "]. Time elapsed: " + timeElapsed / 1000000 + " ms.");
}

}



Reading or copying code is not a problem. The problem exists in the overall thought model of the Context parameter in the





this.databaseHandler = new DatabaseHandler(MainActivity.this);


statement. The line code has to be there in order to call the methods in the databaseHandler class.





package com.example.tablefreezepane;

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


public class DatabaseHandler extends SQLiteOpenHelper {

// for our logs
public static final String TAG = "DatabaseHandler.java";

public TextView tvstatus;

// database version
private static final int DATABASE_VERSION = 7;

// database name
protected static final String DATABASE_NAME = "NinjaDatabase2";

// table details
public String tableName = "locations";
public String fieldObjectId = "id";
public String fieldObjectName = "name";
public String fieldObjectDescription = "description";

// constructor
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// creating table
@Override
public void onCreate(SQLiteDatabase db) {

String sql = "";
this.tvstatus.setText("Creating table");

sql += "CREATE TABLE " + tableName;
sql += " ( ";
sql += fieldObjectId + " INTEGER PRIMARY KEY AUTOINCREMENT, ";
sql += fieldObjectName + " TEXT, ";
sql += fieldObjectDescription + " TEXT ";
sql += " ) ";

db.execSQL(sql);
this.tvstatus.setText("Table created...");

// create the index for our INSERT OR REPLACE INTO statement.
// this acts as the WHERE name="name input" AND description="description input"
// if that WHERE clause is true, I mean, it finds the same name and description in the database,
// it will be REPLACEd.
// ELSE, what's in the database will remain and the input will be INSERTed (new record)
String INDEX = "CREATE UNIQUE INDEX locations_index ON "
+ tableName + " (name, description)";

db.execSQL(INDEX);
}

/*
* When upgrading the database, it will drop the current table and recreate.
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

String sql = "DROP TABLE IF EXISTS " + tableName;
db.execSQL(sql);

onCreate(db);
}

// insert data using transaction and prepared statement
public void insertFast(int insertCount) {

// you can use INSERT only
String sql = "INSERT OR REPLACE INTO " + tableName + " ( name, description ) VALUES ( ?, ? )";

SQLiteDatabase db = this.getWritableDatabase();

/*
* According to the docs http://ift.tt/1rexubC
* Writers should use beginTransactionNonExclusive() or beginTransactionWithListenerNonExclusive(SQLiteTransactionListener)
* to start a transaction. Non-exclusive mode allows database file to be in readable by other threads executing queries.
*/
//db.beginTransactionNonExclusive();
db.beginTransaction();

SQLiteStatement stmt = db.compileStatement(sql);

for(int x=1; x<=insertCount; x++){

stmt.bindString(1, "Name # " + x);
stmt.bindString(2, "Description # " + x);

stmt.execute();
stmt.clearBindings();

}

db.setTransactionSuccessful();
db.endTransaction();

}

// inserts the record without using transaction and prepare statement
public void insertNormal(int insertCount){
try{

SQLiteDatabase db = this.getWritableDatabase();

for(int x=1; x<=insertCount; x++){

ContentValues values = new ContentValues();
values.put(fieldObjectName, "Name # " + x);
values.put(fieldObjectDescription, "Description # " + x);

db.insert(tableName, null, values);

}

db.close();

}catch(Exception e){
e.printStackTrace();
}
}

// deletes all records
public void deleteRecords(){

SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+ tableName);
db.close();
}

// count records
public int countRecords(){

SQLiteDatabase db = this.getWritableDatabase();

Cursor cursor = db.rawQuery("SELECT count(*) from " + tableName, null);
cursor.moveToFirst();

int recCount = cursor.getInt(0);

cursor.close();
db.close();

return recCount;
}

}



Any guidance, links to graphic models, to how the





this.databaseHandler = new DatabaseHandler(MainActivity.this);


statement is constructed would be appreciated Thank you in advance.


No results from sqlalchemy query to SQLite DB

Im attempting to validate user credentials stored in a sqlite db via sqlalchemy.


The relevant code is as follows:



from flask import Flask
from flask.ext.httpauth import HTTPBasicAuth
from models import User, Base
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

engine = create_engine('sqlite:///users.db')
Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
session = DBSession()

app = Flask(__name__)

auth = HTTPBasicAuth()

@auth.get_password
def get_password(username):
return session.query(User.password).first()[0]

@app.route('/')
@auth.login_required
def welcome():
return 'Hello, %s' %auth.username()

if __name__ == '__main__':
app.run(host='localhost', port=8080, debug=True)


However, i get 'None' back even though there is a matching record in the DB.


When I attempt to query the DB directly from my models.py, I get the expected results. My models.py code is as follows:



from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class User(Base):
__tablename__ = 'userdb'
id = Column(Integer, primary_key=True, nullable=False)
username = Column(String(64), nullable=False)
password = Column(String(64), nullable=False)
email = Column(String(255), nullable=True)

engine = create_engine('sqlite:///users.db')
Base.metadata.create_all(engine)

DBSession = sessionmaker(bind=engine)
session = DBSession()

username = 'x'

match = session.query(User).filter(User.username == username).all()[0]
print match.password

SQlite reorder integer autoincrement when I delete some row

I have a SQLite database that have a table called Bookmarks. This table have an integer autoincrement column called Id.


Supose that I have three rows in this table, like this:



Id | Name
1 | Bookmark 1
2 | Bookmark 2
3 | Bookmark 3


If I delete the row 2, so I get this:



Id | Name
1 | Bookmark 1
3 | Bookmark 3


Anyone knows how can I reorder the Id sequence to get like this:



Id | Name
1 | Bookmark 1
2 | Bookmark 3


Justa an observation: I allready know how to restore the sqlite_sequence table sequence.


Tks for the help! =D


Why HashMap method returns null object reference?

I've tried to make a HashMap method to get SQLite database data, but when I call the method it returns null reference that made my Android app stop working.


This my code:


HashMap method:



public HashMap<String, String> getUserDetails(){
HashMap<String,String> user = new HashMap<String,String>();
String selectQuery = "SELECT * FROM " + TABLE_LOGIN;

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

cursor.moveToFirst();
if(cursor.getCount() > 0){
user.put("name", cursor.getString(1));
user.put("position", cursor.getString(2));
user.put("level", cursor.getString(3));
user.put("email", cursor.getString(4));
user.put("uid", cursor.getString(5));
user.put("created_at", cursor.getString(6));
}
cursor.close();
db.close();

return user;
}


and this how I call the method in other class



DatabaseHandler db = new DatabaseHandler(getApplicationContext());
HashMap<String,String> userDetail= db.getUserDetails();
int userLevel = Integer.parseInt(userDetail.get("level").toString());


anyway I use a tutorial reference to make this and merge with my own needs.


Are there any examples of finding ancestor elements in an adjacency list db?

I have a DB in SQLite3 and I'm trying to figure out a recurrent query to get all ancestor elements from a many-to-many hierarchy. I can find lots of examples of traveling down the hierarchy, but no examples of going up. I don't need the whole path, just the top level element.


The table is organized like this: parentID | name | childID | level


Thanks!


Importing .csv into .db

Okay, I hope I don't sound stupid with any of the questions I'm asking because I'm very new to this. I used aSQLiteManager from the Play Store to backup the contents of a database (Contents_Setup) of one of my apps, then I deleted this table. The backup was stored as a csv file. The app was reinstalled, so the contents of this table are empty now. I tried to import the csv file back into the table, but I get an error ...CSV Import Error: Length=1; Index=1. Now, I am not educated in SQLite, I actually just started reading a tutorial for beginners. I am using only my android tablet, no PC. Is there anyone who can advise me on how to handle this error?


Calling an AlertDialog in another class from a button onClick in another Activity

I want to call my AlertDialog "DeleteConfirm" in my Alerts.class from my AccountManager.class through a button onClick event. How do I go about this without affecting the AlertDialog's ability to delete an entry from my database.


If there are any pieces of code that are missing for reference please feel free to ask.


AlertDialog "DeleteConfirm" snippet:



public class Alerts extends Activity {



public static void ShowAccAddedAlert(Context con)
{
AlertDialog.Builder builder=new AlertDialog.Builder(con);
builder.setTitle("Add new Account");
builder.setIcon(android.R.drawable.ic_dialog_info);
DialogListener listener=new DialogListener();
builder.setMessage("Account Added successfully");
builder.setPositiveButton("ok", listener);

AlertDialog diag=builder.create();
diag.show();
}

public static AlertDialog DeleteConfirm(final Context con, final Account Acc) {


AlertDialog.Builder b = new AlertDialog.Builder(con);
b.setTitle("Account Details");
LayoutInflater li = LayoutInflater.from(con);
View v = li.inflate(R.layout.delete, null);
b.setView(v);

b.setPositiveButton("Yes", new OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
DatabaseHelper db = new DatabaseHelper(con);
db.DeleteAcc(Acc);
}
});

b.setNegativeButton("No", null);

return b.create();

}
}


AccountManager button onClick snippet:



public class AccountDetails extends Activity {


@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.accdetails);

Button delete = (Button) findViewById(R.id.delete);
delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//THIS IS WHERE I WANT TO CALL MY DeleteConfirm AlertDialog
}
});
}
}

Creating a Login in android using SQLite

The scenario is that I want to create a login for my app which uses sqlite, it hasnt got to be secure as its for demonstration purposes only and wont be storing any personal information about real people. But so far I can create an account, but when i try to log in, the trouble starts. I have a method which is supposed to get a password for the email (the email is the parameter) my code so far is this -



public String getSingleEntry1(String email)
{
SQLiteDatabase database = open();
database.beginTransaction();

Cursor cursor=database.query(DataBaseHelper.TABLE_NAME, null, DataBaseHelper.COLUMN_EMAIL + "=?", new String[]{email}, null, null, null);
if(cursor.moveToFirst()) // UserName Not Exist
{
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String password = cursor.getString(cursor.getColumnIndex(DataBaseHelper.COLUMN_PASSWORD));
cursor.close();
database.setTransactionSuccessful();
database.endTransaction();
close(database);

return password;}


The error happens at String password line. The error is - 02-28 15:11:28.683 11381-11381/com.example.joeliomason.projectme E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.example.joeliomason.projectme, PID: 11381 android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0


I know I have a stupid error somewhere, but I cant figure out where, any help wold be appreciated :)


How to load TextViews from Database?

okay, I'm tryna make a "Lyrics" app and I wanna make it simple by loading Lyrics from Database. Is there any samples or ideas that you guys could help me out with?


BTW! I found this app, it's cool I wanna make an app like THIS


Thanks!


SQL Lite Prepopulating

We had an app which was getting data from online API, to render data in the UI. We are planning to make it into a local SQLLite App. What is the best way to achieve this. More about the App: Its a rate chart of some parts of an Automobile. There are about 5000 parts..


Requirements: 1. On opening the app, check if table exists, else create it and insert the data from the online APIs. 2. Fetch Data from the SQL Lite instead of reading from the API. 3. Auto Sync or Manual Sync of data from the mobile.


Kindly enlighten me what would be the best approach to handle this.


Search is not bringing anything back

I have wrote code to bring back records from a 'DataHandler.java' file. However when I search anything nothing appears. The code is meant to get the film details from 'DataHandler.java' and display them in the ScrollView.



public void search (View v) {
EditText edtSearchTerm = (EditText) findViewById(R.id.edtSearch);
String searchTerm = "%" + edtSearchTerm.getText().toString() + "%";
db = new DataHandler(this).getReadableDatabase();
String[] tblColumns = {"*"};
String whereClause = "film LIKE ? OR actor1 LIKE ? OR actor2 LIKE ? OR director LIKE ?";
String[] whereArgs = {searchTerm, searchTerm, searchTerm, searchTerm};
Cursor searchResults = db.query("films", tblColumns, whereClause, whereArgs, null, null, null);
showFilms(searchResults);
}

public void showFilms(Cursor c) {
final LinearLayout resultLayout = (LinearLayout) findViewById(R.id.resultLayout);
if (resultLayout.getChildCount() > 0) {
resultLayout.removeAllViews();
}

while (c.moveToNext()) {
int titleIndex = c.getColumnIndex("title");
int directorIndex = c.getColumnIndex("director");
int idIndex = c.getColumnIndex("id");
String title = c.getString(titleIndex);
String director = c.getString(directorIndex);
int filmID = c.getInt(idIndex);

TextView txt = new TextView(getApplicationContext());
txt.setId(filmID);
txt.setText(title + ", " + director);
txt.setTextColor(Color.BLACK);
txt.setTextSize(15);
txt.setClickable(true);
txt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity4.class);
intent.putExtra(FILM, String.valueOf(v.getId()));
startActivity(intent);
}
});
resultLayout.addView(txt);
}
};

SQLite RawQuery Android

sorry for the noob question.


But I am little stuck as to how to continue with this Method I am writing for an Android Application.


I wish to select some data from two columns in a database based on whether or not two other columns meet a certain condition. I tried creating a raw query but think that I am doing it completely wrong.


Below is the Method I wrote:



public String[] getDayTotals(String year, String month) {
SQLiteDatabase db = sqlHelper.getWritableDatabase();

String query = "SELECT " + sqlHelper.DAY_TOTAL + " AND " + sqlHelper.DAY + " FROM " + sqlHelper.TABLE_NAME + " WHERE " + sqlHelper.YEAR + "=? AND " + sqlHelper.MONTH + "=?";
String[] args = {year, month};

Cursor cursor = db.rawQuery(query, args);
cursor.moveToFirst();

StringBuilder sb = new StringBuilder();

while(cursor.moveToNext()) {

int indexTotal = cursor.getColumnIndex(sqlHelper.DAY_TOTAL);
int indexDay = cursor.getColumnIndex(sqlHelper.DAY);

String value = cursor.getString(indexTotal);
String day = cursor.getString(indexDay);

sb.append(value + "," + day + "\n");

}

String[] temp = sb.toString().split("\n");

return temp;
}


I am very new to SQL and as such am not quite sure how to continue. I do apologize for any stupid mistakes I have made.


SELECT COUNT (DISTINCT ZUSER) in core data

I'm new in core data I'm converting my sql query to fetch the coredata results but not able to convert this query.



SELECT COUNT (DISTINCT ZUSER) AS Users,ZHOUR ,SUM ( ZLIKE) As Likes FROM ZUSERLIKE where ZDAY=28 AND ZMONTH=2 AND ZYEAR=2015 GROUP BY ZHOUR


Any expert can help me out the problem I'm facing at COUNT (DISTINCT ZUSER) this point.


Android cursor sometimes returns empty even when the data exists

I have an android application that first fetch some data from the web (any updates that might available for an Item) and write the data and after that read the fetched data from the database. The problem is in some cases the reading operation with android cursor returns an empty cursor but we know that the data exist because you updated that exact row some seconds ago!


In fact you can't request an online update for some data that not exist. I searched a lot but no result. I thought I might be from reading and writing at the same time but It wasn't.


below is the code that do this work :



protected Biz doInBackground(Void... params) {
Bundle bundle = BizDetailsActivity.this.getIntent().getExtras();
// bizID = bundle.getLong(BIZ);

BizDataSource ds = new BizDataSource(BizDetailsActivity.this);
ds.openWritable();
long ID = bundle.getLong(BIZ);
if (NetworkHelper.IsConnected(BizDetailsActivity.this)) {
// HERE we write data if avaiable
getBizOnline(ID, ds);
}
//read data from database
biz = ds.getBiz(ID, data.getCurrentUser());
ds.close();
return biz;
}


Code for writing/updating data :



public long updateBiz(long ID, String title, String description,
String address, String phone, String mobile, String fax,
String owner, long city, String website, double latitude,
double longitude, int addDate, String expireDate, long gallery,
String logo, float rate) {

ContentValues values = new ContentValues();

values.put(columns[1], title);
values.put(columns[3], description);
values.put(columns[4], address);
values.put(columns[5], city);
if (gallery > 0) {
values.put(columns[6], gallery);
}
values.put(columns[7], latitude);
values.put(columns[8], longitude);
values.put(columns[9], phone);
values.put(columns[10], mobile);
values.put(columns[11], fax);
values.put(columns[12], website);
values.put(columns[13], owner);
values.put(columns[14], logo);
values.put(columns[15], addDate);
values.put(columns[16], expireDate);
values.put(columns[19], rate);

long result;
try {
result = database.updateWithOnConflict("Bizes", values, "ID = ?",
new String[] { ID + "" },SQLiteDatabase.CONFLICT_FAIL);
} catch (Exception e) {
Log.d("UPDATE_BIZ", e.getMessage());
result = -1;
}
return result;
}


Code for getting data :



public Biz getBiz(long id, long UserId) {
Gallery gallery = null;
City city = null;
BizCategory category = null;
Cursor c = database.query("Bizes", columns, "ID=?", new String[] { id + "" }, null, null, null);
if (c.moveToFirst() == false) {
// here we got empty cursor !!!!
c.close();
return null;
} else {
....
}
}

android.database.sqlite.SQLiteException: no such column: locationlocation_setting (code 1):


02-28 14:35:52.946 1923-1937/com.example.android.sunshine.app E/AndroidRuntime﹕ FATAL EXCEPTION: ModernAsyncTask #1
Process: com.example.android.sunshine.app, PID: 1923
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.support.v4.content.ModernAsyncTask$3.done(ModernAsyncTask.java:137)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: android.database.sqlite.SQLiteException: no such column: locationlocation_setting (code 1): , while compiling: SELECT weather._id, date, short_desc, max, min, location_setting, weather_id, coord_lat, coord_long FROM weather INNER JOIN location ON weatherlocation_id = location._id WHERE (locationlocation_setting = ? AND date >= ? ) ORDER BY date ASC
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:400)
at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:294)
at com.example.android.sunshine.app.data.WeatherProvider.getWeatherByLocationSetting(WeatherProvider.java:66)
at com.example.android.sunshine.app.data.WeatherProvider.query(WeatherProvider.java:126)
at android.content.ContentProvider.query(ContentProvider.java:857)
at android.content.ContentProvider$Transport.query(ContentProvider.java:200)
at android.content.ContentResolver.query(ContentResolver.java:461)
at android.content.ContentResolver.query(ContentResolver.java:404)
at android.support.v4.content.CursorLoader.loadInBackground(CursorLoader.java:49)
at android.support.v4.content.CursorLoader.loadInBackground(CursorLoader.java:35)
at android.support.v4.content.AsyncTaskLoader.onLoadInBackground(AsyncTaskLoader.java:242)
at android.support.v4.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:51)
at android.support.v4.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:40)
at android.support.v4.content.ModernAsyncTask$2.call(ModernAsyncTask.java:123)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)

Replace an sqlite databse from another C#

In my project I have one SqlCypher Database say A.db and which is used by the app.


At some point I will get latest data which I have in another SqlCypher db, say B.db.


Both databases has identical structure (tables).


Now how can I replace the entire data of Database A from Database B. All the table name and structure are same.


How can I achieve this using any Query?, or Should I go for a StreamReader..


It is a Xamarin Project which uses ORMLite.


SQLite AutoIncrement always returns 0

I have a android app who use SQLite and sqlite.net pcl library (with xamarin and c#)


This is my table definition (just the id part)



[Table("ConsumoMensual")]
public class ConsumoMensual
{
[PrimaryKey, AutoIncrement]
public int? id {get;set;} //also try with int and int?
...


I insert data with this code, and returns 1



public void RegistroLlamada(MOD.phoneScrapView v){
ConsumoMensual c = findRegistroMes (v.FechaLlamada);
bool update = true;
if (c == null) {
update = false;//this is because always get 0
c = new ConsumoMensual ();
}

c.annio = v.FechaLlamada.Year;
c.mes = v.FechaLlamada.Month;
c.minutosMismaCompania += minutosMismaCompania (v);
c.minutosNumerosGratuitos+= ValidoGratuitos (v);
c.minutosOtraCompania+= minutosOtraCompania (v);
lock (locker) {
if (update)
database.Update (c);//crash here (ID is null)
else
database.Insert (c);//returns 1 here
}
}


but when i read it, i got zero in the id



public ConsumoMensual findRegistroMes(DateTime fecha)
{
lock (locker) {
return (from i in database.Table<ConsumoMensual> ()
where i.mes == fecha.Month && i.annio == fecha.Year
select i).FirstOrDefault ();
}
}


this is the interface code



namespace PlanControlDAL
{
public interface ISQLite
{
SQLiteConnection GetConnection();
}
}


and this is the class who implements the interface public class SQLite_Android : ISQLite { public SQLite_Android () { }



#region ISQLite implementation
public SQLite.Net.SQLiteConnection GetConnection ()
{
var sqliteFilename = "planControl.db3";
string documentsPath = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal); // Documents folder
var path = Path.Combine(documentsPath, sqliteFilename);

// This is where we copy in the prepopulated database
Console.WriteLine (path);
if (!File.Exists(path))
{
/*var s = Forms.Context.Resources.OpenRawResource(Resource.Raw.totalSQLite); // RESOURCE NAME ###*/

// create a write stream

/*using (StreamReader sr = new StreamReader (Resource.Raw.totalSQLite)) {

FileStream writeStream = new FileStream (path, FileMode.OpenOrCreate, FileAccess.Write);
// write to the stream
ReadWriteStream (sr, writeStream);
}*/
}

var plat = new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid();
var conn = new SQLite.Net.SQLiteConnection(plat, path);

// Return the database connection
return conn;
}
#endregion

/// <summary>
/// helper method to get the database out of /raw/ and into the user filesystem
/// </summary>
void ReadWriteStream(Stream readStream, Stream writeStream)
{
int Length = 256;
Byte[] buffer = new Byte[Length];
int bytesRead = readStream.Read(buffer, 0, Length);
// write the required bytes
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = readStream.Read(buffer, 0, Length);
}
readStream.Close();
writeStream.Close();
}
}


I'm follow the demos to the letter and i keep getting zero (or null depends if int or int?) what's doing wrong?


Ps. I use the 2.5.1 nuget version of sqlite.net pcl & 2.5.1 sqlite.net.plataform.xamarin.android


vendredi 27 février 2015

Android: can't insert data in the database

I know there are other questions with similar titles, but non of them solved my issue. I am trying to develop a notes app, I want to show the notes titles in a listview, and when the user clicks on one item the details of the note will appear where he/she can edit it. I am using loader and simplecursoradapter to do that, but after editing a note and clicking save, nothing appears in the list. Here is the code of the main activity where I use the loader inside the fragment,



public class NotesList extends ActionBarActivity {

//go back to home.
@Override
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}

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


setContentView(R.layout.main_notes_activity); //inflates main_notes_activity as our activity will contain only one
//child which is the fragment.
if (savedInstanceState == null) {
/* if no bundle is found, use fragment manager to make operations on fragments, note that
the fragment we are creating is a dynamic fragment since it's not defined in the xml file. That's why we are using the fragment
manager with begin transaction method since these are used for dynamic fragments, then we add a new fragment using add
method after that we commit the change.*/
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new NotesFragment())
.commit();

}
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.list_menu, menu);
return true; /*true= yes we do have an option menu.*/

}

@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) {//open the settings activity to enable the user to change the settings.
//open settings activity via intent here.
startActivity(new Intent (this, Settings.class));
return true;
}

if (id==R.id.insert){ //open the details activity where the user can enter their notes and save it.
Intent intent = new Intent (this,NotesDetails.class );
startActivity(intent);
return true; //this line is necessary
}//end if

return super.onOptionsItemSelected(item);
}


/**
* A placeholder fragment containing a simple view.
*/
public static class NotesFragment extends Fragment implements LoaderManager.LoaderCallbacks <Cursor> {
private String [] from = {NotesTable.COLUMN_SUMMARY}; //we only need to biew the name of the note the main list.
private int [] to = {R.id.label}; //we will mao the summary col returned from the loadercursor to the label text view.
SimpleCursorAdapter mSimpleCursorAdapter;
private static final int LOADER_ID=0;//give our loader an id of 0.

/*DONT FORGET LOADER MANAGER*/
//maybe error is here.


@Override
public void onActivityCreated (Bundle savedInstances)
{
super.onActivityCreated(savedInstances);

mSimpleCursorAdapter=new SimpleCursorAdapter(getActivity(),R.layout.notes_row,null, from, to,0);
getLoaderManager().initLoader(LOADER_ID, null, this); //once this is done onCreateLoader will be called.
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_todo_list, container, false);

ListView listView = (ListView) rootView.findViewById(R.id.notes_list); //findViewById must be called using the rootView because we are inside a fragment.
listView.setAdapter(mSimpleCursorAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Cursor cursor = mSimpleCursorAdapter.getCursor();
if (cursor != null && cursor.moveToPosition(position)) {
String category= cursor.getString(1);
String summary= cursor.getString(2);
String description=cursor.getString(3);
String [] retrievedData= {category, summary, description};
Intent intent = new Intent (getActivity(),NotesDetails.class) ;
intent.putExtra(Intent.EXTRA_TEXT, retrievedData);
startActivity(intent);
}
}
});

return rootView;
}

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
//put the query by which you will be able to observe data here.
String [] projection ={NotesTable._ID,NotesTable.COLUMN_CATEGORY,NotesTable.COLUMN_SUMMARY, NotesTable.COLUMN_DESCRIPTION};
CursorLoader cursorLoader= new CursorLoader(getActivity(),NotesTable.NOTES_URI,projection,null,null,null);

return cursorLoader;
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mSimpleCursorAdapter.swapCursor(data);
}

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

mSimpleCursorAdapter.swapCursor(null);
}


}


}


Here is the detailed activity where the user clicks on save:



public class NotesDetails extends ActionBarActivity {



@Override
protected void onCreate(Bundle savedInstanceState) {
final ContentResolver resolver = getApplicationContext().getContentResolver();
super.onCreate(savedInstanceState);
setContentView(R.layout.notes_edit);

Button saveButton = (Button) findViewById(R.id.todo_edit_button);
final EditText noteSummary = (EditText) findViewById(R.id.todo_edit_summary);
final EditText noteDescription = (EditText) findViewById(R.id.todo_edit_description);
final Spinner noteCategory= (Spinner) findViewById(R.id.category);

if (getIntent().getStringArrayExtra(Intent.EXTRA_TEXT)!=null){
String [] receivedData=getIntent().getStringArrayExtra(Intent.EXTRA_TEXT);

if (receivedData [0].equalsIgnoreCase("important")){
noteCategory.setSelection(0);}//end if
else {
noteCategory.setSelection(1);} //end else
noteSummary.setText(receivedData[1]);
noteDescription.setText(receivedData[2]);

}//end if (feasible only if the received intent contains an array of string, which happens if the user clicks onm one of the items in the simplecursoradapter view)


saveButton.setOnClickListener(new View.OnClickListener() {

String summary= null;
String description= null;
String category= null;

@Override
public void onClick(View view) { //this will happen every time you click the button.
summary= noteSummary.getText().toString();
description= noteDescription.getText().toString();
category = noteCategory.getSelectedItem().toString();
Toast toast ;
if (summary.isEmpty()) {
toast = Toast.makeText(NotesDetails.this, "Summary cannot be empty", Toast.LENGTH_SHORT);
toast.show();
}
else {
ContentValues values = new ContentValues();

values.put(NotesTable.COLUMN_CATEGORY, category);
values.put(NotesTable.COLUMN_SUMMARY, summary);
values.put(NotesTable.COLUMN_DESCRIPTION, description);

//start inserting into the db via provider.
Uri uri =resolver.insert(NotesTable.NOTES_URI, values);
Intent intent = new Intent(NotesDetails.this, NotesList.class);
startActivity(intent);
}
}//end onClick

}); //end onClickListener

}//ok done.

public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.list_menu, menu);
return false; /*true= yes we do have an option menu.*/
}

@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) {
//open settings activity via intent here.
startActivity(new Intent(this, Settings.class));
return true;
}

return super.onOptionsItemSelected(item);
}}


Provider code:



public class NotesProvider extends ContentProvider{

// database
private static TodoDatabaseHelper mdatabaseHelper; //used to retrieve an obj representation of the database.


// used for the UriMacher
private static final int NOTES = 10; //in case an entire table were requested to be returned.
private static final int NOTES_ID = 20; //in case a specific item with a specific uri needs to be returned.


//Let's build the UriMatcher:
static UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {

sUriMatcher.addURI(NotesContract.CONTENT_AUTHORITY, NotesContract.NOTES_PATH, NOTES); //match an entire table.
sUriMatcher.addURI(NotesContract.CONTENT_AUTHORITY, NotesContract.NOTES_PATH +"/#", NOTES_ID);

}//end matching static block.


@Override
public boolean onCreate() {
//get a dbHelper obj,
mdatabaseHelper = new TodoDatabaseHelper(getContext()); //why? Because this will help us retrieve a readable/writable db on which we can make operations like CRUD.
return true; //we were successfully able to create an obj representation of the DB.
}

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
//here we should use the uri matcher to know how we can conduct the query.
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(NotesContract.NotesTable.TABLE_NAME); //could be used for joins also.

verifyColumns (projection); //verify if the columns are valid.
int match= sUriMatcher.match(uri); //save the int associated with this uri in a var to be able to use it in the switch.
Cursor cursor=null; //initialize cursor, it will be used to return the result of the query.
SQLiteDatabase db= mdatabaseHelper.getReadableDatabase(); //we need this because we use an SQLiteQueryBuilder.
switch (match) //start the switch
{
case NOTES:
// call method query and send the params.
cursor= queryBuilder.query(db, projection, selection,
selectionArgs, null, null, sortOrder);
break; //don't go to next case.
case NOTES_ID:
//first initialize the where clause in the queyBuilder:
queryBuilder.appendWhere(NotesContract.NotesTable._ID + "=" + ContentUris.parseId(uri));
//invoke the query method:
cursor= queryBuilder.query(db, projection, selection,
selectionArgs, null, null, sortOrder);
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);

}//end switch
/*the queries above could be built using mSQLiteHelper.getReadableDatabase.query(..)*/
cursor.setNotificationUri(getContext().getContentResolver(), uri); //very important and required, to update the ui when the data change.
return cursor; //return the query result.
}//end query.

@Override
public String getType(Uri uri) {

return null;
}

@Override
public Uri insert(Uri uri, ContentValues contentValues) {
int match = sUriMatcher.match(uri);
SQLiteDatabase db = mdatabaseHelper.getWritableDatabase();
long id = 0;
switch (match) {
case NOTES:
id = db.insert(NotesContract.NotesTable.TABLE_NAME, null, contentValues);

break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null); //notify observers about any update.
return Uri.parse(NotesContract.NOTES_PATH + "/" + id);

}

@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int match = sUriMatcher.match(uri);
SQLiteDatabase db = mdatabaseHelper.getWritableDatabase();
int rowsDeleted = 0;

switch (match) {
case NOTES:
rowsDeleted = db.delete(NotesContract.NotesTable.TABLE_NAME, selection, selectionArgs);
break;
case NOTES_ID:
if (selection.isEmpty()){
String whereClause= NotesContract.NotesTable._ID + "=" + ContentUris.parseId(uri);
rowsDeleted = db.delete(NotesContract.NotesTable.TABLE_NAME, whereClause, null);}

else{
rowsDeleted = db.delete(NotesContract.NotesTable.TABLE_NAME,
NotesContract.NotesTable._ID + "=" + ContentUris.parseId(uri)
+ " and " + selection,
selectionArgs);
}//end else
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}//end switch
getContext().getContentResolver().notifyChange(uri, null); //if any delete happens notify the observers.
return rowsDeleted;
}//end delete


@Override
public int update(Uri uri, ContentValues contentValues, String selection, String[] selectionArgs) {
SQLiteDatabase db = mdatabaseHelper.getWritableDatabase(); //return a writable obj from the db.
int rowsUpdated = 0;
int match= sUriMatcher.match(uri);
switch (match) {
case NOTES:
rowsUpdated = db.update(NotesContract.NotesTable.TABLE_NAME,
contentValues,
selection,
selectionArgs);
break;
case NOTES_ID:
long id = ContentUris.parseId(uri);
if (TextUtils.isEmpty(selection)) {
rowsUpdated = db.update(NotesContract.NotesTable.TABLE_NAME,
contentValues,
NotesContract.NotesTable._ID + "=" + id,
null);
} else {
rowsUpdated = db.update(NotesContract.NotesTable.TABLE_NAME,
contentValues,
NotesContract.NotesTable._ID + "=" + id
+ " and "
+ selection,
selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsUpdated;
}

private void verifyColumns (String [] cols) {
//lets get the columns in the Db and compare.
String[] existed = {NotesContract.NotesTable._ID, NotesContract.NotesTable.COLUMN_CATEGORY,
NotesContract.NotesTable.COLUMN_DESCRIPTION,
NotesContract.NotesTable.COLUMN_SUMMARY};
if (cols != null) {
ArrayList<String> existedCols = new ArrayList<String>(Arrays.asList(existed)); //this is how we convert an array to an arraylist.
ArrayList<String> requestedCols = new ArrayList<String>(Arrays.asList(cols));
// check if all columns which are requested are available
if (!existedCols.containsAll(requestedCols)) {
throw new IllegalArgumentException("Some columns don't exist in the database");
}//end if.
}//end outer if.
}//end verification.

public static Cursor searchDescription (String key)
{
String desc []= {"%"+key +"%"};
SQLiteDatabase db = mdatabaseHelper.getReadableDatabase();
Cursor rtCursor= db.rawQuery("select * from " + NotesContract.NotesTable.TABLE_NAME+ " where " +
NotesContract.NotesTable.COLUMN_DESCRIPTION + " like ?", desc);

return rtCursor;
}//end searchDescription

}//end Provider.


Contract code:



public class NotesContract {


public static final String CONTENT_AUTHORITY="com.project.android.notes.data.NotesProvider"; /*this is
the path in which the content provider resides. Remember we are making an agreement on the underlying data
scheme, and the ways by which we can access it*/

//Now, building the uri from the authority string.

public static final Uri BASE_CONTENT_URI= Uri.parse("content://" + CONTENT_AUTHORITY);/*DON'T FORGET "CONTENT://" IT DEFINED THE SCHEME*/

//Next, we define one string that reflects the table name, in order to add it to a path uri later.
public static final String NOTES_PATH= "notes";

public static final class NotesTable implements BaseColumns {

//first we build the uri of this table using the NOTES_PATH string defined earlier.
public static Uri NOTES_URI = BASE_CONTENT_URI.buildUpon().appendPath(NOTES_PATH).build(); //this can be used later as a base on which
//we can build upon another parts of the uri.

//Now, define the columns:
// no need to define a specific ID column, as any class that implements BaseColumns have _ID automatically.
public static final String TABLE_NAME = "notes";
public static final String COLUMN_CATEGORY = "category";
public static final String COLUMN_SUMMARY = "summary";
public static final String COLUMN_DESCRIPTION = "description";


public static Uri buildUriWithId (long id)
{
Uri uriWithId = ContentUris.withAppendedId(NOTES_URI, id);
//withAppendedId takes a table uri and a row id, then creates a full uri from them.
return uriWithId;
}//end buildUriWithId
//Let's define the mime types that can be returned from the table.
//These data can be either a set of items or a single item.
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/" + CONTENT_AUTHORITY + "/" + NOTES_PATH; //this is a set of items.
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/" + CONTENT_AUTHORITY + "/" + NOTES_PATH; //this is a single item.

}//end inner class.
}//end Contract class.


DB Helper code:



public class TodoDatabaseHelper extends SQLiteOpenHelper {

//fields needed:
public static final String DB_NAME="notes.db";
public static final int DB_VERSION= 1;
public final String LOG_TAG= TodoDatabaseHelper.class.getSimpleName(); //used for log statements in the onUpgrade.

//the create query:
private static final String DATABASE_CREATE = "create table "
+ NotesTable.TABLE_NAME
+ "("
+ NotesTable._ID + " integer primary key autoincrement, " //again as I said in the contract, no need to define a specific ID column.
+ NotesTable.COLUMN_CATEGORY + " text not null, "
+ NotesTable.COLUMN_SUMMARY + " text not null,"
+ NotesTable.COLUMN_DESCRIPTION
+ " text not null"
+ ");";
//end create query

public TodoDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION); //if DB_VERSION is not static this won't work.

}//end constructor.


@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
//first we want to have SQLiteDb object to be able to create a database using the create command.
sqLiteDatabase.execSQL(DATABASE_CREATE);
}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
Log.w(LOG_TAG, "Upgrading database from version "
+ oldVersion + " to " + newVersion
+ ", which will destroy all old data"); /*the class that contains the table is NotesTable, the name
assigned to the table is TABLE_NAME*/
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + NotesTable.TABLE_NAME);
onCreate(sqLiteDatabase); //after clearing the table fill it again by calling onCreate.

}
}


When I edit a note and click on the save button I get this log:



02-28 10:00:06.827: E/SQLiteLog(27827): (257) Open fd: 65, file: /data/data/com.project.android.notes/databases/notes.db-journal
02-28 10:00:06.827: E/SQLiteLog(27827): (257) Close fd: 65
02-28 10:00:06.829: E/SQLiteLog(27827): (257) Open fd: 65, file: /data/data/com.project.android.notes/databases/notes.db-journal
02-28 10:00:06.859: E/SQLiteLog(27827): (257) Close fd: 65
02-28 10:00:06.958: E/SQLiteLog(27827): (257) Open fd: 69, file: /data/data/com.project.android.notes/databases/notes.db-journal
02-28 10:00:06.958: E/SQLiteLog(27827): (257) Close fd: 69
02-28 10:00:07.564: E/HwSystemManager(1208): :ACTION_BATTERY_CHANGED pluged =2
02-28 10:00:10.107: E/(180): AudioCloseDumpPCMFile file== NULL
02-28 10:00:10.107: E/(180): AudioCloseDumpPCMFile file== NULL
02-28 10:00:11.614: E/MCA(28234): Here call up the service!
02-28 10:00:11.614: E/MCA(28234): LT passed!


Please help me I've been spending too long time trying to solve the problem, but nothing worked.


Any help will be appreciated.


Thanks


How to update multiple rows (not ever row) with same value in SQLite database

I have a strange problem with a scenario related to SQLite update, hopefully will get some help here.


my table tbl1 looks like below (sqlfiddle)



id col1 col2 col3
1 0 1 0
2 1 0 0
3 0 0 1
4 1 1 1
5 0 0 0


My requirement is that I get some positive number from user for each column and I need to update the rows of a particular column if they contain zero and finally I should count the number of rows updated and difference between the user input and updated count I should add it to the last row


Let me explain with example:

Say user inputs 10 for col1. col1 has 3 rows containing zero so I will update them to 1 and finally the diff i.e. (10 - 3 = 7) I should update in the last row


I hope I did not confuse, after update I expect the table to look like



id col1 col2 col3
1 1 1 0
2 1 0 0
3 1 0 1
4 1 1 1
5 8 0 0


Sql query update tbl1 set col1=1 where col1=0 and id in (select id from tbl1 where col1=0 limit 10)


The above query updates all 0s to 1 but how do I add the remaining to last row?