8

I am after a code to get the available column names of a table in Android?

I looked around and didn't find anything.

1
  • 2
    How about try writing it... instead of searchin for it. Stackoverflow is not a code generation site. Commented Oct 11, 2013 at 5:12

7 Answers 7

21

This is a simpler way:

Cursor ti = db.rawQuery("PRAGMA table_info(mytable)", null);
if ( ti.moveToFirst() ) {
    do {
        System.out.println("col: " + ti.getString(1));
    } while (ti.moveToNext());
}
Sign up to request clarification or add additional context in comments.

3 Comments

What about getting a content resolvers columns? Is there a simpler way considered to mine, where we run the query on CR?
No, there isn't. In such case a null projection will give you all the columns.
From SQLite documentation "Specific pragma statements may be removed and others added in future releases of SQLite. There is no guarantee of backwards compatibility." Very dangerous on a platform like Android where the SQLite version is not always constant.
14

The simplest way I've implemented.

Cursor cursor = db.rawQuery("SELECT * FROM " + tableName + " LIMIT 1", null);
String[] colNames = cursor.getColumnNames();

Any better suggestion are welcome.

2 Comments

@njzk2, haven't tried that when table is empty. It suppose to work, only that the cursor will not point to any row
I have used it with limit 0, apparently it works, even with an empty table. I like this solution better than querying the pragma.
2
    try {
        Cursor c = db.query(tableName, null, null, null, null, null, null);
        if (c != null) {
            int num = c.getColumnCount();
            for (int i = 0; i < num; ++i) {
                String colname = c.getColumnName(i);

            }
        }

    } catch (Exception e) {
        Log.v(tableName, e.getMessage(), e);
        e.printStackTrace();
    }

Comments

2
public class Database_demo extends Activity {
private String jsonResult;
public static final int DIALOG_DOWNLOAD_JSON_PROGRESS = 0;
private String url = "http://192.168.43.2/brother/song.php";
String urll = url;
private ListView listView;
private static final String HTTP_REQUEST_FAILED = null;
int[] flags;
String strImageName;
int n = 10000;
String[] mySecondStringArray = new String[n];
String[] strArray;
private ProgressDialog mProgressDialog;
HashMap<String, String> hm;
List<HashMap<String, String>> aList;

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

    listView = (ListView) findViewById(R.id.listview);
    try {
        accessWebService();
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(),
                "Check ur network connection", 10000).show();
    }
}

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_DOWNLOAD_JSON_PROGRESS:
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("Please wait.....");
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setCancelable(true);
        mProgressDialog.show();
        return mProgressDialog;

    default:
        return null;
    }
}

// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
    }

    @Override
    protected String doInBackground(String... params) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(params[0]);
        try {
            HttpResponse response = httpclient.execute(httppost);
            jsonResult = inputStreamToString(
                    response.getEntity().getContent()).toString();
        }

        catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private StringBuilder inputStreamToString(InputStream is) {
        String rLine = "";
        StringBuilder answer = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        try {
            while ((rLine = rd.readLine()) != null) {
                answer.append(rLine);
            }
        }

        catch (IOException e) {
            // e.printStackTrace();
            Toast.makeText(getApplicationContext(),
                    "Error..." + e.toString(), Toast.LENGTH_LONG).show();
        }
        return answer;
    }

    @Override
    protected void onPostExecute(String result) {

        ListDrwaer();

        dismissDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);

    }
}

public void accessWebService() {
    JsonReadTask task = new JsonReadTask();
    // passes values for the urls string array
    task.execute(new String[] { url });
}

public void ListDrwaer() {

    try {
        JSONObject jsonResponse = new JSONObject(jsonResult);
        JSONArray jsonMainNode = jsonResponse.optJSONArray("products");

        aList = new ArrayList<HashMap<String, String>>();
        for (int i = 0; i < jsonMainNode.length(); i++) {
            JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
            String name = jsonChildNode.optString("field");


            hm = new HashMap<String, String>();
            hm.put("txt", name);
            //hm.put("cur", number);

            aList.add(hm);

        }
    } catch (JSONException e) {
        Toast.makeText(getApplicationContext(), "Error" + e.toString(),
                Toast.LENGTH_SHORT).show();
    }
    String[] from = { "flag", "txt" };
    int[] to = { R.id.flag, R.id.txt };
    SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList,
            R.layout.news, from, to);
    listView.setAdapter(adapter);


}

}

Comments

1

An alternative to Zul's method is to use columnCount with his simple example and a limit of 0.

Cursor cursor = db.rawQuery("SELECT * FROM " + tableName + " LIMIT 0", null);
int colCount = cursor.getColumnNames().length();

Comments

0

DataBase Map

 private HashMap<String, String[]> getDataBaseMap(SQLiteDatabase db){

    HashMap<String, String[]> DBMap = new HashMap<>();
    ArrayList<String> tableNames = new ArrayList<>();
    String[] columns ;

    Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);

    if (c.moveToFirst()) {
        while ( !c.isAfterLast() ) {
            tableNames.add(c.getString(0));
            c.moveToNext();
        }
    }
    c.close();

    for ( int i = 0 ; i < tableNames.size() ; i++){
        Cursor  cursor = db.rawQuery("select * from " + tableNames.get(i),null);
        columns = cursor.getColumnNames();
        cursor.moveToNext();

        DBMap.put(tableNames.get(i),columns);
        cursor.close();

    }

    return DBMap;
}

Comments

0

try this:

Best if you use a SQLiteDatabase instance and use query method

SQLiteDatabase mDataBase;
(some code here...)
mDataBase = getReadableDatabase();
Cursor dbCursor = mDataBase.query(TABLE_NAME, null, null, null, null, null, null);
String[] columnNames = dbCursor.getColumnNames();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.