Esempio n. 1
0
  @Override
  public List<Word> getWords() {
    List<Word> wordList = new ArrayList<Word>();
    Db_Help dbhelper = new Db_Help(mContext);
    String query = "SELECT _id,vocab,pronunciation,meaning FROM tb_words;";
    ArrayList datatable = new ArrayList();
    try {
      datatable = dbhelper.getDataTable(query);

      int i = 0;
      while (datatable.size() > i) {
        HashMap tablerow = new HashMap();
        tablerow = (HashMap) datatable.get(i);
        Word obj =
            new Word(
                tablerow.get(tbWord.id).toString(),
                tablerow.get(tbWord.vocab).toString(),
                tablerow.get(tbWord.prounuciation).toString(),
                tablerow.get(tbWord.meaning).toString());

        wordList.add(obj);
        i++;
      }

    } catch (SQLiteException e) {
      Log.e("SQLITE_Exception", e.getMessage());
    }
    return wordList;
  }
  public boolean deleteCounter(String id, String type) throws SQLiteException {
    SQLiteDatabase database = getWritableDatabase();

    // if deleting a row that is added by the user
    if (type.equals("user")) {
      try {
        database.delete(USER_COUNTER_TABLE, "id=?", new String[] {id});
        database.close();
        return true;
      } catch (SQLiteException e) {
        e.printStackTrace();
      }
    }
    // else deleting a default row. Only hide default rows.
    else {
      // create new values
      ContentValues values = new ContentValues();
      values.put("visible", "false");

      try {
        // update the database with new values. (make rows disappear)
        database.update(DEFAULT_COUNTER_TABLE, values, "id=?", new String[] {id});
        database.close();
        return true;
      } catch (SQLiteException e) {
        e.printStackTrace();
      }
    }

    database.close();
    return false;
  }
Esempio n. 3
0
  private long insert(
      String className,
      String id,
      long triggerAtMillis,
      long intervalMillis,
      int repeatCount,
      boolean repeatMode) {

    ContentValues values = new ContentValues();
    values.put(ReminderDBHelper.JobsColumns.CLASS_NAME, className);
    if (id != null) values.put(ReminderDBHelper.JobsColumns.CUSTOM_ID, id);
    values.put(ReminderDBHelper.JobsColumns.TRIGGERTIME, triggerAtMillis);
    values.put(ReminderDBHelper.JobsColumns.INTERVALTIME, intervalMillis);
    values.put(ReminderDBHelper.JobsColumns.REPEATCOUNT, repeatCount);
    values.put(ReminderDBHelper.JobsColumns.REPEATMODE, repeatMode);

    long rowId = -1;
    synchronized (this) {
      SQLiteDatabase db = null;

      try {
        db = this.getWritableDatabase();
        rowId = db.insert(TABLE_NAME, null, values);
      } catch (SQLiteException e) {
        e.printStackTrace();
      }
    }
    return rowId;
  }
Esempio n. 4
0
  public List<ReminderItem> getAllReminders() {
    ArrayList<ReminderItem> alarmJobList = new ArrayList<ReminderItem>();

    ReminderItem alarmJob = null;
    SQLiteDatabase db = null;
    synchronized (this) {
      db = this.getWritableDatabase();

      try {
        Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null);
        if (cursor != null) {
          while (cursor.moveToNext()) {
            alarmJob = createAlarmJobFromCursor(cursor);
            if (alarmJob != null) {
              alarmJobList.add(alarmJob);
            }
          }
          cursor.close();
        } else {
          AIOLog.d(AIOConstant.TAG, "[getAlarmJobs]: Cursor is null.");
        }
      } catch (SQLiteException e) {
        e.printStackTrace();
      }
    }

    return alarmJobList;
  }
Esempio n. 5
0
  /* Insert new request into table 'request' */
  void insertRequest(int number) {

    // Log.i("PRIME", "Table : request : Inside insertRequest() : No -> "
    //		 										+ number);

    SQLiteDatabase db = this.getWritableDatabase();

    // ??
    String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

    // Log.i("PRIME", "DbHandler : insertRequest() "
    //		 				+ "howmany -> " + number);

    ContentValues values = new ContentValues();
    values.put("howmany", number);
    values.put("current_count", 0);
    values.put("is_complete", "N");
    values.put("created_time", timeStamp);
    values.put("tstamp", timeStamp);

    try {
      // Inserting Row
      db.insertOrThrow(TABLE_REQUEST, null, values);

    } catch (android.database.sqlite.SQLiteConstraintException e) {
      Log.e("PRIME", "insertRequest : SQLiteConstraintException:" + e.getMessage());
    } catch (android.database.sqlite.SQLiteException e) {
      Log.e("PRIME", "SQLiteException:" + e.getMessage());
    } catch (Exception e) {
      Log.e("PRIME", "Exception:" + e.getMessage());
    }

    db.close(); // Closing database connection
  }
Esempio n. 6
0
 // ------------------------------------------------------------------------------
 private void luu() {
   String name = edit_ten.getText().toString();
   int diemchoi = Integer.parseInt(text_diem.getText().toString());
   // Nếu chưa nhập tên thì yêu cầu nhập tên
   if (name.length() == 0 || name == null) {
     Toast.makeText(this, "Bạn chưa nhập tên.", Toast.LENGTH_LONG).show();
     return;
   }
   try {
     db.open();
     Cursor c = db.getAllRows();
     if (c.moveToPosition(9)) {
       String id = c.getString(c.getColumnIndex(Database.KEY_ROWID));
       int math = c.getInt(c.getColumnIndex(Database.KEY_DIEM));
       if (math < diemchoi) {
         db.updatePlayer(id, name, diemchoi);
         LinearLayout l = (LinearLayout) findViewById(R.id.linearLayout_diem);
         l.setVisibility(View.GONE);
         luu.setVisibility(View.GONE);
         xem_diem_cao.setVisibility(View.VISIBLE);
         xemdiemcao();
       }
     }
     c.close();
     db.close();
   } catch (SQLiteException e) {
     e.printStackTrace();
   }
 }
Esempio n. 7
0
  public void fillInitialDish() {
    String cooking =
        "Салатные листья замочить в холодной воде на 1 час, чтобы они стали свежими и хрустящими.\n"
            + "Белый хлеб очистить от корочки и порезать на кубики размером примерно 1 сантиметр, затем выложить на противень и подсушить в не слишком горячей духовке.\n"
            + "В глубокую сковороду налить растительное масло, положить измельченный чеснок. Как только кусочки потемнеют, снять их со сковороды и выложить в масло сухарики. Обжарить до золотистой корочки, выложить на бумажную салфетку для удаления лишнего масла.\n"
            + "Куриное филе натереть солью и обжарить до готовности, затем остудить и порезать тонкими пластинками.\n"
            + "Листья салата порвать руками, сыр нарезать тонкими пластинками. Помидоры черри разрезать на четыре части.\n"
            + "Выложить в салатник все ингредиенты, слегка встряхнуть, чтобы они перемешались, и сразу же подать на стол. Майонез подать отдельно, чтобы каждый едок мог добавлять его по вкусу.";
    if (db != null) {
      try {
        db.beginTransaction();
        ContentValues values = new ContentValues();
        values.put(Dish.COLUMN_TITLE, "Салат \"Цезарь\" с курицей и сухариками");
        values.put(Dish.COLUMN_COOKING, cooking);
        values.put(Dish.COLUMN_CELEBRATORY, true);
        values.put(Dish.COLUMN_KIND_ID, 3);
        db.insert(Dish.TABLE_NAME, null, values);
        db.setTransactionSuccessful();

        Log.i(LOG_TAG, "Dish table filled");
      } catch (SQLiteException e) {
        Log.e(LOG_TAG, e.getMessage());
      } finally {
        db.endTransaction();
      }
    }
  }
Esempio n. 8
0
 private List<String> checkAssets(IProgress progress) {
   String fv = Version.getFullVersion(context);
   if (!fv.equalsIgnoreCase(context.getSettings().PREVIOUS_INSTALLED_VERSION.get())) {
     File applicationDataDir = context.getAppPath(null);
     applicationDataDir.mkdirs();
     if (applicationDataDir.canWrite()) {
       try {
         progress.startTask(context.getString(R.string.installing_new_resources), -1);
         AssetManager assetManager = context.getAssets();
         boolean isFirstInstall =
             context.getSettings().PREVIOUS_INSTALLED_VERSION.get().equals("");
         unpackBundledAssets(assetManager, applicationDataDir, progress, isFirstInstall);
         context.getSettings().PREVIOUS_INSTALLED_VERSION.set(fv);
         copyRegionsBoundaries();
         copyPoiTypes();
         for (String internalStyle :
             context.getRendererRegistry().getInternalRenderers().keySet()) {
           File fl = context.getRendererRegistry().getFileForInternalStyle(internalStyle);
           if (fl.exists()) {
             context.getRendererRegistry().copyFileForInternalStyle(internalStyle);
           }
         }
       } catch (SQLiteException e) {
         log.error(e.getMessage(), e);
       } catch (IOException e) {
         log.error(e.getMessage(), e);
       } catch (XmlPullParserException e) {
         log.error(e.getMessage(), e);
       }
     }
   }
   return Collections.emptyList();
 }
    public Image getImageFromContentUri(Uri contentUri) {
      String[] cols = {MediaStore.Images.Media.DATA, MediaStore.Images.ImageColumns.ORIENTATION};

      // can post image
      Cursor cursor = getActivity().getContentResolver().query(contentUri, cols, null, null, null);

      Uri uri = null;
      int orientation = -1;

      try {
        if (cursor.moveToFirst()) {
          uri = Uri.parse(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)));
          orientation =
              cursor.getInt(cursor.getColumnIndex(MediaStore.Images.ImageColumns.ORIENTATION));
        }
      } catch (SQLiteException e) {
        e.printStackTrace();
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        if (cursor != null && !cursor.isClosed()) {
          cursor.close();
        }
      }

      return new Image(uri, orientation);
    }
  /*
   * loadAdminClasses (String table)
   * dbHelperAdminClasses is a helper class which mimics the SQL format of quizzes that is used
   * on our remote database.
   * Parameters: String username - 'username' should be the username of the currently logged user
   * Returns: Pair<ArrayList<String>, HashMap<String,List<String>>> - Returns
   *              1. An ArrayList representing the headers of each quiz topic
   *              2. A HashMap that that pairs header keys with a List of that header's children
   *          The header and child information is used in SubjectNavActivity to create
   *          an expandable list where the unexpanded tab is a quiz topic, and the expanded tabs
   *          are specific quizzes belonging to that topic.
   *
   */
  public Pair<ArrayList<String>, HashMap<String, List<String>>> loadAdminClasses(String username) {

    this.table = "`" + username + "Classes`";

    String selectionQuery = "SELECT * FROM " + this.table + " ORDER BY indexer";
    try {
      Cursor dataCurs = this.getWritableDatabase().rawQuery(selectionQuery, null);
      dataCurs.moveToFirst();
      HashMap<String, List<String>> headerChildPairs = new HashMap<>();
      ArrayList<String> headers = new ArrayList<>();
      do {
        List<String> children = new ArrayList<>();
        String header = dataCurs.getString(CLASS_INDEX); // Get Header
        headers.add(header);

        // Iterate starts after header and ends before indexer.
        for (int i = CLASS_INDEX + 1; i < dataCurs.getColumnCount() - 1; i++) {
          if (dataCurs.getString(i) != null) // If child isn't null, or "" add to list of child
          if (!dataCurs.getString(i).equals("")) children.add(dataCurs.getString(i));
        }
        headerChildPairs.put(header, children);
      } while (dataCurs.moveToNext());
      dataCurs.close();

      return new Pair<>(headers, headerChildPairs);
    } catch (SQLiteException e) {
      e.printStackTrace();
    }

    return null;
  }
Esempio n. 11
0
  private void saveAccelerometerDevice(Sensor acc) {
    Cursor accelInfo =
        getContentResolver().query(Accelerometer_Sensor.CONTENT_URI, null, null, null, null);
    if (accelInfo == null || !accelInfo.moveToFirst()) {
      ContentValues rowData = new ContentValues();
      rowData.put(
          Accelerometer_Sensor.DEVICE_ID,
          Aware.getSetting(getApplicationContext(), Aware_Preferences.DEVICE_ID));
      rowData.put(Accelerometer_Sensor.TIMESTAMP, System.currentTimeMillis());
      rowData.put(Accelerometer_Sensor.MAXIMUM_RANGE, acc.getMaximumRange());
      rowData.put(Accelerometer_Sensor.MINIMUM_DELAY, acc.getMinDelay());
      rowData.put(Accelerometer_Sensor.NAME, acc.getName());
      rowData.put(Accelerometer_Sensor.POWER_MA, acc.getPower());
      rowData.put(Accelerometer_Sensor.RESOLUTION, acc.getResolution());
      rowData.put(Accelerometer_Sensor.TYPE, acc.getType());
      rowData.put(Accelerometer_Sensor.VENDOR, acc.getVendor());
      rowData.put(Accelerometer_Sensor.VERSION, acc.getVersion());

      try {
        getContentResolver().insert(Accelerometer_Sensor.CONTENT_URI, rowData);

        Intent accel_dev = new Intent(ACTION_AWARE_ACCELEROMETER);
        accel_dev.putExtra(EXTRA_SENSOR, rowData);
        sendBroadcast(accel_dev);

        if (Aware.DEBUG) Log.d(TAG, "Accelerometer device:" + rowData.toString());
      } catch (SQLiteException e) {
        if (Aware.DEBUG) Log.d(TAG, e.getMessage());
      } catch (SQLException e) {
        if (Aware.DEBUG) Log.d(TAG, e.getMessage());
      }
    } else accelInfo.close();
  }
Esempio n. 12
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_chat);
    sInstance = this;
    textViewContactName = (TextView) findViewById(R.id.tv_contact_name_chat);
    editTextMessage = (EditText) findViewById(R.id.et_chat);
    buttonSend = (ImageButton) findViewById(R.id.button_chat_send);
    buttonSend.setOnClickListener(this);
    ListView bubbleList = (ListView) findViewById(R.id.lv_chat);

    Intent intent = getIntent();
    contactName = intent.getStringExtra("CONTACT_NAME");
    ipAddress = intent.getStringExtra("IP_ADDRESS");
    MessagesDatabase database = new MessagesDatabase(this);
    mContextUserTable = intent.getStringExtra("user_table");
    textViewContactName.setText(contactName);

    try {
      messages = database.getMessagesForContact(mContextUserTable);
    } catch (SQLiteException e) {
      e.printStackTrace();
      // Apparently no table exists.
    }

    adapter = new ChatArrayAdapter(this, R.layout.activity_chat_singlemessage, messages);
    bubbleList.setAdapter(adapter);
  }
Esempio n. 13
0
 @ChromeDevtoolsMethod
 public JsonRpcResult executeSQL(JsonRpcPeer peer, JSONObject params) {
   ExecuteSQLRequest request = mObjectMapper.convertValue(params, ExecuteSQLRequest.class);
   try {
     return mDatabasePeerManager.executeSQL(
         request.databaseId,
         request.query,
         new DatabasePeerManager.ExecuteResultHandler<ExecuteSQLResponse>() {
           @Override
           public ExecuteSQLResponse handleResult(Cursor result) throws SQLiteException {
             ExecuteSQLResponse response = new ExecuteSQLResponse();
             response.columnNames = Arrays.asList(result.getColumnNames());
             response.values = flattenRows(result, MAX_EXECUTE_RESULTS);
             return response;
           }
         });
   } catch (SQLiteException e) {
     Error error = new Error();
     error.code = 0;
     error.message = e.getMessage();
     ExecuteSQLResponse response = new ExecuteSQLResponse();
     response.sqlError = error;
     return response;
   }
 }
Esempio n. 14
0
 private void tryExecuteSql(SQLiteDatabase db, String sql) {
   try {
     db.execSQL(sql);
   } catch (SQLiteException ex) {
     Log.e("xrx-sql", ex.getMessage());
   }
   Log.d("xrx-sql", "sql exectue success: " + sql);
 }
 public static final void open(Context context) throws SQLException {
   dbHelper = new MyHelper(context);
   try {
     db = dbHelper.getWritableDatabase();
   } catch (SQLiteException e) {
     Log.w("POLS2", "ProjectsDbAdapter::getWritableDatabase error: " + e.getMessage());
   }
 }
Esempio n. 16
0
  private TodorooCursor<Task> constructCursor() {
    String tagName = null;
    if (getActiveTagData() != null) {
      tagName = getActiveTagData().getName();
    }

    Criterion tagsJoinCriterion =
        Criterion.and(
            Field.field(TAGS_METADATA_JOIN + "." + Metadata.KEY.name)
                .eq(TaskToTagMetadata.KEY), // $NON-NLS-1$
            Field.field(TAGS_METADATA_JOIN + "." + Metadata.DELETION_DATE.name).eq(0),
            Task.ID.eq(Field.field(TAGS_METADATA_JOIN + "." + Metadata.TASK.name)));
    if (tagName != null) {
      tagsJoinCriterion =
          Criterion.and(
              tagsJoinCriterion,
              Field.field(TAGS_METADATA_JOIN + "." + TaskToTagMetadata.TAG_NAME.name).neq(tagName));
    }

    // TODO: For now, we'll modify the query to join and include the things like tag data here.
    // Eventually, we might consider restructuring things so that this query is constructed
    // elsewhere.
    String joinedQuery =
        Join.left(Metadata.TABLE.as(TAGS_METADATA_JOIN), tagsJoinCriterion)
                .toString() //$NON-NLS-1$
            + Join.left(
                TaskAttachment.TABLE.as(FILE_METADATA_JOIN),
                Task.UUID.eq(Field.field(FILE_METADATA_JOIN + "." + TaskAttachment.TASK_UUID.name)))
            + filter.getSqlQuery();

    sqlQueryTemplate.set(SortHelper.adjustQueryForFlagsAndSort(joinedQuery, sortFlags, sortSort));

    String groupedQuery;
    if (sqlQueryTemplate.get().contains("GROUP BY")) {
      groupedQuery = sqlQueryTemplate.get();
    } else if (sqlQueryTemplate.get().contains("ORDER BY")) // $NON-NLS-1$
    {
      groupedQuery =
          sqlQueryTemplate
              .get()
              .replace("ORDER BY", "GROUP BY " + Task.ID + " ORDER BY"); // $NON-NLS-1$
    } else {
      groupedQuery = sqlQueryTemplate.get() + " GROUP BY " + Task.ID;
    }
    sqlQueryTemplate.set(groupedQuery);

    // Peform query
    try {
      return taskService.fetchFiltered(sqlQueryTemplate.get(), null, taskProperties());
    } catch (SQLiteException e) {
      // We don't show this error anymore--seems like this can get triggered
      // by a strange bug, but there seems to not be any negative side effect.
      // For now, we'll suppress the error
      // See http://astrid.com/home#tags-7tsoi/task-1119pk
      log.error(e.getMessage(), e);
      return null;
    }
  }
Esempio n. 17
0
 public static boolean requery(Context context, Cursor cursor) {
   try {
     return cursor.requery();
   } catch (SQLiteException e) {
     LogUtil.e("Catch a SQLiteException when requery: ", e.getMessage());
     checkSQLiteException(context, e);
     return false;
   }
 }
  // DEBUG ONLY :: Remove in release
  public void deleteTable() {

    try {
      db = appCtx.openOrCreateDatabase(databaseName, Context.MODE_PRIVATE, null);
      db.delete(tableName, null, null);
      db.close();
    } catch (SQLiteException exception) {
      Log.e("deleteTable", exception.getMessage());
    }
  }
Esempio n. 19
0
 public static Uri insert(
     Context context, ContentResolver resolver, Uri uri, ContentValues values) {
   try {
     return resolver.insert(uri, values);
   } catch (SQLiteException e) {
     LogUtil.e("Catch a SQLiteException when insert: ", e.getMessage());
     checkSQLiteException(context, e);
     return null;
   }
 }
Esempio n. 20
0
 public static int delete(
     Context context, ContentResolver resolver, Uri uri, String where, String[] selectionArgs) {
   try {
     return resolver.delete(uri, where, selectionArgs);
   } catch (SQLiteException e) {
     LogUtil.e("Catch a SQLiteException when delete: ", e.getMessage());
     checkSQLiteException(context, e);
     return -1;
   }
 }
Esempio n. 21
0
  public void insertDayMaxSteps(int y, int m, int d, int s, float dis, float cal, long st) {

    Cursor c = queryDayAll(y, m, d);
    if (c != null) {
      c.moveToLast();
    } else {
      return;
    }

    int lap, year, month, day, hour, minute, lapsteps, steps, pace, achievement;
    float lapdistance, distance, lapcalories, calories, speed;
    long lapsteptime, steptime;

    year = y;
    month = m;
    day = d;
    hour = 23;
    minute = 0;
    lap = 0;
    lapsteps = 0;
    lapdistance = 0;
    lapcalories = 0;
    lapsteptime = 0;
    steps = s;
    distance = dis;
    calories = cal;
    speed = 0;
    pace = 0;
    steptime = st;
    achievement = 0;

    ContentValues newTaskValue = new ContentValues();
    try {
      newTaskValue.put(Constants.KEY_LAP, lap);
      newTaskValue.put(Constants.KEY_YEAR, year);
      newTaskValue.put(Constants.KEY_MONTH, month); // month[0-11]
      newTaskValue.put(Constants.KEY_DAY, day);
      newTaskValue.put(Constants.KEY_HOUR, hour);
      newTaskValue.put(Constants.KEY_MINUTE, minute);
      newTaskValue.put(Constants.KEY_LAPSTEPS, lapsteps);
      newTaskValue.put(Constants.KEY_LAPDISTANCE, lapdistance);
      newTaskValue.put(Constants.KEY_LAPCALORIES, lapcalories);
      newTaskValue.put(Constants.KEY_LAPSTEPTIME, lapsteptime);
      newTaskValue.put(Constants.KEY_STEPS, steps);
      newTaskValue.put(Constants.KEY_DISTANCE, distance);
      newTaskValue.put(Constants.KEY_CALORIES, calories);
      newTaskValue.put(Constants.KEY_SPEED, speed);
      newTaskValue.put(Constants.KEY_PACE, pace);
      newTaskValue.put(Constants.KEY_STEPTIME, steptime);
      newTaskValue.put(Constants.KEY_ACHIEVEMENT, achievement);
      mDB.insert(Constants.TABLE_NAME, null, newTaskValue);
    } catch (SQLiteException ex) {
      ex.printStackTrace();
    }
  }
Esempio n. 22
0
  public boolean removeMovieCategories(String id) {
    try {
      String where = MOVIE_ID + " = ?";
      String[] whereArgs = {id};

      return mDb.delete(TABLE_NAME, where, whereArgs) > 0;
    } catch (SQLiteException e) {
      Log.v("Insert into database failed", e.getMessage());
      return false;
    }
  }
Esempio n. 23
0
  @Override
  public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    Log.v("open onCreate", "Creating all the tables");

    try {

      db.execSQL(CREATE_TABLE1);
    } catch (SQLiteException ex) {
      Log.v("open exception caught", ex.getMessage());
    }
  }
 public boolean updateQuery(ContentValues values, String whereClause, String[] whereArgs) {
   int numRows = 0;
   try {
     db = appCtx.openOrCreateDatabase(databaseName, Context.MODE_PRIVATE, null);
     numRows = db.update(tableName, values, whereClause, whereArgs);
     db.close();
   } catch (SQLiteException exception) {
     Log.e(
         "NewsPaperTableHandler::updateQuery", "Update checkbox failed" + exception.getMessage());
   }
   return numRows == 1 ? true : false;
 }
 private SQLiteDatabase returnDatabase() {
   try {
     SQLiteDatabase db =
         SQLiteDatabase.openDatabase(
             mDatabasePath + "/" + mName, mFactory, SQLiteDatabase.OPEN_READWRITE);
     Log.i(TAG, "successfully opened database " + mName);
     return db;
   } catch (SQLiteException e) {
     Log.w(TAG, "could not open database " + mName + " - " + e.getMessage());
     return null;
   }
 }
Esempio n. 26
0
  /**
   * Open database for writing
   *
   * @return true if db is open and writable, false otherwise
   * @exception ex caught SQLiteException if failure to open writable database, will open readable
   *     if fails
   */
  public boolean open() {
    try {
      db = dbhelper.getWritableDatabase();
    } catch (SQLiteException ex) {
      if (LOG_ON) Log.e("Open database exception caught", ex.getMessage());
      db = dbhelper.getReadableDatabase();
      return false;
    }

    // enforce referential integrity
    db.execSQL("PRAGMA foreign_keys=ON;");
    return true;
  }
Esempio n. 27
0
 /**
  * checking the database Availability based on Availability copying database to the device data
  *
  * @return true (if Available)
  */
 private boolean checkDataBase() {
   SQLiteDatabase checkDB = null;
   try {
     String myPath = DB_PATH + DB_NAME;
     checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
   } catch (SQLiteException e) {
     Log.e(TAG, "Error is" + e.toString());
   }
   if (checkDB != null) {
     checkDB.close();
   }
   return checkDB != null ? true : false;
 }
  public boolean checkDataBase(String myPath) {
    SQLiteDatabase checkDB = null;
    try {
      checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
    } catch (SQLiteException e) {
      // database does't exist yet.
      Log.e(TAG, "database in " + myPath + " does't exist yet:" + e.getMessage());
    }
    if (checkDB != null) {
      checkDB.close();
    }

    return checkDB != null ? true : false;
  }
  public ArrayList<ArrayList<Feed>> getCategoriesForNewsPapers(ArrayList<String> newsPaperNames) {
    Cursor result = null;
    ArrayList<ArrayList<Feed>> categories = new ArrayList<ArrayList<Feed>>();
    ArrayList<Feed> category = new ArrayList<Feed>();

    try {
      db = appCtx.openOrCreateDatabase(databaseName, Context.MODE_PRIVATE, null);

      for (String newsPaper : newsPaperNames) {
        result =
            db.query(
                tableName,
                new String[] {"Category", "FeedURL", "Subscribed"},
                "NewsPaperName=?",
                new String[] {newsPaper},
                null,
                null,
                null);
        result.moveToFirst();
        Feed feed = new Feed();

        int categoryIndex = result.getColumnIndex("Category");
        int subscribedIndex = result.getColumnIndex("Subscribed");
        int feedUrlIndex = result.getColumnIndex("FeedURL");
        // Add to corresponding array list
        while (!result.isAfterLast()) {
          feed.setNewsPaper(newsPaper);
          feed.setCategory(result.getString(categoryIndex));
          feed.setFeedURL(result.getString(feedUrlIndex));
          feed.setSubscribed(result.getInt(subscribedIndex));

          category.add(feed);
          result.moveToNext();
        }
        categories.add(category);
        category = new ArrayList<Feed>();
      }
      result.close();
      db.close();

    } catch (SQLiteException exception) {
      Log.e(
          "NewsPaperTableHandler::getCategoriesForNewsPapers",
          "Categories could not be got " + exception.getMessage());
    } catch (Exception exception) {
      Log.e("NewsPaperTableHandler::getCategoriesForNewsPapers", exception.getMessage());
    }

    return categories;
  }
  private boolean checkDataBase() {
    SQLiteDatabase mCheckDataBase = null;
    try {
      String myPath = DB_PATH + DB_NAME;
      mCheckDataBase =
          SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
    } catch (SQLiteException mSQLiteException) {
      Log.e(TAG, "DatabaseNotFound " + mSQLiteException.toString());
    }

    if (mCheckDataBase != null) {
      mCheckDataBase.close();
    }
    return mCheckDataBase != null;
  }