Question

I'm trying to populate a table in android app built with xml with data coming in JSON format from MYSQL database, here's the segment of code I tried to populate the table cells:

        TableLayout table = (TableLayout)findViewById(R.id.tablelayout1);

        JSONObject jobj = json.getJSONObject(0);

        Log.d("json.getJSONObject(0)", ""+json.getJSONObject(0));
        textView.setId(R.id.tv21);
        textView.setText(jobj.getString("id"));

        Log.d("jobj.getString(c)", ""+jobj.getString("c"));
        rows.addView(textView);
        table.addView(rows);

json.getJSONObject(0) returns [{"id":"2222222", "c":"some text"}, "foo":"some other text"}]

and

jobj.getString("c") returns "some text".

I can't set the text at the entry 21 (or in any other entry in the whole table) with the "some text". Can anyone help please?

Was it helpful?

Solution

You have to specify the individual names of the values. For instance, if your table looked like this (Note, not actually valid(:

<TableLayout>
    <TableRow>
        <TextView android:id="@+id/tv1_1/>
        <TextView android:id="@+id/tv1_2/>
    </TableRow>
    <TableRow>
        <TextView android:id="@+id/tv2_1/>
        <TextView android:id="@+id/tv2_2/>
    </TableRow>
</TableLayout>

Then code like this could set it

TableLayout table = (TableLayout)findViewById(R.id.tablelayout1);
TextView tv=((TextView)table.findViewById(R.id.tv1_1));
tv.setText("Some Text");

Depending on your data, you might actually want to use a ListView, but I'll save that explanation for another time. It works good with long sets of data, such as the Android contact list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top