Click here to Skip to main content
15,888,610 members
Articles / Mobile Apps / Android
Tip/Trick

Quick-and-Dirty Way to Get All Records from Any SQLite Table (Using Java from Android)

Rate me:
Please Sign up or sign in to vote.
4.92/5 (5 votes)
20 May 2014CPOL1 min read 14.6K   6  
Learn how to get all records from any SQLite table, passing the Table Name as String and receiving a StringBuilder

Show Me the Data, Dude or Dudette (as the Case May Be)

Sometimes you just want to quickly see what the contents of a given SQLite table is, without going through the rigamarole of starting up DDMS and then copying files hither and yon, etc., as I showed how to do here.

Doing so is easy; you need to know the data type of the column you're retrieving, but there are only five possibilities in SQLite (null, Int, Float, String, and BLOb), and the Cursor class has a getType() method that tells you what that is, so it's rather easy to stuff the entire contents of any SQLite table into a StringBuilder and return that, as shown here:

Java
public class SQLiteOpenHelperPlatypus extends SQLiteOpenHelper {
    . . .
    public StringBuilder getAllRecordsFrom(String tblName) {
        final int NULLVAL = 0;
        final int INTVAL = 1;
        final int FLOATVAL = 2;
        final int STRINGVAL = 3;
        final int BLOBVAL = 4;
        String query = "Select * FROM " + tblName;
        StringBuilder results = new StringBuilder();
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db != null ? db.rawQuery(query, null) : null;

        if (cursor == null) return results;
        int colCount = cursor.getColumnCount();
        cursor.moveToFirst();
        int typeVal;

        while (true) {
            for (int i = 0; i < colCount; i++) {
                typeVal = cursor.getType(i);
                switch (typeVal) {
                    case NULLVAL:
                        // nuttin', honey
                        break;
                    case INTVAL:
                        results.append(cursor.getInt(i)).toString();
                        break;
                    case FLOATVAL:
                        results.append(cursor.getFloat(i)).toString();
                        break;
                    case STRINGVAL:
                        results.append(cursor.getString(i));
                        break;
                    case BLOBVAL:
                        results.append("BLOb" + String.valueOf(i));
                        break;
                }
            }
            if (cursor.isLast()) break;
            cursor.moveToNext();
        }
        cursor.close();

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

SQL Injection Considered More Harmful than the Zombie Apocalypse

This is probably not something you'd want to expose to your users, based on the possibility of a SQL Injection attack (which would be worse than a Zombie attack, because SQL Injection is real), but for a quick-and-dirty way of seeing what a particular table holds during development, it's the cat's meow. As indicated in the code above, declare this method in a class that extends SQLiteOpenHelper, such as:

Java
public class SQLiteOpenHelperPlatypus extends SQLiteOpenHelper {

...and you're "off to the races." You can call it like so (this assumes you have a Spinner widget that contains the names of the SQLite tables):

Java
private ShowLocalDataTask _showLocalDataTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sqlite);

        final Spinner spin = (Spinner) findViewById((R.id.tableSpinner));

        Button selectAllBtn = (Button) findViewById(R.id.SelectStarBtn);
        selectAllBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                String tblName = String.valueOf(spin.getSelectedItem());
                _showLocalDataTask = new ShowLocalDataTask();
                _showLocalDataTask.execute(tblName);
            }
        });

    }

    . . .

    private class ShowLocalDataTask extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... strings) {
            String tbl = strings[0];
            SQLiteOpenHelperHHS sqliteHHS = new SQLiteOpenHelperPlatypus(SQLiteActivity.this, null);
            StringBuilder sb = sqliteHHS.getAllRecordsFrom(tbl);
            return sb.toString();
        }

        @Override
        protected void onPostExecute(String result) {
            if (result == null) return;
            Log.i("QueryResults", result);
            Toast.makeText(SQLiteActivity.this, result, Toast.LENGTH_LONG).show();
        }
    }

You can find my tip on how to populate a Spinner with values here.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder Across Time & Space
United States United States
I am in the process of morphing from a software developer into a portrayer of Mark Twain. My monologue (or one-man play, entitled "The Adventures of Mark Twain: As Told By Himself" and set in 1896) features Twain giving an overview of his life up till then. The performance includes the relating of interesting experiences and humorous anecdotes from Twain's boyhood and youth, his time as a riverboat pilot, his wild and woolly adventures in the Territory of Nevada and California, and experiences as a writer and world traveler, including recollections of meetings with many of the famous and powerful of the 19th century - royalty, business magnates, fellow authors, as well as intimate glimpses into his home life (his parents, siblings, wife, and children).

Peripatetic and picaresque, I have lived in eight states; specifically, besides my native California (where I was born and where I now again reside) in chronological order: New York, Montana, Alaska, Oklahoma, Wisconsin, Idaho, and Missouri.

I am also a writer of both fiction (for which I use a nom de plume, "Blackbird Crow Raven", as a nod to my Native American heritage - I am "½ Cowboy, ½ Indian") and nonfiction, including a two-volume social and cultural history of the U.S. which covers important events from 1620-2006: http://www.lulu.com/spotlight/blackbirdcraven

Comments and Discussions

 
-- There are no messages in this forum --