Setting the resource of an ImageView using a CursorLoader - android

Sorry for such an open-ended question, but I'm new to Android and I genuinely looked all over for an answer and couldn't find anything. I'm wanting to store some sort of information that references an image in a SQLite table, and then use a SimpleCursorAdapter to move that data to an ImageView. I thought that, if I store an integer (the resource ID) and then have the adapter set to the correct view, the resource of the view would be updated to that ID, but that didn't work. Is there any other way to do what I'm wanting to do?
Thanks in advance :)
Edit 1:
This is what I'm doing right now. I'm storing the drawable's ID in the table and then setting the SimpleCursorAdapter to a View whose resource I want to be the drawable. Here's the code I use to store the info:
ContentValues values = new ContentValues();
values.put(SubwayContract.ROUTE_IMG, R.drawable.red_circle);
values.put(SubwayContract.ROUTE, "R");
values.put(SubwayContract.FINAL_STATION, "Howard-Bound");
values.put(SubwayContract.ARRIVAL_TIME, "5:24:00");
final Uri uri = mContentResolver.insert(SubwayContract.CONTENT_URI, values);
The second line stores the image ID. Here's the code I have that sets the adapter:
private final int URL_LOADER = 0;
private String[] mProjections = {SubwayContract._ID, SubwayContract.ROUTE_IMG, SubwayContract.ROUTE, SubwayContract.FINAL_STATION, SubwayContract.ARRIVAL_TIME};
private int[] mTo = {R.id._id, R.id.arrival_icon, R.id.arrival_letter, R.id.arrival_dest, R.id.arrival_time};
private SimpleCursorAdapter mAdaptor = null;
...
getLoaderManager().initLoader(URL_LOADER, null, ArrivalsFragment.this);
ListView mListView = (ListView) rootView.findViewById(R.id.arrivals_list_view);
mAdaptor = new SimpleCursorAdapter(
rootView.getContext(),
R.layout.arrivals_list_item,
null,
mProjections,
mTo,
0
);
mListView.setAdapter(mAdaptor);
The View's ID is R.id.arrival_icon, which is a View. I know that there's no error in the cursor or the loader, as everything works fine if I take out the View and ID. How can I fix this?

You can save resource Id of the image (which is in drawable folder) into database.
You can try as below:
int resID = mContext.getResources().getIdentifier(image_name, "drawable", mContext.getPackageName());

Related

Linking listview to sqlite database

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
}

update My Spinner from SQlite Database

I FOUND A SOLUTION FOR RESTORING MY VALUES, SEE MY NEW VERSION of populateFields()
Okay so I have been reading through all the Spinner and SQlite posts on here and cannot seem to find a good answer for what I am looking for so I am posting this scenario.
My app has two screens and uses the sqlite database on my device saving a name and weight fields from editTexts as strings like so
String eName = name.getText().toString();
String eWeight = weight.getText().toString();// where name and weight are EditTexts
and I have two spinners as follows
String eReps = spinReps.getSelectedItem().toString();
String eSets = spinSets.getSelectedItem().toString();
Then I call this to add to the database
long id = mDbHelper.createExercise(eName, eWeight, eReps, eSets);
Here is where my issue is, upon someone selecting to create a new exercise my app crashes because it is trying to populate a spinner incorrectly. Here is what I have currently.
private void populateFields(){
if(mRowId != null){ // where mRowId is the selected row from the list
Cursor exercise = mDbHelper.fetchExercise();
name.setText(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_NAME)));
weight.setText(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_WEIGHT)));
// this is the part that i need help with, I do not know how to restore
// the current items spinner value for reps and sets from the database.
spinReps.setSelection(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_REPS)));
spinSets.setSelection(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_SETS)));
}
I assume I need to use some sort of adapter to restore my list items along with the current value from the database, I am just not sure how.
Can someone please help me with this???
** BELOW IS MY SOLUTION**
I had to move my ArrayAdapters repsAdapter, spinAdapter out of my onCreate()
and then implement this new populateFields()
private void populateFields(){
if(mRowId != null){
Cursor exercise = mDbHelper.fetchExercise(mRowId);
// same as before
name.setText(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_NAME)));
// get the string for sReps and sSets from the database
String sReps = exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_REPS));
String sSets = exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_SETS));
// use the strings to get their position in my adapters
int r = repsAdapter.getPosition(sReps);
int s = setsAdapter.getPosition(sSets);
// set their returned values to the selected spinner Items
spinReps.setSelection(r);
spinSets.setSelection(s);
// same as before
weight.setText(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_WEIGHT)));
}
}
The way to set a Spinner to a value, not a position, depends on what adapter you are using.
ArrayAdapter, this one is easy:
int position = adapter.getPosition(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_REPS)));
spinReps.setSelection(position);
SimpleCursorAdapter, this one is a little harder:
String match = exercise.getString(exercise.getColumnIndexOrThrow(ExerciseDbAdapter.KEY_REPS));
Cursor cursor = adapter.getCursor();
cursor.moveToPosition(-1);
int columnIndex = cursor.getColumnIndexOrThrow(ExerciseDbAdapter.KEY_REPS);
while(cursor.moveToNext()) {
if(cursor.getString(columnIndex).equals(match))
break;
}
spinReps.setSelection(cursor.getPosition());
If you are using a different type of adapter and can't modify the code above to fit it, let me know. Hope that helps!

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