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:com.snt.bt.recon.database.DBHandler.java

/**
 * Get all from a table and return a list
 * @return/*from  ww  w  .j a v  a2 s.  co m*/
 */
public <T> List<T> getAll(Class<T> cl) throws InstantiationException, IllegalAccessException {
    T inst = cl.newInstance();
    List<T> list = new ArrayList<T>();

    // Select All Query
    String selectQuery;
    Cursor cursor;
    SQLiteDatabase db = this.getWritableDatabase();
    if (inst instanceof Trip) {
        // Select All Query
        selectQuery = "SELECT * FROM " + TABLE_TRIPS;
        cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Trip trip = new Trip();
                trip.setSessionId(UUID.fromString(cursor.getString(0)));
                trip.setImei(cursor.getString(1));
                trip.setTransport(cursor.getString(2));

                trip.setTimestampStart(cursor.getString(3));
                trip.setTimestampEnd(cursor.getString(4));
                trip.setAppVersion(cursor.getString(5));
                trip.setUploadStatus(cursor.getString(6));
                // Adding contact to list
                list.add((T) trip);
            } while (cursor.moveToNext());
        }
        cursor.close();

    } else if (inst instanceof GPSLocation) {
        // Select All Query
        selectQuery = "SELECT * FROM " + TABLE_LOCATIONS;
        cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                GPSLocation location = new GPSLocation();
                location.setLocationId(UUID.fromString(cursor.getString(0)));
                location.setSessionId(UUID.fromString(cursor.getString(1)));
                location.setTimestamp(cursor.getString(2));
                location.setLatitude(cursor.getFloat(3));
                location.setLongitude(cursor.getFloat(4));
                location.setSpeed(cursor.getFloat(5));
                location.setBearing(cursor.getFloat(6));
                location.setAltitude(cursor.getFloat(7));
                location.setAccuracy(cursor.getFloat(8));
                location.setUploadStatus(cursor.getString(9));

                // Adding contact to list
                list.add((T) location);
            } while (cursor.moveToNext());
        }
        cursor.close();

    } else if (inst instanceof BluetoothClassicEntry) {
        // Select All Query
        selectQuery = "SELECT * FROM " + TABLE_BC;
        cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                BluetoothClassicEntry bc_entry = new BluetoothClassicEntry();
                bc_entry.setSessionId(UUID.fromString(cursor.getString(1)));//START FROM 1 SINCE 0 is ID
                bc_entry.setLocationId(UUID.fromString(cursor.getString(2)));
                bc_entry.setTimestamp(cursor.getString(3));
                bc_entry.setMac(cursor.getString(4));
                bc_entry.setType(cursor.getInt(5));
                bc_entry.setRssi(cursor.getInt(6));
                bc_entry.setDeviceName(cursor.getString(7));
                bc_entry.setBcClass(cursor.getString(8));
                bc_entry.setUploadStatus(cursor.getString(9));

                // Adding contact to list
                list.add((T) bc_entry);
            } while (cursor.moveToNext());
        }
        cursor.close();

    } else if (inst instanceof BluetoothLowEnergyEntry) {
        // Select All Query
        selectQuery = "SELECT * FROM " + TABLE_BLE;
        cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                BluetoothLowEnergyEntry ble_entry = new BluetoothLowEnergyEntry();
                ble_entry.setSessionId(UUID.fromString(cursor.getString(1)));//START FROM 1 SINCE 0 is ID
                ble_entry.setLocationId(UUID.fromString(cursor.getString(2)));
                ble_entry.setTimestamp(cursor.getString(3));
                ble_entry.setMac(cursor.getString(4));
                ble_entry.setRssi(cursor.getInt(5));
                ble_entry.setDeviceName(cursor.getString(6));
                ble_entry.setBleAdvData(cursor.getString(7));
                ble_entry.setUploadStatus(cursor.getString(8));

                // Adding contact to list
                list.add((T) ble_entry);
            } while (cursor.moveToNext());
        }
        cursor.close();

    }

    db.close();

    // return  list
    return list;
}

From source file:com.android.quicksearchbox.ShortcutRepositoryImplLog.java

private boolean hasHistory(SQLiteDatabase db) {
    Cursor cursor = db.rawQuery(HAS_HISTORY_QUERY, null);
    try {/*from   ww w  . ja v  a2 s.co m*/
        if (DBG)
            Log.d(TAG, "hasHistory(): cursor=" + cursor);
        return cursor != null && cursor.getCount() > 0;
    } finally {
        if (cursor != null)
            cursor.close();
    }
}

From source file:ru.orangesoftware.financisto2.db.MyEntityManager.java

public void deleteBudget(long id) {
    SQLiteDatabase db = db();
    Budget b = load(Budget.class, id);
    writeDeleteLog(BUDGET_TABLE, b.remoteKey);
    db.delete(BUDGET_TABLE, "_id=?", new String[] { String.valueOf(id) });
    String sql = "select remote_key from " + BUDGET_TABLE + " where parent_budget_id=" + id + "";
    Cursor cursorCursor = db.rawQuery(sql, null);
    if (cursorCursor.moveToFirst()) {
        do {/*from   w w  w  .  jav a 2 s  .co  m*/
            String rKey = cursorCursor.getString(0);
            writeDeleteLog(BUDGET_TABLE, rKey);
        } while (cursorCursor.moveToNext());
    }
    cursorCursor.close();
    db.delete(BUDGET_TABLE, "parent_budget_id=?", new String[] { String.valueOf(id) });
}

From source file:com.android.quicksearchbox.ShortcutRepositoryImplLog.java

/**
 * Returns the source ranking for sources with a minimum number of clicks.
 *
 * @param minClicks The minimum number of clicks a source must have.
 * @return The list of sources, ranked by total clicks.
 *///w  ww. jav  a2s.  co m
Map<String, Integer> getCorpusScores(int minClicks) {
    SQLiteDatabase db = mOpenHelper.getReadableDatabase();
    final Cursor cursor = db.rawQuery(SOURCE_RANKING_SQL, new String[] { String.valueOf(minClicks) });
    try {
        Map<String, Integer> corpora = new HashMap<String, Integer>(cursor.getCount());
        while (cursor.moveToNext()) {
            String name = cursor.getString(SourceStats.corpus.ordinal());
            int clicks = cursor.getInt(SourceStats.total_clicks.ordinal());
            corpora.put(name, clicks);
        }
        return corpora;
    } finally {
        cursor.close();
    }
}

From source file:com.android.quicksearchbox.ShortcutRepositoryImplLog.java

@VisibleForTesting
ShortcutCursor getShortcutsForQuery(String query, Collection<Corpus> allowedCorpora,
        boolean allowWebSearchShortcuts, long now) {
    if (DBG)//from  w  ww .ja  v a 2s  . c o m
        Log.d(TAG, "getShortcutsForQuery(" + query + "," + allowedCorpora + ")");
    String sql = query.length() == 0 ? mEmptyQueryShortcutQuery : mShortcutQuery;
    String[] params = buildShortcutQueryParams(query, now);

    SQLiteDatabase db = mOpenHelper.getReadableDatabase();
    Cursor cursor = db.rawQuery(sql, params);
    if (cursor.getCount() == 0) {
        cursor.close();
        return null;
    }

    if (DBG)
        Log.d(TAG, "Allowed sources: ");
    HashMap<String, Source> allowedSources = new HashMap<String, Source>();
    for (Corpus corpus : allowedCorpora) {
        for (Source source : corpus.getSources()) {
            if (DBG)
                Log.d(TAG, "\t" + source.getName());
            allowedSources.put(source.getName(), source);
        }
    }

    return new ShortcutCursor(new SuggestionCursorImpl(allowedSources, query, cursor), allowWebSearchShortcuts,
            mUiThread, mRefresher, this);
}

From source file:com.data.pack.ViewVideo.java

/**
   * Get raw data//  w  w  w . j  a  v  a 2s  . c o  m
   * 
   * @param String 
   * @return  Cursor
   */
private Cursor getRawEvents(String sql) {
    SQLiteDatabase db = (placeData).getReadableDatabase();
    Cursor cursor = null;
    try {
        cursor = db.rawQuery(sql, null);

        startManagingCursor(cursor);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return cursor;
}

From source file:net.smart_json_database.JSONDatabase.java

private void updateTagMap() {
    String sql = "SELECT * FROM " + TABLE_TAG;
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    Cursor c = db.rawQuery(sql, new String[] {});
    if (c.getCount() > 0) {
        int col_id = c.getColumnIndex("tag_uid");
        int col_name = c.getColumnIndex("name");

        c.moveToFirst();/*w w  w  . jav  a  2  s  .  c  o m*/
        do {
            tags.put(c.getString(col_name), new Integer(c.getInt(col_id)));
            invertedTags.put(new Integer(c.getInt(col_id)), c.getString(col_name));
        } while (c.moveToNext());
    }
    c.close();
    db.close();
}

From source file:net.smart_json_database.JSONDatabase.java

public Collection<String> getPropertyKeys() {
    ArrayList<String> arrayList = new ArrayList<String>();
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    Cursor c = db.rawQuery("SELECT * FROM " + TABLE_Meta, new String[] {});

    if (c.getCount() > 0) {
        int key_col = c.getColumnIndex("key");
        c.moveToFirst();/*from   w  w  w . ja  va2s  .  c o m*/
        if (c != null) {
            if (c.isFirst()) {
                do {
                    arrayList.add(c.getString(key_col));
                } while (c.moveToNext());
            }
        }
    }
    c.close();

    return arrayList;
}

From source file:com.concentricsky.android.khanacademy.data.remote.LibraryUpdaterTask.java

private void mergeDbs() {
    Log.d(LOG_TAG, "update received - juggling dbs");
    // Get main database, attach temp db to it.
    SQLiteDatabase mainDb = dataService.getHelper().getWritableDatabase();
    mainDb.execSQL("attach database ? as ka_temp",
            new Object[] { dataService.getDatabasePath("ka_temp").getAbsolutePath() });

    mainDb.beginTransaction();/*from w  ww  . ja  v  a2  s . c o m*/
    try {

        // Maintain download status.
        String sql = "select max(download_status), dlm_id, youtube_id from video where download_status != ? group by youtube_id";
        Cursor c = mainDb.rawQuery(sql, new String[] { "" + Video.DL_STATUS_NOT_STARTED });
        Cursor c1;
        String[] videoIds = new String[c.getCount()];
        int i = 0;
        while (c.moveToNext()) {
            String youtube_id = c.getString(c.getColumnIndex("youtube_id"));
            String download_status = c.getString(c.getColumnIndex("max(download_status)"));
            long dlm_id = c.getLong(c.getColumnIndex("dlm_id"));
            videoIds[i++] = youtube_id;
            ContentValues v = new ContentValues();
            v.put("download_status", download_status);
            v.put("dlm_id", dlm_id);
            String[] idArg = new String[] { youtube_id };
            mainDb.update("ka_temp.video", v, "youtube_id = ?", idArg);

            // cursor over parent topics of this video
            sql = "select ka_temp.topic._id from ka_temp.topic, ka_temp.topicvideo, ka_temp.video where ka_temp.video.youtube_id=? and ka_temp.topicvideo.video_id=ka_temp.video.readable_id and ka_temp.topicvideo.topic_id=ka_temp.topic._id";
            c1 = mainDb.rawQuery(sql, idArg);
            Log.d(LOG_TAG, String.format("updating counts for %d topics", c1.getCount()));
            while (c1.moveToNext()) {
                String topicId = c1.getString(c1.getColumnIndex("_id"));
                DatabaseHelper.incrementDownloadedVideoCounts(mainDb, topicId, "ka_temp.topic");
            }
            c1.close();
        }
        c.close();

        mainDb.execSQL("delete from topic");
        mainDb.execSQL("insert into topic select * from ka_temp.topic");

        mainDb.execSQL("delete from topicvideo");
        mainDb.execSQL("insert into topicvideo select * from ka_temp.topicvideo");

        mainDb.execSQL("delete from video");
        mainDb.execSQL("insert into video select * from ka_temp.video");

        mainDb.setTransactionSuccessful();
    } finally {
        mainDb.endTransaction();
        mainDb.execSQL("detach database ka_temp");
    }

    Log.d(LOG_TAG, "finished juggling");
}

From source file:com.android.strictmodetest.StrictModeActivity.java

/** Called when the activity is first created. */
@Override/*www.  jav  a2 s.c o  m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    cr = getContentResolver();
    final SQLiteDatabase db = openOrCreateDatabase("foo.db", MODE_PRIVATE, null);

    final Button readButton = (Button) findViewById(R.id.read_button);
    readButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Cursor c = null;
            try {
                c = db.rawQuery("SELECT * FROM foo", null);
            } finally {
                if (c != null)
                    c.close();
            }
        }
    });

    final Button writeButton = (Button) findViewById(R.id.write_button);
    writeButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            db.execSQL("CREATE TABLE IF NOT EXISTS FOO (a INT)");
        }
    });

    final Button writeLoopButton = (Button) findViewById(R.id.write_loop_button);
    writeLoopButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            long startTime = SystemClock.uptimeMillis();
            int iters = 1000;
            BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
            for (int i = 0; i < iters; ++i) {
                policy.onWriteToDisk();
            }
            long endTime = SystemClock.uptimeMillis();
            Log.d(TAG, "Time for " + iters + ": " + (endTime - startTime) + ", avg="
                    + (endTime - startTime) / (double) iters);
        }
    });

    final Button dnsButton = (Button) findViewById(R.id.dns_button);
    dnsButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.d(TAG, "Doing DNS lookup for www.l.google.com... " + "(may be cached by InetAddress)");
            try {
                InetAddress[] addrs = InetAddress.getAllByName("www.l.google.com");
                for (int i = 0; i < addrs.length; ++i) {
                    Log.d(TAG, "got: " + addrs[i]);
                }
            } catch (java.net.UnknownHostException e) {
                Log.d(TAG, "DNS error: " + e);
            }
        }
    });

    final Button httpButton = (Button) findViewById(R.id.http_button);
    httpButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                // Note: not using AndroidHttpClient, as that comes with its
                // own pre-StrictMode network-on-Looper thread check.  The
                // intent of this test is that we test the network stack's
                // instrumentation for StrictMode instead.
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpResponse res = httpClient.execute(new HttpGet("http://www.android.com/favicon.ico"));
                Log.d(TAG, "Fetched http response: " + res);
            } catch (IOException e) {
                Log.d(TAG, "HTTP fetch error: " + e);
            }
        }
    });

    final Button http2Button = (Button) findViewById(R.id.http2_button);
    http2Button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                // Usually this ends up tripping in DNS resolution,
                // so see http3Button below, which connects directly to an IP
                InputStream is = new URL("http://www.android.com/").openConnection().getInputStream();
                Log.d(TAG, "Got input stream: " + is);
            } catch (IOException e) {
                Log.d(TAG, "HTTP fetch error: " + e);
            }
        }
    });

    final Button http3Button = (Button) findViewById(R.id.http3_button);
    http3Button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                // One of Google's web IPs, as of 2010-06-16....
                InputStream is = new URL("http://74.125.19.14/").openConnection().getInputStream();
                Log.d(TAG, "Got input stream: " + is);
            } catch (IOException e) {
                Log.d(TAG, "HTTP fetch error: " + e);
            }
        }
    });

    final Button binderLocalButton = (Button) findViewById(R.id.binder_local_button);
    binderLocalButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                boolean value = mLocalServiceConn.stub.doDiskWrite(123 /* dummy */);
                Log.d(TAG, "local writeToDisk returned: " + value);
            } catch (RemoteException e) {
                Log.d(TAG, "local binderButton error: " + e);
            }
        }
    });

    final Button binderRemoteButton = (Button) findViewById(R.id.binder_remote_button);
    binderRemoteButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                boolean value = mRemoteServiceConn.stub.doDiskWrite(1);
                Log.d(TAG, "remote writeToDisk #1 returned: " + value);
                value = mRemoteServiceConn.stub.doDiskWrite(2);
                Log.d(TAG, "remote writeToDisk #2 returned: " + value);
            } catch (RemoteException e) {
                Log.d(TAG, "remote binderButton error: " + e);
            }
        }
    });

    final Button binderOneWayButton = (Button) findViewById(R.id.binder_oneway_button);
    binderOneWayButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                Log.d(TAG, "doing oneway disk write over Binder.");
                mRemoteServiceConn.stub.doDiskOneWay();
            } catch (RemoteException e) {
                Log.d(TAG, "remote binderButton error: " + e);
            }
        }
    });

    final Button binderCheckButton = (Button) findViewById(R.id.binder_check_button);
    binderCheckButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            int policy;
            try {
                policy = mLocalServiceConn.stub.getThreadPolicy();
                Log.d(TAG, "local service policy: " + policy);
                policy = mRemoteServiceConn.stub.getThreadPolicy();
                Log.d(TAG, "remote service policy: " + policy);
            } catch (RemoteException e) {
                Log.d(TAG, "binderCheckButton error: " + e);
            }
        }
    });

    final Button serviceDumpButton = (Button) findViewById(R.id.service_dump);
    serviceDumpButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.d(TAG, "About to do a service dump...");
            File file = new File("/sdcard/strictmode-service-dump.txt");
            FileOutputStream output = null;
            final StrictMode.ThreadPolicy oldPolicy = StrictMode.getThreadPolicy();
            try {
                StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.LAX);
                output = new FileOutputStream(file);
                StrictMode.setThreadPolicy(oldPolicy);
                boolean dumped = Debug.dumpService("cpuinfo", output.getFD(), new String[0]);
                Log.d(TAG, "Dumped = " + dumped);
            } catch (IOException e) {
                Log.e(TAG, "Can't dump service", e);
            } finally {
                StrictMode.setThreadPolicy(oldPolicy);
            }
            Log.d(TAG, "Did service dump.");
        }
    });

    final Button lingerCloseButton = (Button) findViewById(R.id.linger_close_button);
    lingerCloseButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            closeWithLinger(true);
        }
    });

    final Button nonlingerCloseButton = (Button) findViewById(R.id.nonlinger_close_button);
    nonlingerCloseButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            closeWithLinger(false);
        }
    });

    final Button leakCursorButton = (Button) findViewById(R.id.leak_cursor_button);
    leakCursorButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            final StrictMode.VmPolicy oldPolicy = StrictMode.getVmPolicy();
            try {
                StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects()
                        .penaltyLog().penaltyDropBox().build());
                db.execSQL("CREATE TABLE IF NOT EXISTS FOO (a INT)");
                Cursor c = db.rawQuery("SELECT * FROM foo", null);
                c = null; // never close it
                Runtime.getRuntime().gc();
            } finally {
                StrictMode.setVmPolicy(oldPolicy);
            }

        }
    });

    final CheckBox checkNoWrite = (CheckBox) findViewById(R.id.policy_no_write);
    final CheckBox checkNoRead = (CheckBox) findViewById(R.id.policy_no_reads);
    final CheckBox checkNoNetwork = (CheckBox) findViewById(R.id.policy_no_network);
    final CheckBox checkPenaltyLog = (CheckBox) findViewById(R.id.policy_penalty_log);
    final CheckBox checkPenaltyDialog = (CheckBox) findViewById(R.id.policy_penalty_dialog);
    final CheckBox checkPenaltyDeath = (CheckBox) findViewById(R.id.policy_penalty_death);
    final CheckBox checkPenaltyDropBox = (CheckBox) findViewById(R.id.policy_penalty_dropbox);

    View.OnClickListener changePolicy = new View.OnClickListener() {
        public void onClick(View v) {
            StrictMode.ThreadPolicy.Builder newPolicy = new StrictMode.ThreadPolicy.Builder();
            if (checkNoWrite.isChecked())
                newPolicy.detectDiskWrites();
            if (checkNoRead.isChecked())
                newPolicy.detectDiskReads();
            if (checkNoNetwork.isChecked())
                newPolicy.detectNetwork();
            if (checkPenaltyLog.isChecked())
                newPolicy.penaltyLog();
            if (checkPenaltyDialog.isChecked())
                newPolicy.penaltyDialog();
            if (checkPenaltyDeath.isChecked())
                newPolicy.penaltyDeath();
            if (checkPenaltyDropBox.isChecked())
                newPolicy.penaltyDropBox();
            StrictMode.ThreadPolicy policy = newPolicy.build();
            Log.v(TAG, "Changing policy to: " + policy);
            StrictMode.setThreadPolicy(policy);
        }
    };
    checkNoWrite.setOnClickListener(changePolicy);
    checkNoRead.setOnClickListener(changePolicy);
    checkNoNetwork.setOnClickListener(changePolicy);
    checkPenaltyLog.setOnClickListener(changePolicy);
    checkPenaltyDialog.setOnClickListener(changePolicy);
    checkPenaltyDeath.setOnClickListener(changePolicy);
    checkPenaltyDropBox.setOnClickListener(changePolicy);
}