Linking listview to sqlite database - android

Here is what I am trying to do and would like some advice on the best methods to do it:
have a database that contains a word, and the name of an image file associated with that word.
the words from the database will be displayed in a listview
when the word is selected, a new activity will start displaying the word and the image in an image view.
Would it be best to store the terms in an array and have the list view populate from this array and then pull from the database onitemclick? Or can the list view be populated with the terms from the database?
Will android be able to display the image if the name of the file is stored in the db?

The best way to achieve what you're looking for is to store the term and image path in the DB, then use the path to fetch the image from whatever location you have put it in.
Images can be stored in the DB, but the general consensus is that it is better to store the image outside the DB and a path to said image in the DB.
Your DB can then be as simple as three columns... "_id", "term" and "term_image".
You can do a simple query to fetch all the info at once (thus only querying the DB once).
Then use the cursor returned by that query to populate your list of terms, and onListItemClick to start a new activity to display the associated image using the path from the list that is in the same record as the term from the list.
Query to fetch data:
public Cursor fetchAllTerms() {
return mDb.query(TERMS_TABLE, new String[] { "_id", "term", "term_img" }, null, null, null, null, null);
}
Using it in your list:
mTermCursor = mDbHelper.fetchAllTerms();
getActivity().startManagingCursor(mTermCursor);
String[] from = new String[] { YourDBClass.term };
int[] to = new int[] { android.R.id.Text1 };
SimpleCursorAdapter ranks = new SimpleCursorAdapter(getActivity(),
android.R.layout.simple_list_item_1, mRankCursor, from, to);
setListAdapter(ranks);
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
String imagePath = mTermCursor.getString(mTermCursor.getColumnIndexOrThrow("term");
// code to start your new activity and put the image path into the bundle to be passed
}

Related

Can I load a SQLite column of binary data into switches?

I have SQLite Database. I've set it up using android and listview such that I can view the data in the database. Most of the columns are text. For these, I have set up several textView objects that permit me to upload the text in the SQL columns into the list view.
But I have a column of binary data. And I'd like to load this such that if there is a "0" in the column, then the switch is in the off position, and if there is a "1" in the column, the switch is in the on position?
Do I need to set up some kind of case system on the switch object?
Here's my current code for populating the ListView
// THIS UPDATES THE LIST
private void populateListViewFromDNewBMetric(){
Cursor cursor = mydbmetric.getAllRows();
// Setup mapping from cursor to view fields
String[] fromFieldNames = new String[]
{DBAdapter_Metrics.KEY_ROWID,DBAdapter_Metrics.KEY_NAME,DBAdapter_Metrics.KEY_DESCRIPTION,DBAdapter_Metrics.KEY_SWITCH};
int[] toViewIDs = new int[]
{R.id.textViewMetricID,R.id.textViewName,R.id.textViewDescription,R.id.switch1};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(),R.layout.item_metric,cursor,fromFieldNames,toViewIDs,0);
ListView mylist = (ListView) findViewById(R.id.listViewMetric);
mylist.setAdapter(myCursorAdapter);
}
}
DBAdapter_Metrics.KEY_SWITCH and R.id.switch1 are the things I don't think makes sense. It works for the other ones like DBAdapter_Metrics.KEY_DESCRIPTION because these are text. But KEY_SWITCH is an integer while switch1 is a switch not a field, so I'm not sure if I can somehow "load" a switch.

Implementing Manually Coded Auto-Incrementing RowId/Using VACUUM in SQLite

I have run into that timeless issue of wanting to have an auto-incrementing column (in SQLITE) that remains intact after a record is deleted. I have run into a number of posts about this problem, but none of them explain exactly how to code your own column for this purpose. I need the numbers to be consecutive because I want to be able to display a record number for each item in a ListView which will also serve as a running total of how many records are in the db.
So far, I have been trying to use the VACUUM function because it's my understanding that it will reset the numbers once it's complete, and I thought I would run it every time a record is deleted, but nothing seems to happen when the code is run. I'm not getting any errors, but the VACUUM isn't happening as far as I can tell. Here's the code:
String sql = "VACUUM;" ;
db.execSQL(sql,new String [] {sql});
Maybe nothing is happening because the coding is off? So I guess what I am getting at here is am I on the right track with trying to use VACUUM or should I go with manually setting up an auto-incrementing column? Either way, any advice is greatly appreciated!
Here's the fetch and display portion of the code:
populateListViewFromDB();
}
#SuppressWarnings("deprecation")
private void populateListViewFromDB() {
Cursor cursor = db.getAllRecords();
//Allow activity to manage cursor lifetime
startManagingCursor(cursor);
//Setup mapping from cursor to view fields:
String [] fromFieldNames = new String []
{DBAdapter.KEY_ROWID, DBAdapter.KEY_GENRE, DBAdapter.KEY_TITLE, DBAdapter.KEY_PLATFORM, DBAdapter.KEY_DATE, DBAdapter.KEY_PRICE, DBAdapter.KEY_WHEREBOUGHT};
int [] toViewIDs = new int []
{R.id.RecordNumberEdit, R.id.textView1, R.id.textView2, R.id.textView3, R.id.textView4, R.id.textView5, R.id.textView6};
//Create mapping from cursor to view fields
SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(
this,
R.layout.database_view_layout,
cursor, //Set of DB records
fromFieldNames, //DB field Names
toViewIDs //View IDs in which to put info
);
//Set the adapter for the list view
ListView listViewFromDB = (ListView) findViewById(R.id. listViewFromDB);
listViewFromDB.setAdapter(myCursorAdapter);
I changed the VACCUUM code to the following since the original code was actually passing the query twice :
String sql = "VACUUM;" ;
db.execSQL(sql);
Still, though, nothing seems to be happening.

listview display images from internet and data from sqlite

My cursor gets 3 columns of data from sqlite, 1st column is recipe name, 2nd column in recipe author and 3rd column is the url for the recipe's image. here's a portion of my code
private static final String fields[] = { "recipeID", "recipeName", "thumbnail"};
Cursor mCursor = dbAdapter.getAllTitles(); //get all titles returns the recipe name, author and thumbs
startManagingCursor(mCursor);
dataSource = new SimpleCursorAdapter(this, R.layout.recipelist, mCursor, fields,
new int[] { R.id.recipeAuthor, R.id.recipeName, R.id.recipeThumb });
setListAdapter(dataSource);
Obviously instead of displaying the recipe image, the code above just displays the url for the recipe image at R.id.recipeThumb. How can I make it display pictures from the internet instead?
The post right below the answer in this discussion might be of use to you:
Lazy load of images in ListView
You need a CustomAdapter and override the getView() method.
In the getView() method based on the Url you create a ImageView.
getView(...) {
//First Create a Drawable from the InputStream of the Url
//store this drawable locally so that you don't have to fetch it again
Drawable imgDrawable = Drawable.createFromStream(inputStream,"");
//set this in the imageView
imgView.setImageDrawable(imgDrawable);
//set this imgView in the contentview and return
}

Android - store/set imageResource path in database?

Cursor c = dbHelper.getMostRecent();
String[] from = new String[] { "name", "data", "thumb" };
int[] to = new int[] { R.id.activityName, R.id.activityData, R.id.activityThumb };
startManagingCursor(c);
SimpleCursorAdapter activities;
activities = new SimpleCursorAdapter(this, R.layout.activitywidget, c, from, to);
setListAdapter(activities);
On the second line, I'm grabbing the name, data, and thumb from the database.
On the third line, I'm setting those values for activityName (TextView), activityData (TextView), and activityThumb (ImageView).
It works fine for "name" and "data", but I have no idea what to put for "thumb".
I have some images in /res/drawable/, but I'm not sure how to store them in the database (file path as a string? R.drawable.IMAGE_NAME as a string? Do I need to save it as raw data somehow?)
Best case scenario: I'd like to just tell each instance of activityThumb in the list what image path it should be using as its resource.
EDIT: I figured it out by creating an implementation of SimpleCursorAdaptor and overriding bindView.
R.drawable.IMAGE_NAME is an integer. You can store it into the database, but it might change on the next build and break all existing databases.
You can do an enum with 2 fields: One "external representation" string that you can store in the database and one int that represents the resource identifier. You would also need a way to restore the enum from the string representation, e.g. using a map.
I figured it out by creating an implementation of SimpleCursorAdaptor and overriding bindView.
public void bindView(View view, Context context, Cursor cursor) {
ImageView imageView = (ImageView) view.findViewById(R.id.image);
//do stuff with image here
super.bindView(view, context, cursor);
}

Android: Cursor results to String[]

I have a query in my android app that pulls all image paths from a custom table and displays them to a gallery. The problem is with my database I cant seem to get a row of the database to a String[]. I can easily get the results to a listArray but I need the image path in a string or string array. I want to be able to click on an image in the gallery and have it pull up full screen to be able to zoom in on it or delete it etc. This is the basic query i use
public void listimages() {
SimpleCursorAdapter adapter;
String[] columns = {"Image", "ImageDate", "_id"};
query = new TableImages(this);
queryString = query.getData("images", columns, null, null, null, null, "ImageDate", "DESC");
int to[] = {R.id._id1, R.id._id2};
adapter = new SimpleCursorAdapter(this, R.layout.imagelist, queryString, columns, to);
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(adapter);
g.setOnItemClickListener(this);
try {
query.destroy();
} catch (Throwable e) {
e.printStackTrace();
}
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(ViewAllImages.this, ImageViewer.class);
Bundle b = new Bundle();
//I want to be able to use this -> b.putString("image_path", Image);
b.putlong("id", id);
i.putExtras(b);
startActivity(i);
}
This passes the ID to my next activity and the next activity queries the DB pulling that one image path. I still have to use a listview to display the image which makes the app crash on the phone due to memory usage (image is too large).
I can compress the image but I need the path as a string and I cant figure out how to do that without creating a custom content provider or adding a textview and using gettext.toString and thats just getto. My head is killing me as it is with all the reading and coding I have done lol. I have searched all over Google and different forums but I am having problems finding an answer.
Is there a way to use the existing query and get a string or a string array as the result?
Thanks.
I just ended up building a custom content provider. Now I have alot more flexability in my queries.

Categories

Resources