mercredi 31 décembre 2014

Need to clear the list of contacts in my android app. Please help)

I'm writting my own android app for storing contacts (name, phone number, email). I've got a database, two activity, one for displaying the list of contacts and the other for filling a form with a contact data. The probleme is that I don't know how to delete all conctacts from the list and also how to delete a single contact from the list. I will show you my code.



package com.example.contactsapp;

public class Contact {



//private variables
int _id;
String _name;
String _lastName;
String _phone_number;
String _email;

// Empty constructor
public Contact(){

}
// constructor
public Contact(int id, String name, String lastName, String _phone_number, String email){
this._id = id;
this._name = name;
this._lastName = lastName;
this._phone_number = _phone_number;
this._email = email;
}

// constructor
public Contact(String name, String lastName, String _phone_number, String email){
this._name = name;
this._lastName = lastName;
this._phone_number = _phone_number;
this._email = email;
}
// getting ID
public int getID(){
return this._id;
}

// setting id
public void setID(int id){
this._id = id;
}

// getting name
public String getName(){
return this._name;
}

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

// getting lastName
public String getLastName(){
return this._lastName;
}

// setting lastName
public void setLastName(String lastName){
this._lastName = lastName;
}

// getting phone number
public String getPhoneNumber(){
return this._phone_number;
}

// setting phone number
public void setPhoneNumber(String phone_number){
this._phone_number = phone_number;
}

// getting lastName
public String getEmail(){
return this._email;
}

// setting lastName
public void setEmail(String email){
this._email = email;
}
}

package com.example.contactsapp;

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

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

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 = "contactsManager";

// Contacts table name
private static final String TABLE_CONTACTS = "contacts";

// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_LAST_NAME = "last_name";
private static final String KEY_PH_NO = "phone_number";
private static final String KEY_EMAIL = "email";

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

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + KEY_LAST_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT," + KEY_EMAIL + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_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_CONTACTS);

// Create tables again
onCreate(db);
}

/**
* All CRUD(Create, Read, Update, Delete) Operations
*/

// Adding new contact
public void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_LAST_NAME, contact.getLastName()); // Contact Last Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
values.put(KEY_EMAIL, contact.getEmail()); // Contact Email

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

// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();

Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_LAST_NAME, KEY_PH_NO, KEY_EMAIL }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();

Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4));
// return contact
return contact;
}

// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;

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

// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setLastName(cursor.getString(2));
contact.setPhoneNumber(cursor.getString(3));
contact.setEmail(cursor.getString(4));

String name = cursor.getString(1) +"\n"+ cursor.getString(2) +"\n"+ cursor.getString(3) +"\n"+ cursor.getString(4);
MainActivity.ArrayofName.add(name);
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}

// return contact list
return contactList;
}

// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_LAST_NAME, contact.getLastName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
values.put(KEY_EMAIL, contact.getEmail());

// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}

//public void clearDataBase(SQLiteDatabase db) {
//db.execSQL("DROP TABLE " + TABLE_CONTACTS);
//onCreate(db);
//}

// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}


// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();

// return count
return cursor.getCount();
}

}

public class MainActivity extends Activity {

DatabaseHandler db = new DatabaseHandler(this);

private ListView listView;
public static ArrayList<String> ArrayofName = new ArrayList<String>();

//For menu
private Menu m = null;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
//R.menu.menu est l'id de notre menu
inflater.inflate(R.menu.menu, menu);
m = menu;
return true;
}


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

db.getAllContacts();

listView = (ListView) findViewById(R.id.listView1);

registerForContextMenu(listView);
listView.setOnCreateContextMenuListener(this);

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

listView.setAdapter(adapter);

listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(getApplicationContext(),
((TextView) v).getText(), Toast.LENGTH_SHORT).show();
//db.deleteContact();
}
});
}

public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
}

//For menu
@Override
public boolean onOptionsItemSelected (MenuItem item)
{

final Context context = this;

switch(item.getItemId())
{
case R.id.item1:
//Dans le Menu "m", on active tous les items dans le groupe d'identifiant "R.id.group2"
//m.setGroupEnabled(R.id.group2, true);
//return true;
Intent intent = new Intent(context, Form.class);
startActivity(intent);
//break;
//case R.id.item2:
//db.clearDataBase(db);
//break;
}
return super.onOptionsItemSelected(item);
}
}


In the MainActivity, when I call the menu, there are two options. The second one is supposed to delete all conctacts from the list. My friends, I don't how to implement it, please help


Thanks a lot in advance, Karen.


Get a Value from One Cell in Sqlite to Livecode

I am using sqlite as my database. It is connected to the livecode project.


The Contacts table has the following data (address and contact number are omitted for security)



ID Name Address Contact No.
1 John ...Philippines 0999999999
2 Kim ...Philippines 0999999999


When I executed this command...



SELECT Name from Contacts ORDER BY ID DESC LIMIT 1


It will return



Kim


In Livecode, I want to store that value to the variable and display it as a Message Box.


How to do that?


android database: how to match credentials from sqlite database

I've a user info table with 8 columns stored in sqlite database. I'm having problem in comparing the user entered credentials with the one that stored in database. My app says that user name and password does not match, although i'm entering the correct values.


method in main activity



@Override
public void onClick(View v) {
// TODO Auto-generated method stub
ffCode = ed_login.getText().toString();
password = ed_password.getText().toString();
// check if any of edit text is empty
if(ffCode.equals(""))
{
Toast.makeText(getApplicationContext(), "Please enter your FF code", Toast.LENGTH_LONG).show();
return;
}
else if (password.equals(""))
{
Toast.makeText(getApplicationContext(), "Please enter your password", Toast.LENGTH_LONG).show();
return;
}
Log.e("calling database", "yes");
Db_getUserDetail myDb= new Db_getUserDetail(MainActivity.this);

//this is the method to query
String storedffcode = myDb.getCodeAndPassword(ffCode,password);
String storedpassword = myDb.getCodeAndPassword(ffCode,password);
myDb.close();

if(ffCode.equals (storedffcode) && password.equals (storedpassword))
{
Toast.makeText(getApplicationContext(), "Congrats: Login Successfull", Toast.LENGTH_LONG).show();

}
else
{
Toast.makeText(getApplicationContext(), "User Name or Password does not match", Toast.LENGTH_LONG).show();
}
}
});


method of database helper class



public String getCodeAndPassword(String ffCode,String password)
{
Log.e("retrieving ff code", "yes");
SQLiteDatabase db = getWritableDatabase();
// Cursor cursor = db.query("user_detail", null, " ff_code=?",new String[]{ffCode,password}, null, null, null);
Cursor cursor = db.rawQuery("SELECT ff_code, user_pwd FROM " + "user_detail" + " WHERE ff_code = '"+ ffCode + "' AND user_pwd ='"+ password+ "'", null);
if(cursor.getCount()<1)
{
cursor.close();
return "Not Exist";
}
Log.e("found ff code", "yes");
cursor.moveToFirst();
String ffcode= cursor.getString(cursor.getColumnIndex("ff_code"));
return ffcode;
}

SQLIte ReadOnly Exception after Application has been published to Windows Phone store

I am struggling with a SQLIte Readonly exception that occurs only after I published application to WP Store.


In Development all works fine, I even checked with my real device on release ARM mode.


But after application has been certified and published and after installing app from Store, I got ReadOnly exception when I try to update the SQLite Table



[Type]:[SQLiteException]
[ExceptionMessage]:[ReadOnly]
[StackTrace]:[
at Helpers.DBHelper.Update[T](T obj, String statement)


I have used nuget libraries sqlite-net, sqlite-net-wp8 and "SQLite for Windows Phone" Visual Studio Extension


DBHelper :



public class DBHelper : IDisposable
{
private String _dbName;
private SQLiteConnection db = null;
public DBHelper( String dbName)
{
IsolatedStorageFile store =IsolatedStorageFile.GetUserStoreForApplication();
if (!store.FileExists(dbName))
{
CopyFromContentToStorage(dbName);
}
_dbName = dbName;
}
~DBHelper()
{
Dispose(false);
}
private void Open()
{
if (db == null)
{
db = new SQLiteConnection(_dbName,SQLiteOpenFlags.ReadWrite);

}
}

private void Close()
{
if (db != null)
{
db.Close();
db.Dispose();
db = null;
}
}
//Insert operation
public int Insert<T>(T obj, string statement) where T : new()
{
try
{
Open();
SQLiteCommand cmd = db.CreateCommand(statement);

int rec = cmd.ExecuteNonQuery();
Close();
return rec;

}
catch (SQLiteException ex)
{
System.Diagnostics.Debug.WriteLine("Insert failed: " + ex.Message);
throw ex;
}
}

//Update operation
public int Update<T>(T obj, string statement) where T : new()
{
try
{
Open();
SQLiteCommand cmd = db.CreateCommand(statement);

int rec = cmd.ExecuteNonQuery();
Close();
return rec;

}
catch (SQLiteException ex)
{
System.Diagnostics.Debug.WriteLine("Update failed: " + ex.Message);
throw ex;
}
}
//Insert operation
public void Delete<T>(string statement) where T : new()
{
try
{
Open();
SQLiteCommand cmd = db.CreateCommand(statement);
cmd.ExecuteNonQuery();
Close();
}
catch (SQLiteException ex)
{
System.Diagnostics.Debug.WriteLine("Deletion failed: " + ex.Message);
throw ex;
}
}

//Query operation
//new约束指定泛型类声明中的任何类型参数都必须具有公共的无参数构造函数
public List<T> SelectList<T>(String statement) where T : new()
{
Open();
SQLiteCommand cmd = db.CreateCommand(statement);
var lst = cmd.ExecuteQuery<T>();
Close();
return lst.ToList<T>();
}
public ObservableCollection<T> SelectObservableCollection<T>(String statement)
where T : new()
{
return new ObservableCollection<T>(SelectList<T>(statement));
}

private void CopyFromContentToStorage(String dbName)
{
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();

// Create a stream for the file in the installation folder.
using (Stream input = Application.GetResourceStream(new Uri(dbName, UriKind.Relative)).Stream)
{
// Create a stream for the new file in the local folder.
using (IsolatedStorageFileStream output = iso.CreateFile(dbName))
{
// Initialize the buffer.
byte[] readBuffer = new byte[4096];
int bytesRead = -1;

// Copy the file from the installation folder to the local folder.
while ((bytesRead = input.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
output.Write(readBuffer, 0, bytesRead);
}
}
}
}
private static void CopyStream(System.IO.Stream input,
IsolatedStorageFileStream output)
{
byte[] buffer = new byte[32768];
long TempPos = input.Position;
int readCount;
do
{
readCount = input.Read(buffer, 0, buffer.Length);
if (readCount > 0)
{
output.Write(buffer, 0, readCount);
}
} while (readCount > 0);
input.Position = TempPos;
}
private bool disposed = false;

protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{

Close();
}

disposed = true;
}
}

public void Dispose() // Implement IDisposable
{
Dispose(true);
GC.SuppressFinalize(this);
}

}

Querying a has_and_belongs_to_many association in Ruby

OK. What I am trying to achieve is based on generating a list of related articles based on a specific article and I want to get these related articles based on the categories that are associated with the article. I have a simple habtm relationship between these two models: article and category (join table is named articles_categories). I want to create a related articles query based on articles that have the same category_ids as one article. For example, article #1 is associated with category #1 and category #2. I want to write a query that grabs the category ids of article #1, then queries the article model for all articles that are associated with those same categories, category #1 and category #2. I have tried everything under the sun and can't seem to figure this out. I have tried .join statements of various kinds and nothing seems to work. I tried to break it down into two parts below:


I can grab all of the category ids of the specific article that I want to reference like this: article_cat_ids = @article.category_ids


The second part would be the article filter based on these category ids but I can't figure this part out.


So my question is, how do I get an array of articles that are associated with the category ids in the array article_cat_ids. And as a bonus kicker, I would love to exclude the specific article that I originally reference to create the article_cat_ids so that the list of articles does not include the article that I am trying to get related articles for.


Any help would be appreciated.


How To Use SQLite COUNT in Android to return number of rows

I want to write a query that add up all the rows that have the string value of "left" in column named DIRECTION. Next I want to return this sum.


In my code snip-it below assume data and data base are established.


Here is the prototype:



public int getSumLeft() {
String selectQuery = "SELECT COUNT( "+TableData.TableInfo.DIRECTION+" ) WHERE "+TableData.TableInfo.DIRECTION+" = left";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToFirst();
int sum = cursor.getInt(0);
cursor.close();
return sum;
}


I've tried several queries and this one seems to be the closes to what I need. I think the problem is with statement 'int sum = cursor.getInt(0);'


I think the zero parameter is overriding the results. When I remove the zero the code breaks. getInt is an SQLite function that is used to access data in the database. I did not create that function. But I must use it or and another function like it.


Also, do I need to put a while loop around the query to move the cursor for a COUNT query? Doesn't the Database count for you, therefor no need for iteration?


Is there another way of counting the rows where the string value is 'left' and the sum can be returned?


Full code here:


Database: http://ift.tt/1xABS7u


Implementation (see the button in onCreate function ): http://ift.tt/1rBHtuT


Thanks for looking into this.


SQLite query returning old results

I have a sqlite database (.sqdb3) being created and updated by another application (of which I don't have any control over the code). I can run SELECT statements successfully against the db file using the standalone sqlite3.exe download. However, when I run the 3rd party application which updates the db content, re-running the SELECT statement returns the previous result set.


More specifically, when I first began accessing the .sqdb3 file, there were 9 records. I ran the 3rd party application which should have at least added 2 more records. When I run the sqlite3.exe SELECT * FROM table, it returns the original 9 records. When I open the .sqdb3 file in Scite (text editor) I can see references to the 2 new records and the timestamp of the file has been updated so I know the new data exists. When I make a copy of the .sqdb3 and run the sqlite3.exe SELECT * FROM table, I can see the anticipated 11 records. But no matter what, I only get the original 9 records from the primary file.


I've looked around to see if there's any kind of cache that needs to be cleared but there are no other files besides the .sqdb3 and the standalone sqlite3.exe and I'm not seeing any "clear cache" type commands via .help. I've tried closing and reopening the command prompt and reopening access to the primary .sqdb3, but so far the only way I can see the new records via sqlite3.exe use, is if I make a file copy of the primary db file and query against the copy.


Dates are coming back invalid using openNTF jdbc driver for Domino

I'm creating reports utilizing openNTF's domSQL/JDBC driver for Domino (powered by SQLite). It enables us to use Domino's databases as SQL database views. One of the features of this driver is that it converts all the Domino db date fields to text fields. Somehow, in doing this, it converts the date 'xxxx-03-01 xx:xx:xx' to 'xxxx-02-29 xx:xx:xx'. Not only is the date incorrect, but 2/29 is a leapyear date being assigned to non-leapyears. This is causing an additional error when we attempt to store this invalid date into a date field.


More info on DomSQL can be found here: http://ift.tt/1B5qymo$file/DominoJDBCAccess.pdf


Problems with ListView and layout

i'm using android studio and i'm trying to follow this guide: http://ift.tt/1B5j7LV that implements database but i have problems with " R.layout.listactivity_row.

This guide not explain nowhere how and where to insert "listactiviry_row" Can you help me ?


`@Override public View newView(Context ctx, Cursor arg1, ViewGroup arg2) { View v=getLayoutInflater().inflate(R.layout.listactivity_row, null);



return v;
}`


this is main_activiry.xml



<RelativeLayout
android:layout_height="wrap_content"
android:layout_width="400dp"
xmlns:android="http://ift.tt/nIICcg">


<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="@+id/oggetto"
android:hint="Oggetto"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="53dp"
android:layout_marginTop="20dp" />

<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="@+id/testo"
android:hint="testo"
android:layout_below="@+id/oggetto"
android:layout_alignLeft="@+id/oggetto"
android:layout_alignStart="@+id/oggetto"
android:layout_marginRight="53dp" />

<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="@+id/data"
android:hint="data"
android:layout_below="@+id/testo"
android:layout_alignLeft="@+id/testo"
android:layout_alignStart="@+id/testo" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="salva"
android:id="@+id/button"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="150dp"
android:layout_marginLeft="150dp" />

<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_marginTop="200dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:weightSum="1">

<TextView
android:layout_width="100dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="@+id/txt_subject"
android:hint="subject" />

<TextView
android:layout_width="100dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="@+id/txt_date"
android:layout_marginLeft="110dp"
android:layout_marginTop="-16dp"
android:hint="data" />


<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:src="@android:drawable/ic_menu_delete"
android:id="@+id/btn_delete"
android:layout_gravity="right"
android:layout_marginRight="50dp"
android:layout_marginTop="-10dp" />

<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/listView" />
</LinearLayout>

How can I check that a SQL statement executed without error in Ruby?

I'm re-writing some scripts from PHP to Ruby.


In PHP I can put the SQL statement in a variable and execute it and then check the variable to see if it executed without error.


For example if ($query).


Documentation on SQL in Ruby is not as extensive as PHP.


How can I check that a SQL statement executed without error?


Thanks


A lexical database for Arabic

Where can I get a lexical database for Arabic words like http://ift.tt/LwlRbj I mean a list of all Arabic words ??

I searched in Google but I didn't find anything.so what should I do??


Sqlite-net create two tables from the same class

The documentation of the Sqlite-net says you can create a table using the ORM available in the library by using the generics as follow:



await connection.creatTableAsync<myClass>();


This will result in a table in the database named myClass


Now suppose that I need another table for storing the same type (myClass) but in a different table with different name (e.g.myOtherClassTable).


How can this be done, using the Sqlite-net library?


How to read the whatsapp database in non rooted phone?

I would like to create a Android application that can read the whatsapp database and display in my app.. So please provide me exact code or the hint to complete my task..


Strike through TextView item in ListView by checking database status

I am a beginner in Android, I have a ListView which loads data from SQLite database with this code on onCreate:



Cursor cursor = dbAdapter.getAllTasks();
String[] fromFields = new String[] {dbAdapter.dbHelper.KEY_TASK};

int[] toView = new int[] {R.id.task};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.task_items, cursor, fromFields, toView, 0);

ListView myList = (ListView) findViewById(R.id.taskList);
myList.setAdapter(myCursorAdapter);


I have db fields task (text), done (boolean) and date (text).


I can toggle strike through in the TextView on item click of ListView using this code and I can change the db field done value here:



ListView myList = (ListView) findViewById(R.id.taskList);
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

TextView v = (TextView) view.findViewById(R.id.task);

if ((v.getPaintFlags() & Paint.STRIKE_THRU_TEXT_FLAG) > 0){
v.setPaintFlags( v.getPaintFlags() & (~ Paint.STRIKE_THRU_TEXT_FLAG));
} else {
v.setPaintFlags(v.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
// calling update method to change done value in db
}
});


Now how can I strike through all items which is marked as done (done = 1) when loading ListView.


crate new multiple table with different name

How do I create multiple tables, i.e. one named "salesAccounts" and another "PurchaseAccounts" based off of the Account class?


but in sales and purchase i need to create individual user account with new table. can u help me in that i am using Sq-lite and net beans software


/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */


/** * * @author Kedar */ public class roshantrades extends javax.swing.JFrame {



/**
* Creates new form roshantrades
*/
public roshantrades() {
initComponents();
}

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jMenuBar1 = new javax.swing.JMenuBar();
jMenu4 = new javax.swing.JMenu();
jMenu5 = new javax.swing.JMenu();
jPanel1 = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
button_Purchase = new javax.swing.JButton();
button_Purchase5 = new javax.swing.JButton();
button_Purchase4 = new javax.swing.JButton();
button_Purchase3 = new javax.swing.JButton();
button_Purchase2 = new javax.swing.JButton();
jToolBar2 = new javax.swing.JToolBar();
Button_add = new javax.swing.JToggleButton();
jSeparator3 = new javax.swing.JToolBar.Separator();
jPanel2 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
panel_addons = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
table_purchase = new javax.swing.JTable();
jMenuBar2 = new javax.swing.JMenuBar();
jMenu6 = new javax.swing.JMenu();
jMenuItem2 = new javax.swing.JMenuItem();
jSeparator1 = new javax.swing.JPopupMenu.Separator();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem3 = new javax.swing.JMenuItem();
jMenuItem4 = new javax.swing.JMenuItem();
jSeparator2 = new javax.swing.JPopupMenu.Separator();
jMenuItem5 = new javax.swing.JMenuItem();
jMenu7 = new javax.swing.JMenu();
jMenuItem6 = new javax.swing.JMenuItem();
jMenuItem7 = new javax.swing.JMenuItem();
jMenuItem8 = new javax.swing.JMenuItem();
jMenu8 = new javax.swing.JMenu();
jMenuItem9 = new javax.swing.JMenuItem();
jMenuItem10 = new javax.swing.JMenuItem();

jMenu4.setText("File");
jMenuBar1.add(jMenu4);

jMenu5.setText("Edit");
jMenuBar1.add(jMenu5);

setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
jPanel1.setForeground(new java.awt.Color(255, 255, 255));

jPanel4.setBackground(new java.awt.Color(153, 153, 153));
jPanel4.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 2, true));

button_Purchase.setBackground(new java.awt.Color(255, 255, 255));
button_Purchase.setFont(new java.awt.Font("Times New Roman", 2, 18)); // NOI18N
button_Purchase.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Purchase.JPG"))); // NOI18N
button_Purchase.setText("Purchase");
button_Purchase.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true));
button_Purchase.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

button_Purchase5.setBackground(new java.awt.Color(255, 255, 255));
button_Purchase5.setFont(new java.awt.Font("Times New Roman", 2, 18)); // NOI18N
button_Purchase5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/search.JPG"))); // NOI18N
button_Purchase5.setText("Search");
button_Purchase5.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true));
button_Purchase5.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

button_Purchase4.setBackground(new java.awt.Color(255, 255, 255));
button_Purchase4.setFont(new java.awt.Font("Times New Roman", 2, 18)); // NOI18N
button_Purchase4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Other Exp.JPG"))); // NOI18N
button_Purchase4.setText("Other Exp");
button_Purchase4.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true));
button_Purchase4.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

button_Purchase3.setBackground(new java.awt.Color(255, 255, 255));
button_Purchase3.setFont(new java.awt.Font("Times New Roman", 2, 18)); // NOI18N
button_Purchase3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Sales.JPG"))); // NOI18N
button_Purchase3.setText(" Sales");
button_Purchase3.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true));
button_Purchase3.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

button_Purchase2.setBackground(new java.awt.Color(255, 255, 255));
button_Purchase2.setFont(new java.awt.Font("Times New Roman", 2, 18)); // NOI18N
button_Purchase2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Banks.JPG"))); // NOI18N
button_Purchase2.setText("Banks");
button_Purchase2.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true));
button_Purchase2.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(button_Purchase5, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(button_Purchase4, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(button_Purchase3, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(button_Purchase2, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(button_Purchase, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(button_Purchase)
.addGap(18, 18, 18)
.addComponent(button_Purchase3, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(button_Purchase4, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(button_Purchase2, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(button_Purchase5, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(29, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);

jToolBar2.setRollover(true);

Button_add.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N
Button_add.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Add.JPG"))); // NOI18N
Button_add.setText("Add ");
Button_add.setFocusable(false);
Button_add.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
Button_add.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBar2.add(Button_add);
jToolBar2.add(jSeparator3);

jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPanel2.setLayout(new java.awt.CardLayout());

jPanel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPanel3.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

panel_addons.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

javax.swing.GroupLayout panel_addonsLayout = new javax.swing.GroupLayout(panel_addons);
panel_addons.setLayout(panel_addonsLayout);
panel_addonsLayout.setHorizontalGroup(
panel_addonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 1138, Short.MAX_VALUE)
);
panel_addonsLayout.setVerticalGroup(
panel_addonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 118, Short.MAX_VALUE)
);

jPanel3.add(panel_addons, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1140, 120));

table_purchase.setAutoCreateRowSorter(true);
table_purchase.setFont(new java.awt.Font("Times New Roman", 0, 11)); // NOI18N
table_purchase.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
table_purchase.getTableHeader().setReorderingAllowed(false);
jScrollPane1.setViewportView(table_purchase);

jPanel3.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 120, 1140, 520));

jPanel2.add(jPanel3, "card2");

jMenu6.setText("File");

jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem2.setText("New File");
jMenu6.add(jMenuItem2);
jMenu6.add(jSeparator1);

jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem1.setText("Save");
jMenu6.add(jMenuItem1);

jMenuItem3.setText("Print View");
jMenu6.add(jMenuItem3);

jMenuItem4.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem4.setText("Print");
jMenu6.add(jMenuItem4);
jMenu6.add(jSeparator2);

jMenuItem5.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem5.setText("Exit");
jMenu6.add(jMenuItem5);

jMenuBar2.add(jMenu6);

jMenu7.setText("Edit");

jMenuItem6.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK | java.awt.event.InputEvent.CTRL_MASK));
jMenuItem6.setText("Cut");
jMenu7.add(jMenuItem6);

jMenuItem7.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem7.setText("Copy");
jMenu7.add(jMenuItem7);

jMenuItem8.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem8.setText("Paste");
jMenu7.add(jMenuItem8);

jMenuBar2.add(jMenu7);

jMenu8.setText("Help");

jMenuItem9.setText("Check for Update");
jMenu8.add(jMenuItem9);

jMenuItem10.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_H, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem10.setText("About");
jMenu8.add(jMenuItem10);

jMenuBar2.add(jMenu8);

setJMenuBar(jMenuBar2);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jToolBar2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 756, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(0, 0, Short.MAX_VALUE))
);

pack();
setLocationRelativeTo(null);
}// </editor-fold>

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(roshantrades.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(roshantrades.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(roshantrades.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(roshantrades.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new roshantrades().setVisible(true);
}
});
}

// Variables declaration - do not modify
private javax.swing.JToggleButton Button_add;
private javax.swing.JButton button_Purchase;
private javax.swing.JButton button_Purchase2;
private javax.swing.JButton button_Purchase3;
private javax.swing.JButton button_Purchase4;
private javax.swing.JButton button_Purchase5;
private javax.swing.JMenu jMenu4;
private javax.swing.JMenu jMenu5;
private javax.swing.JMenu jMenu6;
private javax.swing.JMenu jMenu7;
private javax.swing.JMenu jMenu8;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuBar jMenuBar2;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem10;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JMenuItem jMenuItem3;
private javax.swing.JMenuItem jMenuItem4;
private javax.swing.JMenuItem jMenuItem5;
private javax.swing.JMenuItem jMenuItem6;
private javax.swing.JMenuItem jMenuItem7;
private javax.swing.JMenuItem jMenuItem8;
private javax.swing.JMenuItem jMenuItem9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JPopupMenu.Separator jSeparator1;
private javax.swing.JPopupMenu.Separator jSeparator2;
private javax.swing.JToolBar.Separator jSeparator3;
private javax.swing.JToolBar jToolBar2;
private javax.swing.JPanel panel_addons;
private javax.swing.JTable table_purchase;
// End of variables declaration


}


syntax error (code 1): , while compiling: CREATE TABLE

What am I missing in my sql command?



public class PhoneDal extends SQLiteOpenHelper {

// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = Constants.DB_NAME;

public static final String BLOCKED_PHONES_TABLE = "BLOCKED_PHONES_TABLE";

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

@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_BLOCKED_PHONES_TABLE =
"CREATE TABLE "+ BLOCKED_PHONES_TABLE +
" ( "+ KEY_ID+" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL DEFAULT 1, "
+ KEY_PHONE+" TEXT, "
+ KEY_IS_BLOCKED+" BIT," +
" UNIQUE "+ KEY_PHONE+" )";

db.execSQL(CREATE_BLOCKED_PHONES_TABLE);
}


and the error is



android.database.sqlite.SQLiteException: near "KEY_PHONE": syntax error (code 1): , while compiling: CREATE TABLE BLOCKED_PHONES_TABLE ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL DEFAULT 1, KEY_PHONE TEXT, KEY_IS_BLOCKED BIT, UNIQUE KEY_PHONE )
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)

SQlite parallel read and write in Android

I am working with sqlite in android. I have one database having almost 10 tables. I am accessing database through one SQLiteOpenHelper class. For each table's read and write i have written separate functions. Each functions having getReadableDatabase() and getWritableDatabase() respectively and end of each function am closing opened database with db.close() function. I have multiple threads to read and write parallel, while reading i am unable to write its shows database locked exception. I tried to use WAL but something is missing or not correct.


Which is the best way to implement WAL or parallel access to database ?


inserting into SQLLite database

I am very much new to Sqlite operation, Till now I was operating only to UI + some Web service


What I am facing issue is that,


I am creating a table from Terminal and inserting values in it from Xcode by matching the table name. The table consist for 4 fields, out of which 2 belongs to table and 2 are foreign keys.


When even I insert the Query my app FREEZES at that point.


It doesn't move further, not allowing any operations.


Here is my query



FMDatabase* db=[SqlLiteDAOFactory createConnection];

for(int i=0;i<[matchQesA count];i++)
{
MTQuestionDTO *mTQuestionDTO =[matchQesA objectAtIndex:i];

NSLog(@"value of testsample id is :- %@",questionDTO.testsampledid);
NSLog(@"value of sampletest id is :- %@",questionDTO.sampletestid);
NSLog(@"value of MTQ Question id :- %@",mTQuestionDTO.mtq_question_id);
NSLog(@"value of MTQ Question Text :- %@",mTQuestionDTO.mtq_question_text);

[db executeUpdate:@"insert into matchquestion (testsampledID,sampletestid,mtq_question_id,mtq_question_text) values(?,?,?,?)",questionDTO.testsampledid,questionDTO.sampletestid,mTQuestionDTO.mtq_question_id,mTQuestionDTO.mtq_question_text];

if ([db hadError])
{
NSLog(@"database error before");
NSLog(@"Err in inserting %d: %@", [db lastErrorCode], [db lastErrorMessage]);
[db close];
}
}

[db close];
return TRUE;


When I NSlog the values, it gives me proper values. Also when I fire the same query from Terminal value get inserted into database.


I am firing this Query to my Array count. I am having total Array, and want to insert the elements into table till array count.


Why my app is FREEZING, if its error then It must go in Error block, its not going there, So I am facing difficulties to track it.


What a mistake I made.


Thanks in advance.


Drop SQLite tables using list of tables names

I am trying to drop a collection of tables by using tables names in the list and then get the type of each string and drop it :



List<string> models = new List<string> { "WebBrowser", "Notebook", "Members"};

foreach (string mod in models)
{

Type type = Type.GetType(mod));
using (var dbConn = new SQLiteConnection(app.DBPath))
{
dbConn.RunInTransaction(() =>
{
dbConn.DropTable<type>();
//dbConn.DropTable<WebBrowser>();
dbConn.Dispose();
dbConn.Close();
});
}
}


Problem : I can't drop table using this way, DropTable need the name of class (e.g WebBrowser ) and I don't want to drop each table alone (i.e dbConn.DropTable< WebBrowser >();) since I have more than 50 tables to drop.


OSX: PySide WebKit bridge and sqlite and utf-8

I've created a sqlite database frontent to manage cooking recipes. It uses a html file displayed by PySide's QWebKit module as UI (python2.7).


Among other functions, displayed recipes can be filtered by tags and searched by titles. Tags and titles may (will!) contain German umlauts.


The application works well, umlaut-strings can be exchanged between the Python module, the sqlite database and the HTML/JavaScript interface - if and only if python is invoked from the shell or by double-clicking chmod'd file on linux.


Under OSX however, to be able to run an application I have to wrap it somehow. I tried py27-py2app 0.9_1 as well as Platypus 4.4, both with the same result:


The utf-8 encoded strings with umlauts get exchanged between Python and JS/HTML, but the sqlite module suddenly can't use them to search and filter entries anymore.


I already tried including an intermediate step of making the app launch a shell script which exports a number of variables (LC_ALL, LANG,...) and then calls the python interpreter, but it didn't change anything.


Any clues/ideas?


Full source code can be found at https://github.com/hermann-p/recipes (expect sloppy style and many results of trial-and-error learning of css/sqlite)


android database: the method open() is undefined for the type databasehelper class

i want to authenticate user id and password from sqlite database. The user table is saved in sqlite db, i want to compare the edittext value with the value saved in the sqlite db, when i initialize and open the database i get error that the method open() is undefined for the Db_getUserDetail (name of my database helper class).


code of main activity



@Override
public void onClick(View v) {

ffCode = ed_login.getText().toString();
password = ed_password.getText().toString();
// check if any of edit text is empty
if(ffCode.equals(""))
{
Toast.makeText(getApplicationContext(), "Please enter your FF code", Toast.LENGTH_LONG).show();
return;
}

else if (password.equals(""))
{
Toast.makeText(getApplicationContext(), "Please enter your password", Toast.LENGTH_LONG).show();
return;
}
Log.e("opening database", "yes");
Db_getUserDetail myDb= new Db_getUserDetail(MainActivity.this);
myDb.open();
//this is the method to query
String storedffcode=Db_getUserDetail.getCodeAndPassword(ffCode);
myDb.close();

if(ffCode.equals(storedffcode))
{
Toast.makeText(getApplicationContext(), "Congrats: Login Successfull", Toast.LENGTH_LONG).show();

}
else
{
Toast.makeText(getApplicationContext(), "User Name or Password does not match", Toast.LENGTH_LONG).show();
}

}

});


code for getting values from database



public static String getCodeAndPassword(String ffCode)
{
Log.e("retrieving ff code", "yes");
SQLiteDatabase db = null;
Cursor cursor = db.query("user_detail", null, " ff_code=?" , new String[]{ffCode}, null, null, null);
if(cursor.getCount()<1)
{
cursor.close();
return "Not Exist";
}
Log.e("found ff code", "yes");
cursor.moveToFirst();
String ffcode= cursor.getString(cursor.getColumnIndex("ff_code"));
return ffcode;
}


log cat:

java.lang.NullPointerException at com.example.db_client.Db_getUserDetail.getCodeAndPassword(Db_getUserDetail.java:135) at com.example.db_client.UserDetailActivity$1.onClick(UserDetailActivity.java:75) at android.view.View.performClick(View.java:4438) at android.view.View$PerformClick.run(View.java:18422) at android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:136)enter code here


code of db helper class



public class Db_getUserDetail extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "CRM";
public static final String CONTACTS_TABLE_NAME = "user_detail";
public static final String CONTACTS_COLUMN_USER_ID = "user_id";
public static final String CONTACTS_COLUMN_USER_PWD = "user_pwd";
public static final String CONTACTS_COLUMN_FF_CODE= "ff_code";
public static final String CONTACTS_COLUMN_FF_NAME = "ff_name";
public static final String CONTACTS_COLUMN_TERR_CODE = "terr_code";
public static final String CONTACTS_COLUMN_DG_CODE= "dg_code";
public static final String CONTACTS_COLUMN_DIST_CODE = "dist_code";
public static final String CONTACTS_COLUMN_FF_MOB = "ff_mob";
public static final String CONTACTS_COLUMN_IMEI_NO = "imeino";

//constructor for database class DBHelper....
public Db_getUserDetail(Context context)
{
super(context, DATABASE_NAME , null, 1);
}

String ff_code;
String ff_name;
String terr_code;
String dg_code;
String dist_code;
String ff_mob;
String imeino;

//override onCreate method to create Database table...
@Override
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub.
Log.e("DB created", "yes");
db.execSQL("create table user_detail" + "(user_id text, user_pwd text,ff_code text,ff_name text,terr_code text,dg_code text, dist_code text,ff_mob text,imeino text) ");
}

//Upgrade new Table...
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS user_detail");
onCreate(db);
}
//to insert new records in table...
public boolean insertUserData (String user_id, String user_pwd, String ff_code ,String ff_name,String terr_code,String dg_code, String dist_code,
String ff_mob, String imeino)

{
Log.e("DB insert call", "yes");

SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();

Log.e("content values", "yes");
contentValues.put("user_id", user_id);
contentValues.put("user_pwd", user_pwd);
contentValues.put("ff_code", ff_code);
contentValues.put("ff_name",ff_name);
contentValues.put("terr_code", terr_code);
contentValues.put("dg_code", dg_code);
contentValues.put("dist_code", dist_code);
contentValues.put("ff_mob", ff_mob);
contentValues.put("imeino", imeino);

db.insert("user_detail", null, contentValues);
return true;
}

//get data from table...
public Cursor getData(String id)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from user_detail", null );
return res;
}

//get no of rows in table...
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, CONTACTS_TABLE_NAME);
return numRows;
}

//to delete data from table at particular id....
public Integer deleteContact (String id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("user_detail","id = '"+id+"'", null);
}
//to get all data from database...
public ArrayList getAllCotacts()
{
ArrayList array_list = new ArrayList();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from user_detail", null );
res.moveToFirst();
while(res.isAfterLast() == false)
{
array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_USER_ID)));
array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_USER_PWD)));
array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_FF_CODE)));
array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_FF_NAME)));
array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_TERR_CODE)));
array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_DG_CODE)));
array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_DIST_CODE)));
array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_FF_MOB)));
array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_IMEI_NO)));

res.moveToNext();
}
return array_list;
}

public static String getCodeAndPassword(String ffCode)
{
Log.e("retrieving ff code", "yes");
SQLiteDatabase db = null;
//SQLiteDatabase db = getWritableDatabse();
Cursor cursor = db.query("user_detail", null, " ff_code=?" , new String[]{ffCode}, null, null, null);
if(cursor.getCount()<1)
{
cursor.close();
return "Not Exist";
}
Log.e("found ff code", "yes");
cursor.moveToFirst();
String ffcode= cursor.getString(cursor.getColumnIndex("ff_code"));
return ffcode;
}

WAMP server: Calling a MySQL database through PHP files

I'm currently developing an android application. The backend is written in PHP and takes input from the android app and connects it with a MySQL database (similar to http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/).


One of my class files (similar to the UserFunctions.java in the above link) requires the url to be given e.g. private static String loginURL = "http://10.0.2.2/android_api/index.php" so that the requisite communcation can take place. My issue is that all my PHP files are in a folder under \www e.g. \www\blah\. I'm fairly sure that I have put my PHP files in the wrong place as the link (Point 2 of http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/) shows some files being placed in \include\ and the index.php file outside this \include\ directory.


Where should I be placing my PHP files so that my file structure enables my app to communicate with the MySQL database (defined for example as android_api as in the link).


Android SQLite Database: Syntax error when adding to database

Hi I'm getting this error when adding data to my database but i can't figure out why. I think the problem is in the addData()-Method, but none of my atempts to fix it have worked so far.


"E/SQLiteLog﹕ (1) near "Aktivität": syntax error"


as well as:


"android.database.sqlite.SQLiteException: near "Aktivität": syntax error (code 1): , while compiling: INSERT INTO MedDatenTabelle(Schmerz,Broteinheiten,Messzeit,Wasser,Diastole,Müdigkeit,Puls,Symptom,letzte Aktivität,Gewicht,Kalorien,Bemerkungen,Systole,Temperatur,Blutzucker) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"


public class DatabaseHandler extends SQLiteOpenHelper {



private static final int DATABASE_VERSION = 1;

private static final String DATABASE_NAME= "MedDatenManager";

private static final String TABLE_MEDDATEN = "MedDatenTabelle";


private static final String KEY_ID = "id";
private static final String KEY_SYST = "Systole";
private static final String KEY_DIAST = "Diastole";
private static final String KEY_PULS = "Puls";
private static final String KEY_BLUTZ = "Blutzucker";
private static final String KEY_TEMP = "Temperatur";
private static final String KEY_GEW = "Gewicht";
private static final String KEY_KAL = "Kalorien";
private static final String KEY_BE ="Broteinheiten";
private static final String KEY_WASSER = "Wasser";
private static final String KEY_TIME = "Messzeit";
private static final String KEY_SCHMERZ = "Schmerz";
private static final String KEY_MUD = "Müdigkeit";
private static final String KEY_AKTI = "letzte Aktivität";
private static final String KEY_SYMP = "Symptom";
private static final String KEY_BEM = "Bemerkungen";

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

@Override
public void onCreate(SQLiteDatabase database) {
String CREATE_TABLE_MEDDATEN = "CREATE TABLE " + TABLE_MEDDATEN + " ("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_SYST + " TEXT,"
+ KEY_DIAST + " TEXT," + KEY_PULS + " TEXT," + KEY_BLUTZ + " TEXT,"
+ KEY_TEMP + " TEXT," + KEY_GEW + " TEXT," + KEY_KAL + " TEXT,"
+ KEY_BE + " TEXT," + KEY_WASSER + " TEXT," + KEY_TIME + " TEXT,"
+ KEY_SCHMERZ + " TEXT," + KEY_MUD + " TEXT," + KEY_AKTI + " TEXT,"
+ KEY_SYMP + " TEXT," + KEY_BEM + " TEXT" + " )";
database.execSQL(CREATE_TABLE_MEDDATEN);
}

@Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
database.execSQL("DROP TABLE IF EXISTS " + TABLE_MEDDATEN);

onCreate(database);
}

public void addData (MEDDATEN meddaten){
SQLiteDatabase database = this.getWritableDatabase();

ContentValues values = new ContentValues();

values.put(KEY_SCHMERZ,meddaten.getSchmerz());
values.put(KEY_BE,meddaten.getBroteinheiten());
values.put(KEY_TIME,meddaten.getMesszeit());
values.put(KEY_WASSER,meddaten.getWasser());
values.put(KEY_MUD,meddaten.getMüdigkeit());
values.put(KEY_DIAST,meddaten.getDiastole());
values.put(KEY_PULS,meddaten.getPuls());
values.put(KEY_SYMP,meddaten.getSymptome());
values.put(KEY_AKTI,meddaten.getLetzteAkt());
values.put(KEY_GEW,meddaten.getGewicht());
values.put(KEY_KAL,meddaten.getKalorien());
values.put(KEY_BEM,meddaten.getBemerkungen());
values.put(KEY_TEMP,meddaten.getTemperatur());
values.put(KEY_SYST,meddaten.getSystole());
values.put(KEY_BLUTZ,meddaten.getBlutzucker());

database.insert(TABLE_MEDDATEN, null, values);
database.close();

}




}


}


Cannot enter simply form information into SQLite DB (Rails)

So, I'm running into a fairly simple problem, where I cannot enter some simple form values into my SQLite DB (Rails).


Interestingly, the code doesn't fail - I submit the form, and am redirected successfully to the correct URL - and a record IS inserted into the DB, but the columns "name, type and user_id" are not filled with anything. To clarify, the columns are blank, for that new record.


If I comment out the code in the "create" and simply spit out the params (render plain: params[:plan].inspect) I do see all the correct parameters filled out, so I have a feeling there must be something wrong in the line:



@plan = Plan.new(params[:plan])


I'm really stuck here, any guidance would be much appreciated!


The create form



<h1> Create a new plan </h1>

<%= form_for :plan, url: plans_path do |f| %>
<p>
<%= f.label :name %><br>
<%= f.text_field :name %>
</p>

<p>
<%= f.label :type %><br>
<%= f.text_field :type %>
</p>

<%= f.hidden_field :user_id, :value => current_user.id %>

<p>
<%= f.submit %>
</p>
<% end %>


plans_controller.rb



class PlansController < ApplicationController

def index
@plans = Plan.all
end

def show
@plan = Plan.find(params[:id])
end

def new
@plan = Plan.new
end

def create
#render plain: params[:plan].inspect
params.permit!
@plan = Plan.new(params[:plan])
if @plan.save
redirect_to @plan
else
redirect_to dashboard_path, :notice => "Plan NOT Created!"
end
end

end


The Model



class Plan < ActiveRecord::Base

end

display informations from database by clicking listview

I want to display differents informations depending on what object is clicked i have a listfragment which display only name of objects like : KEYS,SHOES,USB and they are stored in my data base but each element has other information who are already stored but not shown for example KEYS has also a mac adress which is for example 0.0.0.1 and a password which is 123 .


So i want to display the mac adress and the password which correspond to the object who is clicked so who is in the same line in my database.



public class F1_fr extends ListFragment {
View rootview;
TextView textView1;
ArrayAdapter<String> aa;
ArrayList<String> arrayList = new ArrayList<String>();
SQLiteDatabase db;
ListView listView;

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);

}

@Override

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
rootview=inflater.inflate(R.layout.f1_lay,container,false);
textView1=(TextView)rootview.findViewById(R.id.textView1);
db = getActivity().openOrCreateDatabase("testDB2", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS test2(mac VARCHAR,mdp VARCHAR,obj VARCHAR);");

aa = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, arrayList);
setListAdapter(aa);



Cursor cursor = db.rawQuery("SELECT * FROM test2", null);
// Toast.makeText(myContext, ""+cursor.getCount(), Toast.LENGTH_LONG).show();
if(cursor.moveToFirst())

{
do {
arrayList.add(cursor.getString(2));


} while (cursor.moveToNext());
}


rootview.findViewById(R.id.semi_transparent).

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

Intent intent = new Intent(getActivity(), ajout.class);
startActivityForResult(intent, 2);

}

}

);
return rootview;

}


and the layout :



<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:fab="http://schemas.android.com/apk/res-auto"

android:layout_width="match_parent"
android:layout_height="match_parent">



<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@id/android:list"

android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true" />

<TextView
android:id="@android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textSize="30sp"
android:text="" />


<com.getbase.floatingactionbutton.AddFloatingActionButton
android:id="@+id/semi_transparent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
fab:fab_plusIconColor="@color/primaryColorDark"
fab:fab_colorNormal="@color/primaryColor"
fab:fab_colorPressed="@color/AccentColor"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />


</RelativeLayout>


I already put the method to click item in the list.


Thanks in advance for your help


Suggest best solution for my requirement below

I am created scanning application in windows using C#. Main task of my application is to get data from online SQL database to local database, after scanning complete and then upload data from local to online. now i am using XML file as local DB.I need to get download only one table from online DB which having 2 fields i.e (Ticket ID, Scanning Status). After records downloaded to local XML file, i am updating Scanning Status from False to True when ticket is scanned and then uploading Scanned tickets data to online database.


I was already did this work using XML files , but here issue is it took more time for downloading records (from Online to XML) and uploading (from XML to Online Database) because having thousands of records.


Loading time is issue here . so i am thinking about to use SQL lite or SQL Compact CE as local database instead of XML for faster Execution.


Please suggest me the best solution for my requirement


If i change format number on Sql i need to update table?

My application is on the market with alot of users. and i am a little bit afraid to update the app because i do some changing in the columns of my table. I.e i had "number INTEGER," and i only change the format to "number REAL,". i know that if i added new columns or remove columns i need to increase the version of the database and onUpgrade it (i did it before). for my case - i have to onUpgrade the table? or it sould working fine without to do that? When i tried to install to new table after i changing on my own device it's not crash and it's seems like it working very well, but what if the author user get error and all them data delete?


mardi 30 décembre 2014

Sqlite Fetching EXC_BAD_ERROR

I am fetching some details from database, while fetching i got an error like EXC_BAD_ACCESS. This error doesn't occurs regularly, it occurs randomly. Due to this i am not able to solve the issue. Please see the attached image, whether this occurs due to empty database.enter image description here


Problems converting a utf-8 encoded text to a json object. Json object not utf-8 encoded correctly

I am using a webservice in my Android application (which is utf-8 encoded, i am assuming this also applies to the SQLite Database that comes prepackaged with the Anddroid project) to download, parse and i am extracting the strings form the tags and saving it in my SQLite database on the mobile device. When i convert my custom objects into an arraylist and converting this to a json object, when i submit this to POST (to subsquently store in the remote MySQL database) I am getting a malformed UTF-8 characters. please can anyone help?



// recalling my arraylist of custom object form SQLite database

ArrayList list; list = recallSharedListFromDb();




//Converting arralyist to gson object
Gson gson = new GsonBuilder().create();
String json_arrayList = gson.toJson(list);

// Build parameters.
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("jsonObj", json_object));

//submitting to server
JSONObject json = jsonParser.makeHttpRequest(url_register_code, "POST", param);

// Read json response coming from server.
Log.d("SyncToMySQL", "json string: "+ json.toString());


My php file:



//Get JSON posted by Android Application
$json[] = $_POST["jsonObj"]; // this works...

foreach ($json as $string) {
echo 'Decoding: ' . $string;
json_decode($string);

switch (json_last_error()) {
case JSON_ERROR_NONE:
echo ' - No errors';
break;
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
echo ' - Unknown error';
break;
}

echo PHP_EOL;


}


An example of a typical custom object I have in my arrayList is below. I have noticed that when a character like "©" is present in my attribute, I get the "JSON_ERROR_UTF8" error and my program breaks. I have been working on this for days and i am really stuck. Untill i get pass this bit I cannot convert the json object into an array where i can then grab the attributes and place them into my remote MYSQL database.



[{"abstractText":"Ebola viruses and Marburg viruses include some of the most virulent and fatal pathogens known to humans. These viruses cause severe haemorrhagic fevers, with case fatality rates in the rangeola viruses and Marburg viruses include some of the most virulent and fatal pathogens known to humans. These viruses cause severe haemorrhagic fevers, with case fatality rates in the range 25-90%. The diagnosis of filovirus using formalin-fixed tissues from fatal cases poses a significant challenge. The most characteristic histopathological findings are seen in the 25-90%. The diagnosis of filovirus using formalin-fixed tissues from fatal cases poses a significant challenge. The mosola viruses and Marburg viruses include some of the most virulent and fatal pathogens known to humans. These viruses cause severe haemorrhagic fevers, with caseola viruses and Marburg viruses include some of the most virulent and fatal pathogens known to humans. These viruses cause severe haemorrhagic fevers, with case fatality rates in the range 25-90%. The diagnosis of filovirus using formalin-fixed tissues from fatal cases poses a significant challenge. The most characteristic histopathological findings are seen in the fatality rates in the range 25-90%. The diagnosis of filovirus using formalin-fixed tissueola viruses and Marburg viruses include some of the most virulent and fatal pathogens known to humans. These viruses cause severe haemorrhagic fevers, with case fatality rates in the range 25-90%. The diagnosis of filovirus using formalin-fixed tissues from fatal cases poses a significant challenge. The most characteristic histopathological findings are seen in the s from fatal cases poses a significant challenge. The most characteristic histopathological findings are seen in the t characteristic histopathological findings are seen in the liver; however, the findings overlap with many other viral and non-viral haemorrhagic diseases.","authorString":"Martines RB, Ng DL, Greer PW, Rollin PE, Zaki SR.","issue":"2","journalTitle":"J. Pathol.","pageInfo":"153-174","pmid":"25297522","pubYear":"2015","title":"Tissue and cellular tropism, pathology and pathogenesis of Ebola and Marburg viruses.","volume":"235"}]



QWT performance improvement for plot

I have a 2D dataset X, Y and an intensity value (but with some points missing). The data is stored in a sqlite database as X, Y, and Z for each row. I have about 1.5M rows for each plot. X range is about 4000pts wide and Y is about 1800 pts wide. So only approx 20% of the points in the plot actually have a specified value, the rest are initialized to a minimum value. Even less will be "visible" based on typical colorbar scale ranges (specified by user).


I am using QwtPlotSpectrogram to get the output I want. It takes a while to perform the SQL queries. Then it takes quite a while to do the plot. I'm looking for recommendations on how to improve the performance, especially on the plotting.


I've attached an excerpt of the code showing me pulling the data from the database then drawing the plot. I did some modifications so the code shown is more concise without pasting me entire program. Hope it makes sense.



QSqlQuery query(tsd_data);
int pl=plot_number;
query.exec("SELECT max(x), min(x), max(z), min(z) FROM database.plot_data WHERE pl="+QString::number(pl));
query.next();
int max_x = query.value(0).toInt();
int min_x = query.value(1).toInt();
int max_z = query.value(2).toInt();
int min_z = query.value(3).toInt();
int x_count = max_x-min_x;
QVector<double> dr_data(x_count*(y_count+1),-200);

query.exec("SELECT y, x, z FROM database.plot_data WHERE pl="+QString::number(pl));
while (query.next())
{
int y = query.value(0).toInt();
int x = query.value(1).toInt();
dr_data[y*x_count+(x-min_x)] = query.value(2).toDouble();
}

QwtMatrixRasterData *qwtm = new QwtMatrixRasterData();
qwtm->setInterval( Qt::XAxis, QwtInterval( min_x-zero, max_x-zero ) );
qwtm->setInterval( Qt::YAxis, QwtInterval( 0, 1800) );
qwtm->setInterval( Qt::ZAxis, QwtInterval( min_z, max_z ) );
qwtm->setValueMatrix(dr_data,bin_count);
QwtPlotSpectrogram *spec = new QwtPlotSpectrogram();
spec->setRenderThreadCount( 0 ); // use system specific thread count
spec->setCachePolicy( QwtPlotRasterItem::PaintCache );
QwtLinearColorMap *colormap = new QwtLinearColorMap(Qt::black, Qt::white);
colormap->addColorStop(0.1,Qt::blue);
colormap->addColorStop(.3,Qt::cyan);
colormap->addColorStop(.5,Qt::green);
colormap->addColorStop(.7,Qt::yellow);
colormap->addColorStop(.9,Qt::red);
spec->setColorMap(colormap);
spec->setData(qwtm);
spec->setDisplayMode( QwtPlotSpectrogram::ImageMode, true );
ui->dr_plot->setEnabled(true);
ui->dr_scale->setEnabled(true);
ui->dr_scale->setColorBarEnabled(true);
ui->dr_scale->setColorBarWidth(40);
QwtInterval zInterval = spec->data()->interval(Qt::ZAxis);
ui->dr_scale->setColorMap(zInterval,colormap);
spec->attach(ui->dr_plot);
ui->dr_plot->replot();

Updating and downloading database

I have an idea for an app that uses Database from internet , Then install it on the current device


When user later open the app, the app checks if there's new version of the current database


So my question is : how to implement this feature ?


Thank you


Android- java.lang.IllegalStateException: Cannot perform this operation because the connection pool has been closed

I was reading through stackoverflow about this question and I still haven't found a solution. Sometimes my application face this problem. this is my error log,



12-31 10:58:28.025: E/AndroidRuntime(16322): FATAL EXCEPTION: Timer-0
12-31 10:58:28.025: E/AndroidRuntime(16322): java.lang.IllegalStateException: Cannot perform this operation because the connection pool has been closed.
12-31 10:58:28.025: E/AndroidRuntime(16322): at android.database.sqlite.SQLiteConnectionPool.throwIfClosedLocked(SQLiteConnectionPool.java:1031)
12-31 10:58:28.025: E/AndroidRuntime(16322): at android.database.sqlite.SQLiteConnectionPool.waitForConnection(SQLiteConnectionPool.java:746)
12-31 10:58:28.025: E/AndroidRuntime(16322): at android.database.sqlite.SQLiteConnectionPool.acquireConnection(SQLiteConnectionPool.java:400)
12-31 10:58:28.025: E/AndroidRuntime(16322): at android.database.sqlite.SQLiteSession.acquireConnection(SQLiteSession.java:905)
12-31 10:58:28.025: E/AndroidRuntime(16322): at android.database.sqlite.SQLiteSession.executeForCursorWindow(SQLiteSession.java:834)
12-31 10:58:28.025: E/AndroidRuntime(16322): at android.database.sqlite.SQLiteQuery.fillWindow(SQLiteQuery.java:62)
12-31 10:58:28.025: E/AndroidRuntime(16322): at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:144)
12-31 10:58:28.025: E/AndroidRuntime(16322): at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:133)
12-31 10:58:28.025: E/AndroidRuntime(16322): at android.database.AbstractCursor.moveToPosition(AbstractCursor.java:197)
12-31 10:58:28.025: E/AndroidRuntime(16322): at android.database.AbstractCursor.moveToFirst(AbstractCursor.java:237)
12-31 10:58:28.025: E/AndroidRuntime(16322): at com.eyepax.horseapp.data.dbadapters.ContactGroupDbAdapter.getContactGroups(ContactGroupDbAdapter.java:138)
12-31 10:58:28.025: E/AndroidRuntime(16322): at com.eyepax.horseapp.data.DataManager.getGroups(DataManager.java:1548)
12-31 10:58:28.025: E/AndroidRuntime(16322): at com.eyepax.horseapp.sync.ContactSync.contactGroupSync(ContactSync.java:43)
12-31 10:58:28.025: E/AndroidRuntime(16322): at com.eyepax.horseapp.service.SynchingService.callSync(SynchingService.java:77)
12-31 10:58:28.025: E/AndroidRuntime(16322): at com.eyepax.horseapp.service.SynchingService.access$0(SynchingService.java:70)
12-31 10:58:28.025: E/AndroidRuntime(16322): at com.eyepax.horseapp.service.SynchingService$1.run(SynchingService.java:57)


This is the method which crashed in ContacGroupDbAdapter class,



/**
* Returns ContactGroup.
*
* @return ArrayList<ContactGroup>
*/
public ArrayList<ContactGroup> getContactGroups() {

this.open();
Cursor cursor = database.rawQuery("SELECT * FROM " + TABLE_NAME, null);
ArrayList<ContactGroup> list = null;

if (cursor != null && cursor.moveToFirst()) {
list = new ArrayList<ContactGroup>();

do {
try {
ContactGroup contactGroup = new ContactGroup();
contactGroup.setGroupId(cursor.getString(cursor.getColumnIndex(GROUP_ID)));
contactGroup.setGroupName(cursor.getString(cursor.getColumnIndex(GROUP_NAME)));
contactGroup.setIsDeleted(cursor.getInt(cursor.getColumnIndex(GROUP_IS_DELETED)));
contactGroup.setUpdatedDate(cursor.getString(cursor.getColumnIndex(GROUP_UPDATE_DATE)));
contactGroup.setIsSync(cursor.getInt(cursor.getColumnIndex(GROUP_IS_SYNC)));

list.add(contactGroup);
} catch (Exception e) {

}
} while (cursor.moveToNext());

}

if (cursor != null)
cursor.close();
return list;
}


And that it crashed in the line cursor.moveToFirst() with this error. please help me to resolve this issue.


Errors in my SQLite Database for Android

I am having multiple issues with my SQLite Database with Android. I am new to developing and learning on my own. SO please use laymens terms and assume i do not know what you are talking about lol. Specifically i am having trouble wit the methods:



  • getLast()

  • deleteLast()

  • getLatestSubjectForContact()

  • getAllRows()

  • isEmpty()


If you see any other errors i will accept feedback. Thanks for all help you can provide. here is my database code



package com.swavey.testing;

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.security.KeyChain;

import java.util.Date;

/**
* Created by Adrian on 11/5/2014.
*/
public class smsDatabase {

private static final String KEY_ID = "_id";
private static final int COLUMN_ID =0;

// database info
public static final String DATABASE_NAME = "texts";
public static final String DATABASE_TABLE = "mainTable";
public static final int DATABASE_VERSION = 4;

// list of fields
public static final String KEY_ADDRESS = "address";
public static final String KEY_BODY = "body";
private static final String KEY_DATE = "date";
private static final String KEY_READ = "read";
private static final String KEY_THREADID = "thread_id";
private static final String KEY_TYPE = "type";
private static final String KEY_SEEN = "seen";

//list of field numbers
private static final int COL_ADDRESS = 1;
private static final int COL_BODY = 2;
private static final int COL_DATE = 3;
private static final int COL_READ = 4;
private static final int COL_THREADID = 5;
private static final int COL_TYPE = 6;
private static final int COL_SEEN = 7;

//create string array of all fields;
public static final String[] ALL_KEYS = new String[] {KEY_ID, KEY_ADDRESS, KEY_BODY, KEY_DATE,
KEY_READ, KEY_THREADID, KEY_TYPE, KEY_SEEN};


private static final String DATABASE_CREATE_SQL = "create table " + DATABASE_TABLE
+ " (" + KEY_ID + " integer primary key autoincrement, "
+KEY_ADDRESS + " text not null, "
+KEY_BODY + " text not null, "
+KEY_DATE + " text not null, "
+KEY_READ+ " text not null, "
+KEY_THREADID+ " text not null, "
+KEY_TYPE+ " text not null, "
+KEY_SEEN+ " text not null"
+ ");";

private final Context context;

private DatabaseHelper dbHelper;
private SQLiteDatabase db;

public smsDatabase (Context cxt) {
this.context = cxt;
dbHelper = new DatabaseHelper(context);
}

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

//returns a cursor with all rows loaded
public Cursor getAllRows() {
String where = null;
Cursor cursor = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null,
null, null);

if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}

public boolean isEmpty() {
String where = null;
Cursor cursor = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null,
null, null);
if (cursor!=null) return false;
return true;
}


// insert sms into table
public long insertSMS (SMS sms) {
ContentValues iv = new ContentValues();
iv.put(KEY_ADDRESS, sms.getAddress());
iv.put(KEY_BODY, sms.getBody());
iv.put(KEY_DATE, sms.getDate());
iv.put(KEY_READ, sms.getRead());
iv.put(KEY_THREADID, sms.getThread_id());
iv.put(KEY_TYPE, sms.getType());
iv.put(KEY_SEEN, sms.getSeen());




return db.insert(DATABASE_TABLE, null, iv);
}

public Cursor getLast() {
SMS txt = new SMS();
String where = null;
Cursor c = db.query(true, DATABASE_TABLE,ALL_KEYS, where, null, null, null, null, null);
c.moveToLast();
return c;

}

public void deleteLast() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE,ALL_KEYS, where, null, null, null, null, null);
String las = Integer.toString(c.getCount());
db.delete(DATABASE_TABLE, KEY_ID + "=" + las, null);
}

public void deleteRow(String address, String date, String body ) {
db.delete(DATABASE_TABLE, KEY_ADDRESS + "=" + address +" and " + KEY_DATE + "=" +
date + " and " + KEY_BODY + "=" + body, null);
}

public String getLatestSubjectForContact() {
Cursor c = getLast();
String sub = c.getString(c.getColumnIndex("body"));
if (sub.length() > 30) {
sub = sub.substring(0, 30) + "...";
return sub;
}
sub = sub + "...";
return sub;
}

private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}


public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
_db.execSQL("DROP TABLE IF EXISTS "+ DATABASE_TABLE);
onCreate(_db);
}
}
}