I am trying to call data from two different cells in my database then combine them and print them out in an activity.
I am using the following code:
public Cursor getGermanDescription(String id) {
String[] args = { id };
return (getReadableDatabase()
.rawQuery(
"SELECT _id,Column1,Column2 FROM Databasing_Details WHERE _id=?",
args));
With the above I am only getting the content of Column1 but not Column2. I am passing the String id to another activity.
My cursor adapter is:
#Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Get our passed variable from our intent's EXTRAS
passedVar=getIntent().getStringExtra(ListViewTwo.ID_EXTRA);
//this is our ListView element, obtained by id from our XML layout
ListView myListView = (ListView)findViewById(R.id.list_view);
String string = passedVar;
int passedInt = Integer.parseInt(string);
if (passedInt==1) { passedVar1 = true;
}
creating our database Helper:
dbDescriptionHelper=new DatabaseHelper(this);
//a set of results from a database query
ourCursor=dbDescriptionHelper.getGermanDescription(passedVar);
//tell android to start managing the cursor,
startManagingCursor(ourCursor);
//create our adapter
adapter=new SlangAdapter(ourCursor);
//set the adapter!!!
myListView.setAdapter(adapter);
} catch (Exception e) {
Log.e("ERROR", "ERROR IN CODE: " + e.toString());
e.printStackTrace();
}
return;
}
The slangAdapterClass:
class SlangAdapter extends CursorAdapter {
SlangAdapter(Cursor c) {
super(ListViewFinal.this, c);
}
#Override
public void bindView(View row, Context ctxt,
Cursor c) {
DescriptionHolder holder=(DescriptionHolder)row.getTag();
holder.populateFrom(c, dbDescriptionHelper);
}
#Override
public View newView(Context ctxt, Cursor c,
ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.main_row, parent, false);
DescriptionHolder holder=new DescriptionHolder(row);
row.setTag(holder);
return(row);
}
}
The DescriptionHolder class:
static class DescriptionHolder {
private TextView name=null;
DescriptionHolder(View row) {
name=(TextView)row.findViewById(R.id.row);
}
void populateFrom(Cursor c, DatabaseHelper r) {
name.setText(r.getName(c));
}
}
Could someone point out where I am going wrong please.
OK, I have found the answer.
My syntax was incorrect, what I needed to write for my cursor was:
public Cursor getGermanDescription(String id) {
String[] args = { id };
return (getReadableDatabase()
.rawQuery(
"SELECT _id, ObjectDescriptionGerman ||'\n\n'|| ObjectDescription FROM Databasing_Details WHERE _id=?",
args));
}
The || needs to be used instead of "," or "AND". I have also inserted line breaks between my two returned value so I do not need to do this in my database.
Related
I'm having trouble loading data from my ListView that I've populated with my CharacterSheetDBHelper. I've tried searching for several answers, one including using SimpleCursorAdapter, but I'm still having trouble. Can someone steer me into the right direction for this? I want to click on a list item and then fill out the form with the data stored on the database for editing.
My Code below:
The LoadCharacter class
public class LoadCharacter extends AppCompatActivity {
TextView testView;
ListView charListView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.load_character);
CharacterDBHelper db = new CharacterDBHelper(getApplicationContext());
charListView = (ListView) findViewById(R.id.charListView);
//get list of names from the Database helper.
List<String> names = new ArrayList<>(db.getNames());
//attempting to create a listAdapter
ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, names);
charListView.setAdapter(adapter);
charListView.setTextFilterEnabled(true);
charListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent passIntent = new Intent(getApplicationContext(), CreateCharacter.class);
//Logically onItemClick would open up a game in progress rather than the character sheet screen.
//I was going to load character data into the Create Character class as an example.
//This is not working right now.
//Cursor c= (Cursor)charListView.getItemAtPosition(position);
//passIntent.putExtra("Characters", c.getColumn);
startActivity(passIntent);
}
});
}
public boolean onCreateOptionsMenu(Menu menu){
menu.add(0,0,0, "New Character");
return(super.onCreateOptionsMenu(menu));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==0){
Intent intent = new Intent(this, CreateCharacter.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
}
My CharacterDBHelper Class:
public class CharacterDBHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "char.db";
private static final int DATABASE_VERSION = 1;
private SQLiteDatabase charDB = null;
public CharacterDBHelper(Context context) {
super(context, DB_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
//Create database
String CREATE_CHAR_TABLE = "CREATE TABLE IF NOT EXISTS Characters(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, " +
"brawling TEXT NOT NULL, highflying TEXT NOT NULL, technical TEXT NOT NULL, startinghealth TEXT NOT NULL," +
"remainingpoints TEXT NOT NULL)";
db.execSQL(CREATE_CHAR_TABLE);
}
public List<String> getNames(){
List<String> names = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
//Read from database and get ALL entries by name.
Cursor cursor = db.rawQuery("SELECT * FROM Characters", null);
if (cursor.moveToFirst()){
do {
//add extracted names to array.
names.add(cursor.getString(cursor.getColumnIndex("name")));
}while(cursor.moveToNext());
}
//close cursor and database.
cursor.close();
db.close();
return names;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS Characters");
onCreate(db);
}
public void insertData(String name, String brawl, String flying, String tech, String health, String points){
SQLiteDatabase charDB = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", name);
values.put("brawling", brawl);
values.put("highflying", flying);
values.put("technical", tech);
values.put("startinghealth", health);
values.put("remainingpoints", points);
//row insert
charDB.insert("Characters", null, values);
charDB.close();
}
}
I believe that you look like you are having problems using intent extras. Here's and example of adding some from a cursor, from within onItemClickListener:-
intent.putExtra("Caller", THIS_ACTIVITY + "Update");
intent.putExtra("AisleID", aisleadapter.getCursor().getString(ShopperDBHelper.AISLES_COLUMN_ID_INDEX));
intent.putExtra("AISLEID", aisleadapter.getCursor().getLong(ShopperDBHelper.AISLES_COLUMN_ID_INDEX));
intent.putExtra("AisleName", aisleadapter.getCursor().getString(ShopperDBHelper.AISLES_COLUMN_NAME_INDEX));
intent.putExtra("AisleOrder", aisleadapter.getCursor().getString(ShopperDBHelper.AISLES_COLUMN_ORDER_INDEX));
intent.putExtra("AisleShopRef", aisleadapter.getCursor().getString(ShopperDBHelper.AISLES_COLUMN_SHOP_INDEX));
intent.putExtra("SHOPID", aisleadapter.getCursor().getLong(ShopperDBHelper.AISLES_COLUMN_SHOP_INDEX));
startActivity(intent);
Note!! ShopperDBHelper.AISLES_COLUMN_??????_INDEX equates to the offset within the cursor of the column.
Here's an example of retrieving from the intent within the started actvity:-
shopid = getIntent().getLongExtra("SHOPID", -1)
Note cursor should be set to the appropriate position. However, you could always use cursor.moveToPosition(position)
Here's an example CursorAdapter :-
package mjt.shopper;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;
/**
* Created by Mike092015 on 6/02/2016.
*/
class AislesCursorAdapter extends CursorAdapter {
public AislesCursorAdapter(Context context, Cursor cursor, int flags) {
super(context, cursor, 0);
}
#Override
public View getView(int position, View convertview, ViewGroup parent) {
View view = super.getView(position, convertview, parent);
Context context = view.getContext();
if (position % 2 == 0) {
view.setBackgroundColor(ContextCompat.getColor(context, R.color.colorlistviewroweven));
} else {
view.setBackgroundColor(ContextCompat.getColor(context, R.color.colorlistviewrowodd));
}
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView textviewaisleid = (TextView) view.findViewById(R.id.aisle_id_entry);
TextView textviewaislename = (TextView) view.findViewById(R.id.aisle_name_entry);
TextView textviewaisleorder = (TextView) view.findViewById(R.id.aisle_order_entry);
TextView textviewaisleshopref = (TextView) view.findViewById(R.id.aisle_shopref_entry);
textviewaisleid.setText(cursor.getString(ShopperDBHelper.AISLES_COLUMN_ID_INDEX));
textviewaislename.setText(cursor.getString(ShopperDBHelper.AISLES_COLUMN_NAME_INDEX));
textviewaisleorder.setText(cursor.getString(ShopperDBHelper.AISLES_COLUMN_ORDER_INDEX));
textviewaisleshopref.setText(cursor.getString(ShopperDBHelper.AISLES_COLUMN_SHOP_INDEX));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.activity_aisle_list_entry, parent, false);
}
}
Note. bindView (set the Listview's line/item/entry views with values) and newView (tell the adapter what layout to use) are required.
getView is optional (used here to alternate row background)
I wish to store it in arraylist and then display it out in listView. Is there any solution to it ? how do I set the adapter? how can I link this two up and display it into a listview using arrayList?
DBhelper.java
public ArrayList<String> getDataarray(){
SQLiteQueryBuilder querybuilder=new SQLiteQueryBuilder();
querybuilder.setTables(DATABASE_TABLES);
String [] columns= new String[]{ KEY_ROWID,KEY_USERNAME,KEY_AGE,KEY_ClINIC,KEY_PHONE,KEY_EMAIL,KEY_DATESIGNUP
,KEY_CONDITIONID,KEY_DOCTORID,KEY_LOGINID,KEY_ACTIVITYNAME,KEY_NOTIFICATIONNAME,KEY_GROUPNAME,KEY_APPROVED
};
Cursor c= ourdatabase.query(DATABASE_TABLES, columns, null,null, null, null, null);
String result="";
ArrayList<String> resultarray = new ArrayList<String>();
int iRow=c.getColumnIndex(KEY_ROWID);
int iUserName=c.getColumnIndex(KEY_USERNAME);
int iAge=c.getColumnIndex(KEY_AGE);
int iClinic=c.getColumnIndex(KEY_ClINIC);
int iPhone=c.getColumnIndex(KEY_PHONE);
int iEmail=c.getColumnIndex(KEY_EMAIL);
int iDateSignup=c.getColumnIndex(KEY_DATESIGNUP);
int iConditionID=c.getColumnIndex(KEY_CONDITIONID);
int iDoctorID=c.getColumnIndex(KEY_DOCTORID);
int iLoginID=c.getColumnIndex(KEY_LOGINID);
int iActivityName=c.getColumnIndex(KEY_ACTIVITYNAME);
int iNotificationName=c.getColumnIndex(KEY_NOTIFICATIONNAME);
int iGroupName=c.getColumnIndex(KEY_GROUPNAME);
int iApproved=c.getColumnIndex(KEY_APPROVED);
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT value FROM " + DATABASE_TABLES, null);
if(cursor.moveToFirst()) {
do {
resultarray.add(cursor.getString(cursor.getColumnIndex("value")));
}while(cursor.moveToNext());
}
cursor.close();
db.close();
return resultarray;
}
ProfileFragment.java this is the page where i want to retrieve out at the listView how can i retrieve it from the database instead of array
public View getView( int position ,View convertView,ViewGroup parent){
LayoutInflater inflater= (LayoutInflater) context.getSystemService(android.content.Context.LAYOUT_INFLATER_SERVICE);
View row =inflater.inflate(R.layout.profile_list,parent,false);
TextView myProfile=(TextView)row.findViewById(R.id.Profile);
TextView myCondition=(TextView)row.findViewById(R.id.condition);
myProfile.setText(ProfileArray[position]);
myCondition.setText(resultarray[position]);
return row;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.user,container,false);
Resources res=getResources();
Profile=res.getStringArray(R.array.Profile);
//how can i change the line below to let it get the data from the database array? or is there any other method?
condition=res.getStringArray(R.array.Profile_values);
list.setAdapter(adapter);
list=(ListView)rootview.findViewById(R.id.listView1);
return rootview;
}
Do you want to display all of data?
Think about using CursorLoader with SimpleCursorAdapter. It will load your data once activity is created in background. And in your activity class just implement interface LoaderManager.LoaderCallback, and in onCreate you simply initialize Loader with getSupportLoaderManager().initLoader(LOADER_ID, null, this)
Here is the link with good example http://www.androiddesignpatterns.com/2012/07/understanding-loadermanager.html
EDIT:
This code use in onCreate
// init DB
db = new DB(this);
db.open();
// forming columns from DB to views
String[] from = new String[] { KEY_ROWID, KEY_USERNAME, KEY_AGE...}; //array of columns from DB
int[] to = new int[] { R.id.textviewId, R.id.textviewUserName, R.id.textviewAge }; //Array of of view components
// create adapter
scAdapter = new SimpleCursorAdapter(this, R.layout.item, null, from, to, 0);
ListView lvData = (ListView) findViewById(R.id.lvData); // listview where you want to display data
lvData.setAdapter(scAdapter);
//init loader
getSupportLoaderManager().initLoader(0, null, this);
//implement these mothods with interface `LoaderManager.LoaderCallback<Cursor>`
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle bndl) {
return new MyCursorLoader(this, db);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
scAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
This code must works for you.
EDIT2
static class MyCursorLoader extends CursorLoader {
DB db;
public MyCursorLoader(Context context, DB db) {
super(context);
this.db = db;
}
#Override
public Cursor loadInBackground() {
return db.getAllData();
}
}
One detail added. This is a class where you download your data from db and return filled cursor.
I have created a ListView using CursorAdapter . Now I am Trying to update the ListView and Refresh the value to the ListView .
But I am not able to figure out . How to work with Loader or changeCursor() to refresh my ListView
Below is My code of setting the CursorAdapter :
//SucessFully done here
SQLDataSore datastore = new SQLDataSore(PrintContent.this);
Cursor cursor = datastore.getJSONData();
final CursorDemo cursorDemo = new CursorDemo(PrintContent.this, cursor);
list_View.setAdapter(cursorDemo);
My Button onClick I am updating the Value into the Database
//SucessFully Done
btn_check.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View view ) {
String editTextValue = edit_check.getText().toString();
if (editTextValue!=null) {
SQLDataSore sqlDataSore = new SQLDataSore(PrintContent.this);
Cursor cursor_update = sqlDataSore.updateData(editTextValue);
//Here How Should I update my ListView ...?
}
}
My UpdateData Method:
public Cursor updateData(String editContent){
SQLiteDatabase updateContent = getReadableDatabase();
Cursor cursor_update = updateContent.rawQuery( "update " +TABLE_NAME + " set content = '"+ editContent
+"' "+" where _id = 357", null);
return cursor_update;
}
CursorDemo Class
public class CursorDemo extends CursorAdapter{
public CursorDemo(Context context, Cursor c) {
super(context, c , false);
// TODO Auto-generated constructor stub
}
#Override
public void changeCursor(Cursor cursor) {
// TODO Auto-generated method stub
super.changeCursor(cursor);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// TODO Auto-generated method stub
TextView txt_content = (TextView) view.findViewById(R.id.txt_content);
TextView txt_likes_count = (TextView) view.findViewById(R.id.txt_likescount);
TextView txt_name = (TextView) view.findViewById(R.id.txt_name);
TextView txt_display_name = (TextView) view.findViewById(R.id.txt_display_name);
txt_content.setText(cursor.getString(cursor.getColumnIndex("content")));
}
#Override
public View newView(Context context , Cursor cursor, ViewGroup viewGroup) {
// TODO Auto-generated method stub
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.message_row_view, viewGroup ,false);
return view;
}
}
Any Help is Appreciated...
});
If CursorDemo extends CursorAdapter, then you have to use adapter.swapCursor(cursor_update);
That should swap the old cursor out for the new one and reload the data. With swapCursor, the old cursor is not closed.
In your CursorDemo you have to owerwrite changeCursor() method and reset the Cursor if you have indexer you have to set it's cursor too.
#Override
public void changeCursor(Cursor cursor) {
mIndexer.setCursor(cursor);
super.changeCursor(cursor);
}
public void changeCursor (Cursor cursor)
Added in API level 1 Change the underlying cursor to a new cursor. If
there is an existing cursor it will be closed.
Parameters cursor The new cursor to be used
Also try for below method if it's apt for your requirement.
Set a FilterQueryProviderand pass your key to that filter.
final Cursor oldCursor = adapter.getCursor();
adapter.setFilterQueryProvider(myQueryProvider);
adapter.getFilter().filter(editTextValue, new FilterListener() {
public void onFilterComplete(int count) {
// assuming your activity manages the Cursor
// (which is a recommended way)
stopManagingCursor(oldCursor);
final Cursor newCursor = adapter.getCursor();
startManagingCursor(newCursor);
// safely close the oldCursor
if (oldCursor != null && !oldCursor.isClosed()) {
oldCursor.close();
}
}
});
private FilterQueryProvider myQueryProvider = new FilterQueryProvider() {
public Cursor runQuery(CharSequence searchKey) {
// assuming you have your custom DBHelper instance
// ready to execute the DB request
return sqlDataSore.updateData(searchKey);;
}
};
PS : The Cursor must include a column named _id or this class will not work see this.
btn_check.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View view ) {
String editTextValue = edit_check.getText().toString();
if (editTextValue!=null) {
SQLDataSore sqlDataSore = new SQLDataSore(PrintContent.this);
Cursor cursor_update = sqlDataSore.updateData(editTextValue);
cursorDemo.swapCursor(cursor_update);
//or cursorDemo=new CursorDemo(this,cursor_update);
list_View.setAdapter(cursorDemo);
}
}
Put this on the activity where declare the ListView . Just create a new adapter and put it in new cursor then recreate it or swap the cursor. make sure your listview or adapter not constant.
you could call
adapter.notifyDataSetChanged();
".java.lang.IllegalArgumentException: column '_id' does not exist ...althouh I have _id field in to my db table" means that the value of "cursor" in your code is wrong.
Check the code of getting the value of "cursor" please. A cursor must have a column named '_id'。
This is my suggestion
If you want to adapt/replace new cursor value to your list view , you should remove the old cursor from adapter and add new cursor value to the adapter.And finally adapt this adapter to listview using listview.setadapter(CursorAdapter) as follows.
liveTagListCursor = ctx.getContentResolver().query(
LiveTagProvider.TAG_LIST_URI, null, null, null, null);
tagCursorAdapter = new LiveTagListCursorAdapter(getActivity(),
liveTagListCursor);
tagCursorAdapter.swapCursor(liveTagListCursor);
listview.setAdapter(tagCursorAdapter);
I am using a CursorAdapter with a ListView and a cursor getting data from an sqlite database. I have this function called RenderList() which I call every time I update the database with a new item for the list or if I set the checked value of a row to one (this will add the new item or strikethough the item name).
private void renderList(){
String showWhere = show_checked ? null : DbHelper.C_CHECKED + "= '0' ";
try {
db = dbHelper.getReadableDatabase();
cursor = db.query(DbHelper.TABLE, null, showWhere, null, null, null, dbHelper.C_ID + " DESC");
groceriesList = (ListView)findViewById(R.id.listView1);
adapter = new GroceryAdapter(this, cursor);
adapter.newView(getApplicationContext(), cursor, groceriesList);
groceriesList.setAdapter(adapter);
groceriesList.setOnItemClickListener(itemListener);
} catch (Exception e) {
Log.d(TAG, "RenderList Error: ",e);
}
}
This will reset the list, so if I click an item that is way down the listview it will reset the listview to the top position. Obviously I'm missing something with how to update the listview, and the database in an efficient, and usable way?
public class GroceryAdapter extends CursorAdapter {
private final LayoutInflater mInflater;
public GroceryAdapter(Context context, Cursor cursor) {
super(context, cursor, true);
mInflater = LayoutInflater.from(context);
// mContext = context;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TwoLineListItem listItem = (TwoLineListItem)view;
TextView t1 = listItem.getText1();
TextView t2 = listItem.getText2();
t1.setText(cursor.getString(cursor.getColumnIndex(DbHelper.C_GROCERY)));
t2.setText("Added by: Wes");
t1.setTag(cursor.getInt(cursor.getColumnIndex(DbHelper.C_ID)));
t2.setTag(cursor.getInt(cursor.getColumnIndex(DbHelper.C_CHECKED)));
if (cursor.getInt(cursor.getColumnIndex(DbHelper.C_CHECKED)) == 1 ) {
t1.setPaintFlags(t1.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
listItem.setBackgroundColor(0xEECCCCCC);
} else {
t1.setPaintFlags(t1.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG) );
listItem.setBackgroundColor(0x00000000);
}
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final View view = mInflater.inflate(R.layout.grocery_list_item, parent, false);
return view;
}
}
Beginning Android programming, coming from html/php/css, I have searched the web for a simple way to separate my code from my style - for now I need to display data from a database in a list- or table view.
Simply put, I get a cursor from the database, iterate through it, creating each list-item dynamically in code as TextViews. Then I would like to apply a style from an external xml layout file to each item.
Pseudo-code:
style.xml:
//mystyle: bold, 12pt
//yourstyle: italic, 11pt
Activity:
for (each cursor-entry)
{
tv1 = new TextView();
applyStyle(tv, mystyle);
tv2 = new TextView();
applyStyle(tv, yourstyle);
//Apply content to textviews from the cursor...
}
mainLayout.setView(tv1);
mainLayout.setView(tv2);
The code examples I've found around the net, uses multiple lines of code, or multiple xml files (using inflate, or cursorAdapters), and IMO quickly become bloated. I just want a nice neat way to apply a style to a dynamically created code. Is this possible?
If you are using ListView, it is so simple to have an XML file for rows. The only thing you need is an XML file and a Adapter class. Take a look at this simple example:
To read data from database, create a helper class like this:
public class MessagingDatabaseAdapter {
protected SQLiteDatabase database;
public MessagingDatabaseAdapter(Context context) {
MessagingDatabaseHelper databaseHelper = new MessagingDatabaseHelper(context, "message_history_db");
database = databaseHelper.getWritableDatabase();
}
public void close() {
database.close();
}
public void Entity[] getAllEntities() {
Entity[] values = null;
String query = "select * from TABLE_NAME";
Cursor cursor = null;
try {
cursor = database.rawQuery(query, null);
if( cursor.moveToFirst() ) {
int s = cursor.getCount();
values = new Entity[s];
do {
Entity entity = new Entity();
entity.setSomeProperty(cursor.getInt(cursor.getColumnIndex(SOME_PROPERTY_COLUMN)));
values[i++] = entity;
} while( cursor.moveToNext() );
}
} catch(Exception ex) {
} finally {
if( cursor != null ) {
cursor.close();
}
return values;
}
}
protected class MessagingDatabaseHelper extends SQLiteOpenHelper {
public MessagingDatabaseHelper(Context context, String name) {
super(context, name, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("Your SQL to create Tables");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}
In your Activity class:
MessagingDatabaseAdapter db = new MessagingDatabaseAdapter();
values = db.getAllEntities();
db.close();
list_view = (ListView) findViewById(R.id.list_view);
ListAdapter adapter = new ListAdapter(this, values);
list_view.setAdapter(adapter);
And ListAdapter class:
public class ListAdapter extends ArrayAdapter<Entity> {
final Context context;
final Entity[] values;
public ListAdapter(Context context, Entity[] values) {
super(context, R.layout.list_screen, values);
this.values = values;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_view_item, parent, false);
TextView datetimeTextView = (TextView) rowView.findViewById(R.id.list_view_datetime_text_view);
datetimeTextView.setTypeface(someTypeFace);
return rowView;
}
}
And row layout XML file (list_view_item.xml):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="#style/BorderedFrame" >
<TextView
android:id="#+id/inbox_list_view_datetime_text_view"
style="#style/MediumText"
android:layout_width="wrap_content" >
</TextView>
</RelativeLayout>