show data in android using gridview from database - android

I want to display data, from a database, in a gridview.
Means I have a data in my table (let it's a customer detail) and I want to show it in gridview (or any other control to display details) same as we done in asp.net.
Solution:--
public void FillGrid() {
DatabaseHelper dbh = new DatabaseHelper(this);
dbh.openDataBase();
Cursor cursor;
GridView grv = (GridView) findViewById(R.id.grvData);
cursor = dbh.getGridData();
dbh.close();
if (cursor != null) {
startManagingCursor(cursor);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.gridlayout, cursor,
new String[] { GridTestActivity.KEY_ROW_ID, GridTestActivity.KEY_ID, GridTestActivity.KEY_DESCRIPTION }
,new int[] { R.id.txtGrv_id, R.id.txtGrvid, R.id.txtGrvDescription } );
adapter.setViewResource(R.layout.gridlayout);
grv.setAdapter(adapter);
}
}

Here's the full example.
Also if your beginning Android this would be a good book for you.

Check this post for gridview: http://developer.android.com/resources/tutorials/views/hello-gridview.html
and this for cursor adapter: http://developer.android.com/reference/android/widget/CursorAdapter.html
Hope this helps!

You can Set the GridView With 3 Columns. It will give you a look of Table form.
OR
You can use customized GridView for your application Using the Following type of Codes..
customergrid.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tab1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<GridView
android:id="#+id/grid"
android:layout_width="fill_parent"
android:layout_height="357dp"
android:numColumns="1"
android:stretchMode="columnWidth" />
<Button
android:id="#+id/cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="cancel" />
</LinearLayout>
And, for each Row use a customized Xml file..
customerrow.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TableRow>
<TextView
android:layout_width="50px"
android:layout_height="wrap_content"
android:id="#+id/row_ID"
android:padding="5px"
android:layout_weight="1" />
<TextView
android:layout_width="50px"
android:layout_height="wrap_content"
android:id="#+id/key_ID"
android:padding="5px"
android:layout_weight="1" />
<TextView
android:layout_width="50px"
android:layout_height="wrap_content"
android:id="#+id/key_Description"
android:padding="5px"
android:layout_weight="1" />
</TableRow>
</TableLayout>
Use customergrid.xml on the Oncreate() method and use customerrow.xml in the Grid creation like as your code..
public void FillGrid() {
DatabaseHelper dbh = new DatabaseHelper(this);
dbh.openDataBase();
Cursor cursor;
GridView grv = (GridView) findViewById(R.id.grvData);
cursor = dbh.getGridData();
dbh.close();
if (cursor != null) {
startManagingCursor(cursor);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.customerrow, cursor, new String[] { GridTestActivity.KEY_ROW_ID,
GridTestActivity.KEY_ID, GridTestActivity.KEY_DESCRIPTION }, new int[] {
R.id.txtGrv_id, R.id.txtGrvid, R.id.txtGrvDescription } );
adapter.setViewResource(R.layout.gridlayout);
grv.setAdapter(adapter);
}
}
You can get the data from the Database on the gridview now.

Related

Android: From database to listview, doens't show nothing

I have a simple database, with _id column and createdOn column.
Trying to print a listView, but my code doesn't show nothing (neither I've errors, also, in LOG I have correctly my values).
Thank you for your help.
EventActivity.java
[...]
private void getEvent(){
db = new DBManager(this);
Cursor cursor = db.query();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.list_activity,
cursor,
new String[] { "createdOn" },
new int[] { R.id.singleDate });
ListView listView = (ListView) findViewById(R.id.listDate1);
listView.setAdapter(adapter);
while (cursor.moveToNext()) {
Log.d(LOGTAG, cursor.getLong(0) + " " + cursor.getString(1));
// here I have all my entries in log
}
list_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="#+id/listDate1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true">
</ListView>
</RelativeLayout>
list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dip" >
<TextView
android:id="#+id/singleDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textStyle="bold" />
</RelativeLayout>
your error is in creating the adapter
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.list_row, // that's the layout to inflate for each row
cursor,
new String[] { "createdOn" }, // those are the cursor columns
new int[] { R.id.singleDate }); // those are the layout views
// to match to the cursor columns

Android: Populate a a ListView from a Database

I have a SQLite Database that I want to use to populate a ListView, but I can't for the life of me figure out how to do that. Based on various internet sources (other questions/tutorials/etc.), I've been able to get this code, but it's clearly not working, as I'm now not even able to open the app in the emulator:
populateListView method
public void populateListView() {
Cursor cursor = db.getAllContacts();
String[] fromFieldNames = new String[] {DBAdapter.KEY_ROWID, DBAdapter.KEY_LOCATION, DBAdapter.KEY_TIME};
int[] toViewIds = new int[] {R.id.textView3, R.id.textView2, R.id.textView4};
SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(this,
R.layout.list_view_layout, cursor, fromFieldNames, toViewIds, 0);
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(myCursorAdapter);
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity"
android:orientation="vertical"
android:id="#+id/TableLayout">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Set New Alarm"
android:id="#+id/setAlarmButton"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="onClickSetAlarm" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView" />
</RelativeLayout>
list_view_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView3" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView4"
android:layout_gravity="center_horizontal" />
</LinearLayout>
I'm fairly certain that the issue isn't with the code for the DBAdapter, as it was working fine before I added this bit of code (I had it display a Toast with the data).
Thanks!
Use a SimpleCursorAdapter
Cursor cursor = obj.fetchAllNames();
registerForContextMenu(lv);
String[] columns = new String[] {
obj.KEY_MAIL,
obj.KEY_NAME
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.tvname,
R.id.tvemail
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
try{
dataAdapter = new SimpleCursorAdapter(
this, R.layout.viewusertext,cursor,columns,
to,
0);
}catch(Exception e)
{e.printStackTrace();}
lv.setAdapter(dataAdapter);
where lv is the listview and dataAdapter is private SimpleCursorAdapter dataAdapter;
The query to retrieve desired element you want to show in the list:
public Cursor fetchAllNames() {
Cursor mCursor = app.myDbHelper.MyDB().query("reg", new String[] {"email as _id","fname"},
null, null, null, null, null);
try{
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}catch(Exception e)
{
return mCursor;
}
}
"reg" is the table name.
Note:while using simplecursoradapter you should use the primary key as _id.In my case email is primary key and I have defined it as public static final String KEY_MAIL="_id";
This question I answered just yesterday. The easiest way to create CursorLoader, which will load your data in background from DB only once when activity creates and easy to set adapter: just form columns "from" (DB.COLUMN_NAME) and "to" (R.id.textviewToDisplay).
Check please this answer.
retriveing data from exisint sqlite database

SimpleCursorAdapter is not populating ListView

The SimpleCursorAdapter is not populating my ListView, no error, just nothing happens.
Could someone help me find the error?
1) Layout with ListView component (tab_frag1_layout.xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FF0000"
android:orientation="vertical" >
<ListView
android:id="#+id/lvVehicle"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
2) Layout to represent row (vehicle_row.xml):
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="1dip" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_arrow_right"
android:contentDescription="#null"
android:adjustViewBounds="true"
android:layout_marginRight="3dip"
android:layout_gravity="center_vertical" />
<TextView
android:id="#+id/plate"
style="#style/vehicleDefaultFont.plate"
android:text="#string/label_text_view" />
<TextView
android:id="#+id/hyphen"
android:text="#string/label_hyphen" />
<TextView
android:id="#+id/model"
android:text="#string/label_text_view" />
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="1dip" >
<TextView
android:id="#+id/driver"
style="#style/vehicleDefaultFont.driver"
android:layout_span="4"
android:text="#string/label_text_view" />
</TableRow>
</TableLayout>
3) Fragment Class:
public class Tab1Fragment extends Fragment {
String TAG = getClass().getName();
private VehicleDbAdapter dbHelper;
private SimpleCursorAdapter dataAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_frag1_layout, container, false);
dbHelper = new VehicleDbAdapter(getActivity());
dbHelper.open();
dbHelper.deleteAllVehicles();
dbHelper.insertVehicles();
Cursor cursor = dbHelper.fetchAllVehicles();
if(cursor != null && cursor.getCount() > 0) {
String[] columns = new String[] {
VehicleDbAdapter.KEY_MODEL,
VehicleDbAdapter.KEY_PLATE,
VehicleDbAdapter.KEY_DRIVER
};
int[] to = new int[] {
R.id.model,
R.id.plate,
R.id.driver,
};
dataAdapter = new SimpleCursorAdapter(
view.getContext(),
R.layout.vehicle_row,
cursor,
columns,
to,
0);
ListView listView = (ListView) view.findViewById(R.id.lvVehicle);
listView.setAdapter(dataAdapter);
Log.i(TAG, "Cursor = " + cursor.getCount());
} else {
Log.i(TAG, "Cursor = " + cursor.getCount());
}
return view;
}
}
Curiously:
My cursor contains an _id field.
I doublechecked my cursor and it has 7 rows.
07-21 01:30:22.215: I/ Cursor = 7
I tried using the layout to the generic android list layout, but nothing doing :(
dataAdapter = new SimpleCursorAdapter(
view.getContext(),
android.R.layout.simple_list_item_1,
cursor,
columns,
to,
0);
Any help is welcome.
The TextViews that you have defined in vehical_row.xml: #+id/plate, #+id/hyphen, #+id/model and #+id/driver are all missing the layout_width and the layout_height attributes. These are required.
For now, set these attributes as "wrap_content". For example:
<TextView
android:id="#+id/plate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#style/vehicleDefaultFont.plate"
android:text="#string/label_text_view" />
Do the above for the other three as well. This should work for you.
I think you have problem at XMl. Check id of your listview.
android:id="#+android:id/mainListView">

updating database from gridview using an alertbox popup in android

I'm developing an Customer details for a shop using Grid view in android. I get the details of my Customers using my Database. I need to update the Stocks handled by the Customer using an alert box for entering the Stock Quantity while performing the Transaction..
customergrid.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tab1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<GridView
android:id="#+id/grid"
android:layout_width="fill_parent"
android:layout_height="357dp"
android:numColumns="1"
android:stretchMode="columnWidth" />
<Button
android:id="#+id/cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="cancel" />
</LinearLayout>
And, for each Row I have used a customized Xml file..
customerrow.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TableRow>
<TextView
android:layout_width="50px"
android:layout_height="wrap_content"
android:id="#+id/row_ID"
android:padding="5px"
android:layout_weight="1" />
<TextView
android:layout_width="50px"
android:layout_height="wrap_content"
android:id="#+id/key_ID"
android:padding="5px"
android:layout_weight="1" />
<TextView
android:layout_width="50px"
android:layout_height="wrap_content"
android:id="#+id/key_Description"
android:padding="5px"
android:layout_weight="1" />
</TableRow>
</TableLayout>
And I have Used customergrid.xml on the Oncreate() method and use customerrow.xml in the Grid creation like as the following code..
public void FillGrid() {
DatabaseHelper sqdb = new DatabaseHelper(this);
sqdb.openDataBase();
Cursor cursor;
GridView grid = (GridView) findViewById(R.id.grvData);
cursor = sqdb.getGridData();
sqdb.close();
if (cursor != null) {
startManagingCursor(cursor);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.customerrow, cursor, new String[] { CustomerActivity.KEY_ROW_ID,
CustomerActivity.KEY_ID, CustomerActivity.KEY_DESCRIPTION }, new int[] {
R.id.txtGrv_id, R.id.txtGrvid, R.id.txtGrvDescription } );
adapter.setViewResource(R.layout.gridlayout);
grid.setAdapter(adapter);
}
And finally I used alert box with an editbox for getting the input of Customer's Stock Quantity. I use this for that task..
grid.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long arg3) {
AlertDialog.Builder b=new AlertDialog.Builder(MarkSheet.this);
b.setTitle("Employee Details");
LayoutInflater li=LayoutInflater.from(MarkSheet.this);
View v=li.inflate(R.layout.dialog, null);
b.setIcon(android.R.drawable.ic_input_get);
b.setView(v);
final TextView txtName=(TextView)v.findViewById(R.id.txtName);
final EditText Quantity=(EditText)v.findViewById(R.id.Quantity);
// Here I need to update the table while clicking the positive button, if I click negative button I need to cancel the Dialog box..
}
});
Anybody help me for Complete this task..
you can find the code for updating the database table here and the concept of alert box here
You need to call the update method of the sqlite from the code where you clicked the button "ok".

unable to get values in list view by using simple cursor adapter android?

In my android app i want to display the list which is retrieving the values from DB .I m using simple cursor adapter to do so,but list view is empty.Here is my code.my list view have two rows. How can i use simple cursor adapter in app.what i m doing wrong.Please suggest.
Thanks in advance.
//list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView android:layout_width="fill_parent" android:id="#android:id/android:list"
android:layout_height="fill_parent" android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"></ListView>
</RelativeLayout>
// textview.xml-->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:weightSum="1">
<TextView android:id="#+id/column1" android:background="#drawable/mid"
android:layout_height="30dp"
android:layout_width="fill_parent" android:layout_weight="0.03"></TextView>
<TextView android:layout_height="wrap_content"
android:text="TextView" android:id="#+id/column2" android:background="#drawable/mid"
android:layout_weight="0.03" android:layout_width="fill_parent"></TextView>
</LinearLayout>
public class AddFood extends ListActivity{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.listxml);
DataBaseHelper db = null;
try {
db = new DataBaseHelper(this);
} catch (IOException e) {
e.printStackTrace();
}
SQLiteDatabase database= db.getReadableDatabase();
Cursor c=database.query("food_list", new String[]{"_id","food_items"}, null, null, null,null,null);
startManagingCursor(c);
String[] displayfield=new String[]{"_id","food_items"};
int[] displayViews = new int[] {R.id.column1,R.id.column2};
SimpleCursorAdapter mAdapter=new SimpleCursorAdapter(getApplicationContext(),R.layout.textview, c,displayfield , displayViews);
this.setListAdapter(mAdapter);
c.close();
}
}
For list.xml use:
<ListView android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"></ListView>
In class file:
do not use c.close();
and use:
SimpleCursorAdapter mAdapter=new SimpleCursorAdapter(this,R.layout.textview, c,displayfield , displayViews);
setListAdapter(mAdapter);

Categories

Resources