Example usage for android.database.sqlite SQLiteDatabase rawQuery

List of usage examples for android.database.sqlite SQLiteDatabase rawQuery

Introduction

In this page you can find the example usage for android.database.sqlite SQLiteDatabase rawQuery.

Prototype

public Cursor rawQuery(String sql, String[] selectionArgs) 

Source Link

Document

Runs the provided SQL and returns a Cursor over the result set.

Usage

From source file:org.rapidandroid.activity.chart.message.MessageDataBroker.java

private JSONGraphData chartMessagesPerHour() {
    JSONObject result = new JSONObject();
    SQLiteDatabase db = rawDB.getReadableDatabase();

    String rawQuery = "select strftime('%H',time), count(*) from rapidandroid_message group by strftime('%H',time) order by strftime('%H',time)";

    // the string value is column 0
    // the magnitude is column 1

    Cursor cr = db.rawQuery(rawQuery, null);
    int barCount = cr.getCount();

    if (barCount != 0) {
        String[] xVals = new String[barCount];
        int[] yVals = new int[barCount];
        cr.moveToFirst();//from  w  ww.j a v  a2 s.  co m
        int i = 0;
        do {
            xVals[i] = cr.getString(0);
            yVals[i] = cr.getInt(1);
            i++;
        } while (cr.moveToNext());

        try {
            result.put("label", "Messages");
            result.put("data", prepareData(yVals));
            result.put("bars", getShowTrue());

        } catch (Exception ex) {

        }
        cr.close();
        JSONArray values = new JSONArray();
        values.put(result);
        return new JSONGraphData(values, new JSONObject());
    }
    // either there was no data or something bad happened
    return new JSONGraphData(getEmptyData(), new JSONObject());
}

From source file:com.yammy.meter.MainActivity.java

private void getVehVal() {
    /**//from w  ww .  ja v  a  2 s  . c om
      * get value from saved preferences
      */
    try {
        prefs = getSharedPreferences(prefName, MODE_PRIVATE);
        nopol.setText(prefs.getString("nopol", null));
        idkendaraan = Integer.parseInt(prefs.getString("idkendaraan", null));
        start.setEnabled(true);
    } catch (Exception e) {
        idkendaraan = prefs.getInt("idkendaraan", 0);
        start.setEnabled(false);
    }

    dbHelper = new MySQLHelper(getApplicationContext());
    SQLiteDatabase jdb = dbHelper.getReadableDatabase();
    try {
        Cursor cursor = jdb.rawQuery("SELECT SUM(jarak) FROM perjalanan WHERE id_kendaraan=" + idkendaraan,
                null);
        if (cursor.moveToFirst()) {
            try {
                totalJarakDitempuhKendaraan = Double.parseDouble(String.format("%.2f", cursor.getString(0)));
            } catch (NumberFormatException e) {
                totalJarakDitempuhKendaraan = Double.parseDouble(cursor.getString(0));
            } catch (Exception e) {
                totalJarakDitempuhKendaraan = cursor.getDouble(0);
            }
        } else {
            totalJarakDitempuhKendaraan = 0.0;
        }
        Toast.makeText(getBaseContext(), "Sudah ditempuh : " + totalJarakDitempuhKendaraan + " m",
                Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(getBaseContext(), "Belum pernah melakukan perjalanan", Toast.LENGTH_SHORT).show();
    }
    jdb.close();
}

From source file:com.denimgroup.android.training.pandemobium.stocktrader.ManageTipsActivity.java

private void doSendTipData(String symbol) {
    StockDatabase dbHelper = new StockDatabase(this.getApplicationContext());
    SQLiteDatabase db = dbHelper.openDatabase();

    StringBuilder sb = new StringBuilder();

    String sql = "SELECT * FROM tip WHERE symbol = '" + symbol + "'";

    Log.d("ManageTipsActivity", "SQL to execute is: " + sql);

    Cursor tips = db.rawQuery(sql, null);

    //   Take all the data returned and package it up for sending
    int numTips = tips.getCount();
    Log.d("ManageTipsActivity", "Got " + numTips + " tips to send");
    tips.moveToFirst();//w w w. ja  v  a 2 s .c  o  m
    for (int i = 0; i < numTips; i++) {
        sb.append("TIP");
        sb.append(i);
        sb.append(":");
        int columnCount = tips.getColumnCount();
        Log.d("ManageTipsActivity", "Tip " + i + " has " + columnCount + " columns");
        for (int j = 0; j < columnCount; j++) {
            if (j > 0) {
                sb.append("&");
            }
            sb.append(tips.getColumnName(j));
            sb.append("=");
            sb.append(tips.getString(j));
        }
        tips.moveToNext();
        sb.append("\n");
    }

    tips.close();
    db.close();

    Log.d("ManageTipsActivity", "Tip data to post is: " + sb.toString());

    String accountId = AccountUtils.retrieveAccountId(getApplicationContext());
    String tradeServiceUrl = getResources().getString(R.string.tip_service);

    String fullUrl = tradeServiceUrl + "?method=submitTips&id=" + accountId;

    Log.d("ManageTipsActivity", "Full URL for tip sending is: " + fullUrl);

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(fullUrl);
    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    pairs.add(new BasicNameValuePair("tipData", sb.toString()));
    try {
        post.setEntity(new UrlEncodedFormEntity(pairs));
        HttpResponse response = client.execute(post);
        tvTipStatus.setText("Tip data for " + etSymbol.getText().toString() + " sent!");

    } catch (Exception e) {
        Log.e("ManageTipsActivity", "Error when encoding or sending tip data: " + e.toString());
        e.printStackTrace();
    }
}

From source file:heartware.com.heartware_master.DBAdapter.java

public HashMap<String, String> getProfilePassword(String id) {
    HashMap<String, String> profileMap = new HashMap<String, String>();
    SQLiteDatabase database = this.getReadableDatabase();
    String selectQuery = "SELECT " + PASSWORD + " FROM " + PROFILES_TABLE + " WHERE " + PROFILE_ID + "='" + id
            + "'";
    Cursor cursor = database.rawQuery(selectQuery, null);

    if (cursor.moveToFirst()) {
        do {/*from  w w  w. j  av  a  2s.  c  o  m*/
            profileMap.put(PASSWORD, cursor.getString(0));
        } while (cursor.moveToNext());
    }
    return profileMap;
}

From source file:com.futureplatforms.kirin.extensions.databases.DatabasesBackend.java

protected Cursor rawQuery(SQLiteDatabase db, String sql, String[] params) {
    return db.rawQuery(sql, params);
}

From source file:com.google.zxing.client.android.history.HistoryManager.java

public JSONArray listarTodosQr() {
    JSONArray listQr = new JSONArray();
    SQLiteOpenHelper helper = new DBHelper(activity);
    SQLiteDatabase db = null;
    db = helper.getWritableDatabase();//w w  w  . j  a  v a 2s .c o  m
    Cursor c = db.rawQuery(
            "SELECT " + DBHelper.TEXT_COL + ", " + DBHelper.TIMESTAMP_COL + " FROM " + DBHelper.TABLE_NAME,
            null);
    if (c != null) {
        c.moveToFirst();
        do {
            String data = c.getString(c.getColumnIndex(DBHelper.TIMESTAMP_COL));
            String incri = c.getString(c.getColumnIndex(DBHelper.TEXT_COL));
            JSONObject inscritos = new JSONObject();
            try {
                inscritos.put("id_inscrito", incri.toString());
                inscritos.put("data_credenciado", data.toString());
                listQr.put(inscritos);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } while (c.moveToNext());
    }
    c.close();
    return listQr;
}

From source file:com.shalzz.attendance.DatabaseHandler.java

/**
 * Get All Subjects/*from w  ww.  j  av a2  s .co  m*/
 * @return subjectList
 */
public List<Subject> getAllSubjects(AsyncTaskLoader callback, String filter) {
    List<Subject> subjectList = new ArrayList<>();
    SQLiteDatabase db = getReadableDatabase();
    Cursor cursor;

    if (filter != null && !filter.isEmpty()) {
        cursor = db.rawQuery(Subject.SELECT_LIKE_NAME, new String[] { '%' + filter + '%' });
    } else {
        cursor = db.rawQuery(Subject.SELECT_ALL, null);
    }
    try {
        while (cursor.moveToNext()) {

            // Check isLoadInBackgroundCanceled() to cancel out early
            if (callback != null && callback.isLoadInBackgroundCanceled()) {
                break;
            }

            // get absent dates from another table and add in the subject object
            int id = cursor.getInt(cursor.getColumnIndexOrThrow(Subject.ID));
            ArrayList<Date> dates = new ArrayList<>();
            Cursor dateCursor = db.rawQuery(AbsentDate.SELECT_BY_ID, new String[] { String.valueOf(id) });
            while (dateCursor.moveToNext()) {
                dates.add(AbsentDate.MAPPER.map(dateCursor).absent_date());
            }

            dateCursor.close();
            subjectList.add(Subject.MAPPER.map(cursor).withAbsentDates(dates));
        }
    } finally {
        cursor.close();
    }

    return subjectList;
}

From source file:com.google.zxing.client.android.history.HistoryManager.java

public boolean historyIsVazio() {
    SQLiteOpenHelper helper = new DBHelper(activity);
    SQLiteDatabase db = null;
    Cursor c = null;/* w w w . j a va 2s .com*/
    db = helper.getWritableDatabase();
    c = db.rawQuery("SELECT count(" + DBHelper.ID_COL + ") FROM " + DBHelper.TABLE_NAME, null);
    if (c != null && c.moveToFirst() && c.getInt(0) > 0) {
        Log.i("Script: ", "Contem dados no histrico!");
        return true;
    }
    Log.i("Script: ", "No contem nunhum dado no histrico!");
    return false;
}

From source file:com.google.zxing.client.android.history.HistoryManager.java

public boolean buscarDado(String dado) {
    SQLiteOpenHelper helper = new DBHelper(activity);
    SQLiteDatabase db = null;
    Cursor c = null;/*w w  w  . j  ava 2  s . co m*/
    db = helper.getWritableDatabase();
    c = db.rawQuery("SELECT " + DBHelper.ID_INSCRITOS + " FROM " + DBHelper.INSCRITOS + " WHERE "
            + DBHelper.ID_INSCRITOS + " = '" + dado + "'", null);
    if (c != null && c.getCount() > 0) {
        c.moveToFirst();
        Log.i("Script: ", "Busca encontrada! " + dado);
        c.close();
        return true;
    } else {
        Log.i("Script: ", "Busca no encontrada! " + dado);
        c.close();
        return false;
    }
}

From source file:com.acrylicgoat.devchat.MainActivity.java

private String getYesterday(String owner) {
    //Log.d("MainActivity", "getYesterday() called: " + owner);
    StringBuilder sb = new StringBuilder();
    String results = "";
    sb.append("select notes_note, date(notes_date) as notes_date from notes where notes_owner='");
    sb.append(currentOwner);/*from www. j  a v a2  s  .  c o m*/

    sb.append("' and date(notes_date)<=date('now','localtime','-1 day') order by date(notes_date) desc");

    DatabaseHelper dbHelper = new DatabaseHelper(this.getApplicationContext());
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    cursor = db.rawQuery(sb.toString(), null);
    if (cursor.getCount() > 0) {
        cursor.moveToNext();
        int notesColumn = cursor.getColumnIndex(Notes.NOTE);
        int dateColumn = cursor.getColumnIndex(Notes.DATE);
        //Log.d("MainActivity.getYesterday()", "notesColumn: " + notesColumn);
        results = cursor.getString(dateColumn) + " - " + cursor.getString(notesColumn);
    }

    cursor.close();
    db.close();
    return results;
}