Ask Question

Name:
Title:
Your Question:

Answer Question

Name:
Your Answer:
User Submitted Source Code!


Description:
  SQLPlugin.java
Language: JAVA
Code:
package com.tcs.plugin.database;


import net.rim.device.api.database.Cursor;
import net.rim.device.api.database.DataTypeException;
import net.rim.device.api.database.Database;
import net.rim.device.api.database.DatabaseException;
import net.rim.device.api.database.DatabaseFactory;
import net.rim.device.api.database.DatabaseIOException;
import net.rim.device.api.database.DatabasePathException;
import net.rim.device.api.database.Row;
import net.rim.device.api.database.Statement;
import net.rim.device.api.io.MalformedURIException;
import net.rim.device.api.io.URI;
import net.rim.device.api.system.ControlledAccessException;

import org.apache.cordova.api;

import org.json.me.JSONArray;
import org.json.me.JSONException;
import org.json.me.JSONObject;

import com.phonegap.api.PluginResult;

public class SQLPlugin extends Plugin{
     
     private Database myDb = null; // Database object
     
     public PluginResult execute(String action, JSONArray args, String callbackId) {
          PluginResult.Status status = PluginResult.Status.OK;
          String result = "";
          try {
               if (action.equals("open")) {
                    
                    openDatabase(args.getString(0));               
                    
               } else if (action.equals("executeSqlBatch")) {
                    String[] queries = null;
                    String[] queryIDs = null;
                    String trans_id = null;                         
                    JSONArray[] jsonparams = null;
                    
                    if (args.isNull(0)) {
                         queries = new String[0];
                    } else {
                         int len = args.length();
                         queries = new String[len];
                         queryIDs = new String[len];
                         jsonparams = new JSONArray[len];

                         for (int i = 0; i < len; i++) 
                         {
                              JSONObject object = args.getJSONObject(i);
                              queries[i] = object.getString("query");
                              queryIDs[i] = object.getString("query_id");
                              trans_id = object.getString("trans_id");
                              jsonparams[i]      = object.getJSONArray("params");
                         }
                    }
                    if(trans_id != null)
                         executeSqlBatch(queries, jsonparams, queryIDs, trans_id);
                    else
                         System.out.println("error"+ "null trans_id");
               }
               return new PluginResult(status, result);
          } catch (JSONException e) {
               return new PluginResult(PluginResult.Status.JSONEXCEPTION);
          } catch (ControlledAccessException e) {
               System.out.println("error : "+e.getMessage());                              
               return new PluginResult(PluginResult.Status.ERROR);
          } catch (DatabaseIOException e) {
               System.out.println("error : "+e.getMessage());
               return new PluginResult(PluginResult.Status.ERROR);
          } catch (DatabasePathException e) {
               System.out.println("error : "+e.getMessage());
               return new PluginResult(PluginResult.Status.ERROR);
          } catch (IllegalArgumentException e) {
               System.out.println("error : "+e.getMessage());
               return new PluginResult(PluginResult.Status.ERROR);
          } catch (MalformedURIException e) {
               System.out.println("error : "+e.getMessage());
               return new PluginResult(PluginResult.Status.ERROR);
          }          
          
     }
     
     
     public boolean isSynch(String action) {
          return true;
     }

     
     @Override
     public void onDestroy() {
          if (myDb != null) {
               try {
                    myDb.close();
               } catch (DatabaseIOException e) {
                    e.printStackTrace();
               }
               myDb = null;
          }
     }

     
     public void openDatabase(String db) throws ControlledAccessException, DatabaseIOException, DatabasePathException, IllegalArgumentException, MalformedURIException {
          
          if (myDb != null) {
               try {
                    myDb.close();
               } catch (Exception e) {
                    e.printStackTrace();
               }
               myDb = null;
          }
          URI uri = URI.create(db);
          myDb = DatabaseFactory.openOrCreate(uri);
     }

     public void executeSqlBatch(String[] queryarr, JSONArray[] jsonparams, String[] queryIDs, String tx_id) throws ControlledAccessException, IllegalArgumentException, MalformedURIException {
          try {
               
               myDb.beginTransaction();
               
               int len = queryarr.length;
               for (int i = 0; i < len; i++) {
                    String query = queryarr[i];
                    String query_id = queryIDs[i];
                    if (query.toLowerCase().startsWith("insert") && jsonparams != null) {
                         
                         Statement myStatement = myDb.createStatement(query);
                         myStatement.prepare();
                         for (int j = 0; j < jsonparams[i].length(); j++) {
                              if (jsonparams[i].get(j) instanceof Float || jsonparams[i].get(j) instanceof Double ) {
                                   myStatement.bind(j + 1, jsonparams[i].getDouble(j));
                              } else if (jsonparams[i].get(j) instanceof Long) {
                                   myStatement.bind(j + 1, jsonparams[i].getLong(j));
                              } else {
                                   myStatement.bind(j + 1, jsonparams[i].getString(j));
                              }
                         }
                         
                         myStatement.execute();
                         

                         String result = "{'insertId':'0'}";
                         /*sendJavascript("SQLitePluginTransaction.queryCompleteCallback('" + tx_id + "','" + query_id + "', " + result + ");");*/
                    } else {
                         
                         
                         Statement statement = myDb.createStatement(query);
                         statement.prepare();     
                         
                         String[] params = null;

                         if (jsonparams != null) {
                              params = new String[jsonparams[i].length()];

                              for (int j = 0; j < jsonparams[i].length(); j++) {
                                   params[j] = jsonparams[i].getString(j);
                                   if(params[j] == "null") // XXX better check
                                        params[j] = "";
                              }
                              
                              for (int j = 0; j < params.length; j++) {                              
                                   statement.bind(j + 1, jsonparams[i].getString(j));                              
                              }
                         }
                         
                         Cursor myCursor = statement.getCursor();

                         processResults(myCursor, query_id, tx_id);
                         myCursor.close();
                         statement.close();
                    }
               }
               myDb.commitTransaction();
          }
          catch (DatabaseException ex) {
               ex.printStackTrace();
               System.out.println("executeSqlBatch: "+ "SQLitePlugin.executeSql(): Error=" +  ex.getMessage());
               /*sendJavascript("SQLitePluginTransaction.txErrorCallback('" + tx_id + "', '"+ex.getMessage()+"');");*/
          } catch (JSONException ex) {
               ex.printStackTrace();
               System.out.println("executeSqlBatch : SQLitePlugin.executeSql(): Error=" +  ex.getMessage());
               /*sendJavascript("SQLitePluginTransaction.txErrorCallback('" + tx_id + "', '"+ex.getMessage()+"');");*/
          } catch (DataTypeException e) {
               System.out.println("executeSqlBatch : SQLitePlugin.executeSql(): Error=" +  e.getMessage());
               /*sendJavascript("SQLitePluginTransaction.txErrorCallback('" + tx_id + "', '"+ex.getMessage()+"');");*/
          }
          finally {
               
               System.out.println("executeSqlBatch: "+tx_id);
               /*sendJavascript("SQLitePluginTransaction.txCompleteCallback('" + tx_id + "');");*/
          }
     }

     
     public void processResults(Cursor cur, String query_id, String tx_id) throws DatabaseException, DataTypeException {

          String result = "[]";
          if (!cur.isEmpty()) {
               
               JSONArray fullresult = new JSONArray();               
               String [] columnNames = cur.getRow().getColumnNames();

               do {
                    JSONObject rowObject = new JSONObject();
                    try {

                         Row r = cur.getRow();
                         for (int i = 0; i < columnNames.length; i++) {
                              rowObject.put(columnNames[i], r.getObject(i));
                         }
                         fullresult.put(rowObject);

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

               } while (cur.next());

               result = fullresult.toString();
               System.out.println("QUERY RESULT: "+result);
          }
          /*if(query_id.length() > 0)
               sendJavascript(" SQLitePluginTransaction.queryCompleteCallback('" + tx_id + "','" + query_id + "', " + result + ");");*/

     }
}
Comments: