Datatype mismatch for blob type blackberry - sqlite

I have an exception that Datatype mismatch in this line
byte[] _data = (byte[])row.getBlobBytes(1);
and in the table I have the type of column 2 is BLOB.
public static UrlRsc getContentUrl(String name) {
UrlRsc elementRsc = null;
try {
Statement statement = DB
.createStatement("SELECT * FROM table where"
+ " Name='"
+ name + "'");
statement.prepare();
Cursor cursor = statement.getCursor();
Row row;
while (cursor.next()) {
row = cursor.getRow();
byte[]_data;
_data = row.getBlobBytes(1);
}
statement.close();
cursor.close();
} catch (DatabaseException dbe) {
System.out.println(dbe.toString());
} catch (DataTypeException dte) {
System.out.println(dte.toString());
}
return elementRsc;
}
Can any one help me ?

Hi i am using following code for save image in my local database and i got success. i just posted my 3 methods
Note: When i am inserting image into data base i changed that image in byte array then only i can save into that table
1)Table creation 2) table insertion 3)image retrieving from table
ContactImage_table creation
public ContactImageTableCreation(){
try{
Statement stmt=DATABASE.createStatement("create table if not exists 'ContactImage_table'(ID 'TEXT',image 'blob',NodeId 'TEXT')");
stmt.prepare();
stmt.execute();
stmt.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
Insert data into ContactImage_table
public void ContactImageTableInsertion(){
try{
Statement st=DATABASE.createStatement("insert into ContactImage_table (ID,Image,NodeId)values(?,?,?)");
st.prepare();
st.bind(1, "101");
st.bind(2, BYTE_ARRY);
st.bind(3,"103");
st.execute();
st.close();
}catch (Exception e) {
System.out.println(e.getMessage());
}
}
Retrieving data from ContactImage_table
public ContactImageTableDataRetriving(){
try{
Statement st=DATABASE.createStatement("select * from ContactImage_table");
st.prepare();
Cursor c=st.getCursor();
Row r;
int i=0;
while(c.next()){
r=c.getRow();
i++;
// ContactImageObject is a wrapper class for data handling
contactImageObj=new ContactImageObject();
contactImageObj.setId(r.getString(0));
byte[] decoded=r.getBlobBytes(1);
EncodedImage fullImage = EncodedImage.createEncodedImage(decoded, 0, decoded.length);
Bitmap b=fullImage.getBitmap();
contactImageObj.setImage(b);
// System.out.println("Successfully retrived");
if(i==0){
// System.out.println("No Records");
}
}
st.close();
}catch (Exception e) {
// System.out.println(e.getMessage());
}
}
just cross check your code with this code snippet hope you will get resolve all the best

Related

How can we insert date into the SQLite database

For each data insert in SQLite database, I would like to get insert the current Date as well. How can I do it in Xamarin Forms app ?
Below is my code which now insert some status data into the database.
public void OnOKButtonClicked(object sender, EventArgs e)
{
overlay.IsVisible = false;
DisplayAlert("Result",
string.Format("You entered {0}", EnteredStatus.Text), "OK");
SoccerAvailability soccerAvailability = new SoccerAvailability();
soccerAvailability.SoccerStatus = EnteredStatus.Text;
var dailySoccerStatus = EnteredStatus.Text;
int x = 0;
try
{
if (!string.IsNullOrWhiteSpace(EnteredStatus.Text))
{
//Insert the soccer status to the database:
x = conn.Insert(soccerAvailability);
}
else
{
DisplayAlert("Soccer Availability", "Availability cannot be left blank", "OK");
}
}
catch (Exception ex)
{
throw ex;
}
if (x == 1)
{
Navigation.PushAsync(new Settings(soccerAvailability));
}
DisplaySoccerStatus();
}
just create a CurrentDate DateTime property on your SoccerAvailability model
soccerAvailability.CurrentDate = DateTime.Now;
x = conn.Insert(soccerAvailability);

If there is data, how is the stream returning zero bytes?

I have a RXTX project that I'm working on. I have it set ups as follows:
public void doConnect(ActionEvent event)
{
String selectedPort = (String)connectTabController.portList.getValue();
System.out.println("Connecting to: " + selectedPort);
selectedPortIdentifier = (CommPortIdentifier)portMap.get(selectedPort);
CommPort commPort = null;
try
{
commPort = selectedPortIdentifier.open("AT QC ReponseTime", TIMEOUT);
serialPort = (SerialPort)commPort;
setConnected(true);
if (isConnected)
{
if (initIOStream() == true)
{
initListener();
System.out.println("Initializing listener");
connectTabController.gui_changeStatusLabel("Device Connected!");
}
}
}
catch (PortInUseException e)
{
System.out.println("Port In use! " + e.toString());
}
catch (Exception e)
{
System.out.println("Failed to open! " + e.toString());
}
}
public boolean initIOStream()
{
//return value for whether opening the streams is successful or not
boolean successful = false;
try {
//
input = serialPort.getInputStream();
output = serialPort.getOutputStream();
writeData(RESETTPOD);
System.out.println("Writing Reset command");
successful = true;
System.out.println("IO Stream opened successfully!");
return successful;
}
catch (IOException e) {
System.out.println("I/O Streams failed to open. (" + e.toString() + ")");
return successful;
}
}
public void initListener()
{
try
{
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
}
catch (TooManyListenersException e)
{
System.out.println("Too many listeners. (" + e.toString() + ")");
}
}
That's how the connection is made, and it has a listener that's supposed to notify when data is available, which triggers the following:
#Override
public void serialEvent(SerialPortEvent evt) {
BufferedReader reader = null;
if (evt.getEventType() == SerialPortEvent.DATA_AVAILABLE)
{
try
{
reader = new BufferedReader(new InputStreamReader(input));
if (reader.ready())
{
fullLine = reader.readLine();
System.out.println(fullLine + "\n");
}
}
catch (Exception e)
{
System.out.println("#SerialEvent Failed to read data. (" + e.toString() + ")");
}
}
}
However, I keep getting "UNDERLYING INPUT STREAM RETURNED ZERO BYTES"
This makes no sense, since if there is nothing to read then the listener shouldnt be triggered int he first place. I tried running the app and I keep getting this error message around every 1/3 second, which corresponds to the burst-output of the device that's sending data. (which works fine in programs like PuttY)
If you are going to use the BufferedReader, take a look at the refence API document for javax.comm, CommPort and getInputStream. Then try using different settings for threshold and receive timeout.
eg).
serialPort.enableReceiveThreshold(3);
serialPort.enableReceiveTimeout(1);
https://docs.oracle.com/cd/E17802_01/products/products/javacomm/reference/api/

JavaFX combo box repeating the same value set

I used a combo box to retrieve data from MySQL database. But when i inserted the first value set to database, combo box values are repeating. I want to know why it is happening and how to avoid it. i called this method on main. Thanks
public void FillCombo(){
try{
String sql = "Select Name from Employee where Position='Driver'";
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()){
op.add(rs.getString("Name"));
}
selectDriverC.setItems(op);
pst.close();
rs.close();
}
catch(Exception e){
System.out.println(e);
}
}
Add a condition that checks if the String you wanna insert is already in op,
I assume op type is ObservableList<String>. This should work :
public void FillCombo(){
try{
String sql = "Select Name from Employee where Position='Driver'";
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()){
if(!op.contains(rs.getString("Name"))
add(rs.getString("Name"));
}
selectDriverC.setItems(op);
pst.close();
rs.close();
}
catch(Exception e){
System.out.println(e);
}
}

SQLite keep expanding

I'm new to the blackberry development and to this site. right now, i'm working on an app that retrieve data from a json service. In my app I should parse the data into a database and save it in four tables. I already parsed the data and I was successful able to create the database and add the first and the second tables.
The problem that I'm facing right now is, the second table in my data base keep expanding. I checked the database in the sql browser and I discovered that everytime I click on the app icon it adds the 700 rows to the table again.(ex. 700 becomes 1400) .
(only to the second table, the first table works so fine).
Thank you in advance
This is my code:
public void parseJSONResponceInBB(String jsonInStrFormat)
{
try {
JSONObject json = newJSONObject(jsonInStrFormat);
JSONArray jArray = json.getJSONArray("tables");
for (inti = 0; i < jArray.length(); i++) {
//Iterate through json array
JSONObject j = jArray.getJSONObject(i);
if (j.has("Managers")) {
add(new LabelField("Managers has been added to the database"));
JSONArray j2 = j.getJSONArray("Managers");
for (intk = 0; k < j2.length(); ++k) {
JSONObject MangersDetails = j2.getJSONObject(k);
if (MangersDetails.has("fName")) {
try {
URI myURI =
URI.create
("file:///SDCard/Databases/SQLite_Guide/"
+ "MyTestDatabase.db");
d = DatabaseFactory.openOrCreate(myURI);
Statement st =
d.createStatement
("CREATE TABLE Managers ( "
+ "fName TEXT, " +
"lName TEXT, " + "ID TEXT," + "Type TEXT )");
st.prepare();
st.execute();
st.close();
d.close();
}
catch(Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
try {
URI myURI =
URI.create
("file:///SDCard/Databases/SQLite_Guide/"
+ "MyTestDatabase.db");
d = DatabaseFactory.open(myURI);
Statement st =
d.createStatement
("INSERT INTO Managers(fName, lName, ID, Type) "
+ "VALUES (?,?,?,?)");
st.prepare();
for (intx = 0; x < j2.length(); x++) {
JSONObject F = j2.getJSONObject(x);
//add(new LabelField ("f"));
st.bind(1, F.getString("fName"));
st.bind(2, F.getString("lName"));
st.bind(3, F.getString("ID"));
st.bind(4, F.getString("Type"));
st.execute();
st.reset();
}
d.close();
}
catch(Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
}
}
}
catch(JSONException e) {
e.printStackTrace();
}
}
//Owners method
public voidparseJSONResponceInBB1(String jsonInStrFormat)
{
try {
JSONObject json = newJSONObject(jsonInStrFormat);
JSONArray jArray = json.getJSONArray("tables");
for (inti = 0; i < jArray.length(); i++) {
//Iterate through json array
JSONObject j = jArray.getJSONObject(i);
if (j.has("Owners")) {
add(new LabelField("Owners has been added to the database"));
JSONArray j2 = j.getJSONArray("Owners");
for (intk = 0; k < j2.length(); ++k) {
JSONObject OwnersDetails = j2.getJSONObject(k);
if (OwnersDetails.has("fName")) {
try {
Statement st =
d.createStatement
("CREATE TABLE Owners ( "
+ "fName TEXT, " +
"lName TEXT, " + "ID TEXT," + "Type TEXT )");
st.prepare();
st.execute();
st.close();
d.close();
}
catch(Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
try {
Statement st =
d.createStatement
("INSERT INTO Owners(fName, lName, ID, Type) "
+ "VALUES (?,?,?,?)");
st.prepare();
for (intx = 0; x < j2.length(); x++) {
JSONObject F = j2.getJSONObject(x);
//add(new LabelField ("f"));
st.bind(1, F.getString("fName"));
st.bind(2, F.getString("lName"));
st.bind(3, F.getString("ID"));
st.bind(4, F.getString("Type"));
st.execute();
st.reset();
}
d.close();
}
catch(Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
}
}
}
catch(JSONException e) {
e.printStackTrace();
}
}
It depends on what your goals are here. If you want to replace the data in the database each time the json query runs, you should add a sqlite command to remove all the existing rows with the newly fetched ones coming in via JSON.
If you just want to keep certain types of records unique, you should add an index to the sqlite table. The 'ID' column is a likely candidate for this. You'll have to do some experiments to make sure a conflict is handled correctly - it may abort the entire transaction. "INSERT OR REPLACE" is useful in that situation.

How to insert an array of String in SQLite database in blackberry

I have a Database Manager class which is creating the SQLite Database.Now from another class, i am creating the instance of that class. Now how can i insert an array of string in the Database?
My Database Manager class code is like below:
public class DatabaseManager
{
public Database sqliteDb = null;
public DatabaseManager()
{
try
{
URI myURI = URI.create("/SDCard/databases/itemdb.db");
Database sqliteDb = DatabaseFactory.openOrCreate(myURI);
sqliteDb.close();
sqliteDb = DatabaseFactory.open(myURI);
Statement statement = sqliteDb.createStatement("CREATE TABLE if not exists SelectedItem (Name TEXT, Quantity TEXT)");
statement.prepare();
statement.execute();
statement.close();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if(sqliteDb!=null)
{
sqliteDb.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
public static void insertValues(String tableName, Hashtable ht)
{
try
{
Logger.out("Grocery", "it is comin here");
URI myURI = null;
try
{
myURI = URI.create("/SDCard/databases/itemdb.db");
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (MalformedURIException e)
{
e.printStackTrace();
}
Database sqliteDb = DatabaseFactory.openOrCreate(myURI);
sqliteDb.close();
sqliteDb = DatabaseFactory.open(myURI);
Statement dbStatement = sqliteDb.createStatement("INSERT INTO SelectedItem(Name,Quantity) " + "VALUES (?,?)");
Enumeration itemName = ht.keys();
Enumeration itemQty = ht.elements();
while(itemName.hasMoreElements())
{
Logger.out("Grocery", "more items");
String strName = itemName.nextElement().toString();
String strQty = itemQty.nextElement().toString();
Logger.out("Grocery", "name:" + " " + strName);
Logger.out("Grocery", "QTY:" + " " + strQty);
dbStatement.bind(1, strName);
dbStatement.bind(2, strQty);
Logger.out("Grocery", "Binded:::::::::");
dbStatement.execute();
dbStatement.reset();
Logger.out("Grocery", "Executed:::::::::");
}
dbStatement.close();
}
catch (DatabaseException e)
{
e.printStackTrace();
}
}
public void closeDb()
{
try
{
sqliteDb.close();
}
catch (DatabaseIOException e)
{
e.printStackTrace();
}
}
}
Now i am taking the name and quantity as a hash table. And in my main class, when i am pressing the button i am inserting the values in the database like below:
dbManager = new DatabaseManager();
dbManager.insertValues("SelectedItem", htItem);
Try this as following when ever you want to use another class method as globle then just declare it as static . genaral query for multiple row insertion is
INSERT INTO 'tablename' SELECT 'data1' AS 'column1', 'data2' AS
'column2' UNION SELECT 'data3', 'data4' UNION SELECT 'data5', 'data6'
UNION SELECT 'data7', 'data8'
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
public class SampleDatabase extends UiApplication
{
LabelField test;
String names[];
int ages[];
MainScreen screen = new MainScreen();
public static void main(String[] args)
{
SampleDatabase theApp = new SampleDatabase();
theApp.enterEventDispatcher();
}
public SampleDatabase()
{
ButtonField btn=new ButtonField("Click");
names=new String[10];
ages=new int[10];
for(int i=0;i<10;i++)
{
names[i]="Govind"+i;
ages[i]=i;
}
btn.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
synchronized (UiApplication.getEventLock()) {
databaseOperations.DatabaseManager();
databaseOperations.InsertDatabaseManager(names,ages);
}
}
});
screen.add(btn);
pushScreen(screen);
}
}
This is another class named as "databaseOperations.java"
import net.rim.device.api.database.Database;
import net.rim.device.api.database.DatabaseFactory;
import net.rim.device.api.database.Statement;
import net.rim.device.api.io.URI;
public class databaseOperations {
public static void DatabaseManager()
{
Database d=null;
try {
URI uri = URI.create("file:///SDCard/Databases/SQLite_Guide/" +
"MyTestDatabase.db");
d = DatabaseFactory.openOrCreate(uri);
d.close();
d = DatabaseFactory.open(uri);
Statement s = d.createStatement( "CREATE TABLE if not exists 'People' ( " +
"'Name' TEXT, " +
"'Age' INTEGER )");
s.prepare();
s.execute();
s.close();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try {
if(d!=null)
{
d.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void InsertDatabaseManager(String[] names,int ages[])
{
Database d=null;
try {
URI uri = URI.create("file:///SDCard/Databases/SQLite_Guide/" +
"MyTestDatabase.db");
d = DatabaseFactory.openOrCreate(uri);
d.close();
d = DatabaseFactory.open(uri);
String query="INSERT INTO 'People' SELECT '"+names[0]+"' AS 'Name', "+ages[0]+" AS 'Age'";
String query2="";
for(int i=1;i<names.length;i++)
{
query2=query2+" UNION SELECT '"+names[i]+"', "+ages[i];
}
System.out.println(query+query2);
Statement s = d.createStatement(query+query2);
s.prepare();
s.execute();
s.close();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try {
if(d!=null)
{
d.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Resources