dimanche 1 mars 2015

Can't insert data more than 254 in sqlite database by java

I am using a java class which allow me to insert data into SQLite database from string. I am inserting the data by a loop. My string have 260 data. When I try to insert those data from string to sqlite database it works fine but stops at the position of 254 every time! Why ?!



for(i = 0; i < 260; i++)
{
try {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:D:\\new.db");
java.sql.Statement statement = connection.createStatement();
statement .executeUpdate("INSERT INTO suggestion (suggesting) VALUES('"+words[i]+"')");
System.out.println(i + " - " + words[i]);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Word.class.getName()).log(Level.SEVERE, null, ex);
}
}


Here is the error log from netbeans!



Exception in thread "main" java.lang.NullPointerException at org.sqlite.NestedDB$CausedSQLException.fillInStackTrace(NestedDB.java:442) at java.lang.Throwable.(Throwable.java:250) at java.lang.Exception.(Exception.java:54) at java.sql.SQLException.(SQLException.java:140) at org.sqlite.NestedDB$CausedSQLException.(NestedDB.java:435) at org.sqlite.NestedDB._open(NestedDB.java:63) at org.sqlite.DB.open(DB.java:77) at org.sqlite.Conn.(Conn.java:88) at org.sqlite.JDBC.connect(JDBC.java:64) at java.sql.DriverManager.getConnection(DriverManager.java:571) at java.sql.DriverManager.getConnection(DriverManager.java:233) at test.Word.main(Word.java:106) Java Result: 1



Android SQLite Passing Item selected in gridview into another Activity for editing

Basically I have a Database with Accounts in them. I use GridView for viewing them, and from there you can select an Account and it will direct you to my Activity AccountManagement wherein you can modify, delete or just view all of the details of the selected Account from the GridView.


My problem is passing the data from the selection in GridView to AccountManagement.I'm not entirely sure how to use Intents for this properly. So far the code below doesn't work because I don't know how to pass the data into my AccountManagement and reference it properly from there.


Code is here, anything with Acc is problematic since Acc is where I'm supposed to put the data from GridView. I marked all those lines with a long ------ to make it easier to spot. Feel free to ask for any missing code.


AccountManagement snippet:



public class AccountDetails extends Activity {

DatabaseHelper dbHelper;
static public LinearLayout Linlay;
EditText txtName;
EditText txtAmt;
EditText txtPurpose;
TextView txtDate;
TextView txtEditDate;
Spinner spinStat;
Spinner spinTerm;

@Override
public void onCreate(Bundle savedInstanceState) {

Intent intent = getIntent();
Bundle bundle = intent.getExtras();

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

Linlay = (LinearLayout) findViewById(R.id.Linlay);
spinStat = (Spinner) findViewById(R.id.spinStat);
spinTerm = (Spinner) findViewById(R.id.spinTerm);
txtName = (EditText) findViewById(R.id.txtDelName);
txtAmt = (EditText) findViewById(R.id.txtDelAmt);
txtPurpose = (EditText) findViewById(R.id.txtDelPurpose);
spinTerm = (Spinner) findViewById(R.id.spinTerm);
txtDate = (TextView) findViewById(R.id.colDate);
txtEditDate = (TextView) findViewById(R.id.colEditDate);
spinStat = (Spinner) findViewById(R.id.spinStat);


Utilities.ManageTermSpinner(AccountDetails.this, spinTerm);
for(int i=0;i<spinTerm.getCount();i++)
{
long id=spinTerm.getItemIdAtPosition(i);
if(id==Acc.getTerms())--------------------------------------------
{
spinTerm.setSelection(i, true);
break;
}
}

Utilities.ManageStatSpinner(AccountDetails.this, spinStat);
for(int j=0;j<spinStat.getCount();j++)
{
long id=spinStat.getItemIdAtPosition(j);
if(id==Acc.getStatus())--------------------------------------------
{
spinStat.setSelection(j, true);
break;
}
}


txtName.setText(Acc.getName());---------------------------------------
txtAmt.setText(String.valueOf(Acc.getAmt()));-------------------------
txtPurpose.setText(Acc.getPurpose());---------------------------------



Button delete = (Button) findViewById(R.id.delete);
delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog diag = Alerts.DeleteConfirm(AccountDetails.this, Acc );--------------------------------
diag.show();
}
});
}


GridView snippet:


This is where I should be getting the data to put into Acc but I'm not sure how, so everything here can be changed since I'm not sure if this is the ideal way to do it.



try {
grid.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
try {



SQLiteCursor cr = (SQLiteCursor) parent.getItemAtPosition(position);
String name = cr.getString(cr.getColumnIndex(DatabaseHelper.colName));
int amount = cr.getInt(cr.getColumnIndex(DatabaseHelper.colAmount));
String purpose = cr.getString(cr.getColumnIndex(DatabaseHelper.colPurpose));
String Terms = cr.getString(cr.getColumnIndex(DatabaseHelper.colTermsClass));
String Status = cr.getString(cr.getColumnIndex(DatabaseHelper.colStatClass));
String date = cr.getString(cr.getColumnIndex(DatabaseHelper.colDate));
String editdate = cr.getString(cr.getColumnIndex(DatabaseHelper.colEditDate));
Account acc = new Account(name, amount, purpose, db.GetTermsID(Terms),date,editdate,db.GetStatID(Status));
acc.SetID((int) id);

Intent myIntent = new Intent(AccountManager.this, AccountDetails.class);
Bundle extras = new Bundle();
myIntent.putExtras(extras);
startActivityForResult(myIntent, 0);


} catch (Exception ex) {
Alerts.CatchError(AccountManager.this, ex.toString());
}
}


});
} catch (Exception ex) {

}

Merging SQLite databases in Java throws "unique constraint failed"

I am trying to merge two SQLite databases with Java. The database scheme is generated as follows:



public static void createDatabaseTables(Connection c)
{
String sql;

// creates the table HASHES
sql = "CREATE TABLE HASHES("
+ "INPUTVALUE TEXT PRIMARY KEY,"
+ "HASHVALUE TEXT);";
executeUpdate(c, sql);
System.out.println("Table HASHES created successfully");
}


I am using the following code to merge two databases (the first one is empty and the second one contains some values (inputvalues and appropriate pearson hashes)).



public static void mergeDatabases(String path1, String path2)
{
// open a database connection
Connection c = openDatabaseConnection(path1);

// end the actual transaction (must be done to attach a new database)
executeUpdate(c,"end transaction");

// attach the second database to the first one
String sql = "ATTACH DATABASE '" + path2 + "' AS toMerge";
executeUpdate(c, sql);

// copy the calculated hashes from the second database to the first one
sql = "INSERT INTO HASHES SELECT * FROM toMerge.HASHES";
executeUpdate(c, sql);

// begin a transaction
executeUpdate(c, "begin transaction");

// close the connection
closeDatabaseConnection(c);

System.out.println("Databases merged.");
}


This leads me to the following exception for every row (because if I add the "OR IGNORE" clause at the INSERT, every row is ignored)



java.sql.SQLException: UNIQUE constraint failed: HASHES.INPUTVALUE


I am sure that the values of the column INPUTVALUE are unique (because they are generated with each ascii symbol in a loop). Nevertheless I get the exception.


What am I doing wrong?


Merging SQLite databases in Java throws "unique constraint failed"

I am trying to merge two SQLite databases with Java. The database scheme is generated as follows:



public static void createDatabaseTables(Connection c)
{
String sql;

// creates the table HASHES
sql = "CREATE TABLE HASHES("
+ "INPUTVALUE TEXT PRIMARY KEY,"
+ "HASHVALUE TEXT);";
executeUpdate(c, sql);
System.out.println("Table HASHES created successfully");
}


I am using the following code to merge two databases (the first one is empty and the second one contains some values (inputvalues and appropriate pearson hashes)).



public static void mergeDatabases(String path1, String path2)
{
// open a database connection
Connection c = openDatabaseConnection(path1);

// end the actual transaction (must be done to attach a new database)
executeUpdate(c,"end transaction");

// attach the second database to the first one
String sql = "ATTACH DATABASE '" + path2 + "' AS toMerge";
executeUpdate(c, sql);

// copy the calculated hashes from the second database to the first one
sql = "INSERT INTO HASHES SELECT * FROM toMerge.HASHES";
executeUpdate(c, sql);

// begin a transaction
executeUpdate(c, "begin transaction");

// close the connection
closeDatabaseConnection(c);

System.out.println("Databases merged.");
}


This leads me to the following exception for every row (because if I add the "OR IGNORE" clause at the INSERT, every row is ignored)



java.sql.SQLException: UNIQUE constraint failed: HASHES.INPUTVALUE


I am sure that the values of the column INPUTVALUE are unique (because they are generated with each ascii symbol in a loop). Nevertheless I get the exception.


What am I doing wrong?


Does ResultSet.Next() skip rows?

I'm running unto a problem with the Resultset.Next() method in Java8. The following code connects to a SQLite database file and attempts to read all the tables contained in the db.



// Set the connection up with jdbc and sqlite.
Connection connection = DriverManager.getConnection("jdbc:sqlite:file.db");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30);

// Get all the tables in the DB so we can check that we have all we need.
ResultSet trs = statement.executeQuery("SELECT name FROM sqlite_master WHERE type='table';");
while (trs.next()) {
String tblname = trs.getString("name").toLowerCase();
log.log(Level.INFO, "Found table: " + tblname);


The database contains 2 tables (verified by running the query in the sqlite3 client), but the while loop only does one iteration before exiting.


Any suggestions as to why the last table gets ignored?


How to add my own PRAGMA statements in SQLite to store custom meta data

I want to store meta data like author name, copyright, source to my SQLite DB without creating a new table. I found out we can use PRAGMA statements to set some values.. I would like to store my own custom name and value ... How to create custom PRAGMA statement? http://ift.tt/1g4bkiN


Has anyone done this before? The doc says..


"The C-language API for SQLite provides the SQLITE_FCNTL_PRAGMA file control which gives VFS implementations the opportunity to add new PRAGMA statements or to override the meaning of built-in PRAGMA statements."


Please let me know how can I achieve this?


cursor is not displaying data in second activity

I have a list of items, the data are stored in the SQLite. The problem occurred when I wanted to get detailed view of the item, it doesn't display any data. This is activity that displays all rows from the database in a listview, works great.



public class List extends Activity {

public final static String ID_EXTRA="com.example.bazadanych._ID";

DBAdapter myDB;

String passedV=null;

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

passedV=getIntent().getStringExtra(MainActivity.ID_EXTRA);

openDB();

populateListViewDB ();

onclickcallback();

}

@Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}

private void openDB() {
myDB = new DBAdapter(this);
myDB.open();

}

private void closeDB() {
myDB.close();

}

private void populateListViewDB() {
Cursor cursor = myDB.getAllRows();

startManagingCursor(cursor);

String[] fromFieldNames = new String[]
{DBAdapter.KEY_NAME, DBAdapter.KEY_COUNTRY, DBAdapter.KEY_REGION, DBAdapter.KEY_PHONE};
int [] toViewIDs = new int []
{R.id.list_item_name, R.id.list_item_country, R.id.list_item_region, R.id.list_icon_item};

SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(
this,
R.layout.list_item,
cursor,
fromFieldNames,
toViewIDs
);


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

}
private void onclickcallback() {
ListView myList = (ListView) findViewById(R.id.listViewDB);
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long id) {

Intent intent = new Intent(List.this, Details.class);
intent.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(intent);
}
});
}
}


From the List.class after clicking on item from the list the user can move to details.class that is suppose to display details of the item. Unfortunately it doesn't display anything and doesn't give any error either.


I'm passing an Id from one activity to another, it moves from one to the other but later on doesn't display any data,



public class Details extends Activity {

DBAdapter myDB;

String passedV=null;

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

passedV=getIntent().getStringExtra(List.ID_EXTRA);
myDB = new DBAdapter(this);
}

private void populatedetailsViewDB() {
Cursor cursor = myDB.getRow(0);

startManagingCursor(cursor);


String[] fromFieldNames = new String[]
{DBAdapter.KEY_NAME, DBAdapter.KEY_COUNTRY, DBAdapter.KEY_REGION, DBAdapter.KEY_ADRESS, DBAdapter.KEY_PHONENUM, DBAdapter.KEY_PHONE};
int [] toViewIDs = new int []
{R.id.item_name, R.id.item_country, R.id.item_region, R.id.item_adress, R.id.item_phonenum, R.id.list_icon_item};

SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(
this,
R.layout.item_layout,
cursor,
fromFieldNames,
);

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


}
}


That's getting a single row from the DBAdapter.



public class DBAdapter {

...

public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}

// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}

// Close the database connection.
public void close() {
myDBHelper.close();
}

...

public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}


Can anyone see what might be the problem?