Android adapter arrayadapter or cursor? - android

I have to set ListView and to fill it by data. I have bitmaps in external storage and name of that bitmaps in table, also I have other data in sqlite beside name of bitmap.
The mechanism is following. I have to get from table name add to path and load bitmap, also with other data from table for specific row.
Which adapter you can recommend me to use?
I tried with CursorAdapter but didn't get success because I have problem with loading and repeating images in ListView.
Here is part of my code:
holder.pic = (ImageView) view.findViewById(R.id.adapterInterPicture);
holder.picIndex = cursor.getColumnIndexOrThrow(BaseHelper.PIC_DATE);
holder.picCheck = cursor.getString(holder.picIndex);
holder.imagePath = Environment.getExternalStorageDirectory() + "/imagesGallery/"+ holder.picCheck + ".jpg";
holder.options=new BitmapFactory.Options();
holder.options.inSampleSize = 8;
holder.bitmap1 = BitmapFactory.decodeFile(holder.imagePath,holder.options);
After that in bind view I use the folllowing code:
if(holder.bitmap1 == null){holder.pic.setImageResource(R.drawable.intermediate_pic);
}
if(holder.bitmap1 != null){
holder.pic.setImageBitmap(holder.bitmap1);
}

Related

Android :How to load image dynamically from server by its name from SQlite

I am new to android and I'm facing an issue while displaying image from server based its name from Sqlite
ie:
I stored only image name (text) in SQLite database (column name images) and I want to load images from Server based on the sqlite image name the image want to display in imageview
In server I create a folder like Cars in that folder I store images with car names..but in sqlite I just add a carname in text format with .jpeg
I have two column names in my DB:
first is Car name
Second is Car Detail
When user selects the Car name, in next activity the user can see the Car details with images.
Here I display Details, But I don't know How to display Car Images From Server
Thanks
Here is my Code:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_activity);
detailtext= (TextView) findViewById(R.id.detail);
imageView= (ImageView) findViewById(R.id.images);
Intent intent= getIntent();
final String selectedData = intent.getStringExtra("selectedItem");
actionBar.setTitle(selectedData);
dbHelper = new SqlLiteDbHelper(this);
try {
dbHelper.openDataBase();
} catch (SQLException e) {
e.printStackTrace();
}
sqLiteDatabase = dbHelper.getReadableDatabase();
cursor=dbHelper.getdetails(sqLiteDatabase, selectedData);
if (cursor.moveToFirst()) {
detailtext.setText(cursor.getString(0));
String imagename = cursor.getString(1);
String imageUrl = "http://your_server/car/" + imagename ;
Picasso.with(this).load(imageUrl).into(imageView );
}
Note:Image Field is the 4th Column http://i.stack.imgur.com/lqvOQ.png
and in server i put image in www.server.com/cars/carnames.jpg
in sqlite i just paste the image name with .jpg ex:carnames.jpg
SqliteDbHelper
public Cursor getdetails(SQLiteDatabase db,String img)
{
db=this.getReadableDatabase();
Cursor cursor;
cursor=db.query("record",new String[]{DETAIL,IMAGES,ITEMNO + " as _id"},SUBCATEGORY + "='" +img+"'",null,null,null,null);
return cursor;
}
If you want to load images from SQlite then I suggest you save the file/file location if the data is stored locally, for the showing of a single image on all image view it is because you are only loading a single image, you might want to put all your ids in an array and passing it to the db, the db query should also return an array/arraylist of image locations which you should load into your image views using a for loop e.g I have a query that loads a bunch of images from my SQLite database, this displays sub-category images of a certain category named shoes so we have images of smart shoes, Casual shoes and more I pass an an Id as parameter
public ArrayList<CategoryItem> getAllSubCategories(int mtargetID) throws SQLException{
ArrayList<CategoryItem> myshoes = new ArrayList<>();
// Select All Query
String sQuery = " SELECT "+Constant.CATEGORY_TB_ID+", "+Constant.SUB_DESCRIPTION+
", "+Constant.SUB_IMAGEPATH+" FROM "+Constant.CATEGORY_TABLE+
" INNER JOIN "+Constant.SUB_CATEGORY_TABLE+" ON "+Constant.CATEGORY_TB_ID +" = " +Constant.SUB_CATEGORY_FK
+ " WHERE "+Constant.CATEGORY_TB_ID +" = ?";
String[] args = new String[1];
args[0] = String.valueOf(mtargetID);
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(sQuery, args);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
CategoryItem myShoesItem = new CategoryItem();
//my shoe image path on external storage
myShoeItem.setmCategoryImgPath(cursor.getString(2));
//i add my image paths to my array list
myshoes.add(myShoeItem);
} while (cursor.moveToNext());
}
// return my arraylist for display into my imageview
return mshoes;
}
on the receiving side I then transverse through my araylist
for(int i = 0; i <getAllSubCategories.size(); i++ )
{
imageView.setImageUri(getAllSubCategories.get(i).getmCategoryImgPath())
}
with this method you will set images to all your imageviews.
You have the path "url" request to the server? like this:
http://server_ip/api/images?imageName="The name you image here"
Then do you need use some lib to load image from server, see this:
Android Picasso
So, something like this:
Picasso.with(context).load("http://server_ip/api/images?imageName="The name you image here.png/jpeg").into(imageView);
You're saying that in your server, you've created a directory called cars/ and all images are in jpeg format and also with same file name as their real names. If I'm correct, so your can use codes below.
Intent intent= getIntent();
final String selectedData = intent.getStringExtra("selectedItem");
actionBar.setTitle(selectedData);
// This a image declared in XML for displaying car image
ImageView carImageView = (ImageView) findViewById(R.id.carImage);
// URL of this car's image
String imageUrl = "http://your_server_address/cars/" + carName + ".jpeg";
// Use Picasso library to load that image
Picasso.with(this).load(imageUrl).into(carImageView);
Note: Picasso is a fearure rich library for fetching images from network in Android.

how to add several images in a listview after getting their names from the sqlite database

i have an android application that use sqlite and after it fetch the data it must be displayed in a listview.
my question is how to display images?
can anyone help me ???
this my code
//but here it display the same image for the hall list how to display each image in its right place ??
for (int i = 0; i < 49; i++) {
ImageView imagenow = (ImageView) convertView
.findViewById(R.id.imageView1);
// flag1
int imageid = context.getResources().getIdentifier("brazil_flag",
"drawable", context.getPackageName());
imagenow.setImageResource(imageid);
}
Thinking in terms of MVC will help MVC pattern in Android?
Create a Layout with ListView which holds Images in each element
Create an Adapter to read the images from Database
In the Activity, use the Adapter to fill Images in the ListView

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
}

Displaying images from a specific folder on the SDCard using a gridview

I'm attempting to create a gridview that is loaded with images from a specific folder that resides on an SDCard. The path to the folder is known, ("/sdcard/pictures") , but in the examples I've seen online I am unsure how or where to specify the path to the pictures folder I want to load images from. I have read through dozens of tutorials, even the HelloGridView tutorial at developer.android.com but those tutorials do not teach me what i am seeking.
Every tutorial I have read so far has either:
A) called the images as a Drawable from the /res folder and put them into an array to be loaded, not using the SDCard at all.
B) Accessed all pictures on the SDCard using the MediaStore but not specifying how to set the path to the folder I want to display images form
or
C) Suggested using BitmapFactory, which I haven't the slightest clue how to use.
If I'm going about this in the wrong way, please let me know and direct me toward the proper method to do what I'm trying to do.
OK, after many iterations of trying, I finally have an example that works and I thought I'd share it. My example queries the images MediaStore, then obtains the thumbnail for each image to display in a view. I am loading my images into a Gallery object, but that is not a requirement for this code to work:
Make sure you have a Cursor and int for the column index defined at the class level so that the Gallery's ImageAdapter has access to them:
private Cursor cursor;
private int columnIndex;
First, obtain a cursor of image IDs located in the folder:
Gallery g = (Gallery) findViewById(R.id.gallery);
// request only the image ID to be returned
String[] projection = {MediaStore.Images.Media._ID};
// Create the cursor pointing to the SDCard
cursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection,
MediaStore.Images.Media.DATA + " like ? ",
new String[] {"%myimagesfolder%"},
null);
// Get the column index of the image ID
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
g.setAdapter(new ImageAdapter(this));
Then, in the ImageAdapter for the Gallery, obtain the thumbnail to display:
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(context);
// Move cursor to current position
cursor.moveToPosition(position);
// Get the current value for the requested column
int imageID = cursor.getInt(columnIndex);
// obtain the image URI
Uri uri = Uri.withAppendedPath( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, Integer.toString(imageID) );
String url = uri.toString();
// Set the content of the image based on the image URI
int originalImageId = Integer.parseInt(url.substring(url.lastIndexOf("/") + 1, url.length()));
Bitmap b = MediaStore.Images.Thumbnails.getThumbnail(getContentResolver(),
originalImageId, MediaStore.Images.Thumbnails.MINI_KIND, null);
i.setImageBitmap(b);
i.setLayoutParams(new Gallery.LayoutParams(150, 100));
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setBackgroundResource(mGalleryItemBackground);
return i;
}
I guess the most important section of this code is the managedQuery that demonstrates how to use MediaStore queries to filter a list of image files in a specific folder.
You need to do a few more steps than the GridView tutorial on developer.android.com. Using the following tutorial
http://developer.android.com/resources/tutorials/views/hello-gridview.html
You'll want to add a method to create ImageView's of the files from your sd card:
Create/add a Vector to your class variables (to hold a list of ImageViews):
private Vector<ImageView> mySDCardImages;
Initialize the vector:
mySDCardImages = new Vector<ImageView>();
Create a method to load images:
List<Integer> drawablesId = new ArrayList<Integer>();
int picIndex=12345;
File sdDir = new File("/sdcard/pictures");
File[] sdDirFiles = sdDir.listFiles();
for(File singleFile : sdDirFiles)
{
ImageView myImageView = new ImageView(context);
myImageView.setImageDrawable(Drawable.createFromPath(singleFile.getAbsolutePath());
myImageView.setId(picIndex);
picIndex++;
drawablesId.add(myImageView.getId());
mySDCardImages.add(myImageView);
}
mThumbIds = (Integer[])drawablesId.toArray(new Integer[0]);
Then down in your ImageAdapter method, change
imageView.setImageResource(mThumbIds[position]);
to
imageView.setImageDrawable(mySDCardImages.get(position).getDrawable());
Remove from the ImageAdapter the initialization of mThumbIds. (it should be up with the definition of mySDCardImages. Accessible to both class methods.)
(Quick and dirty version) Make sure to test your path, etc and catch any Exceptions.
In your case BitmaFactory might be a good way to go. Example:
File dir = new File( "/sdcard/pictures" );
String[] fileNames = dir.list(new FilenameFilter() {
boolean accept (File dir, String name) {
if (new File(dir,name).isDirectory())
return false;
return name.toLowerCase().endsWith(".png");
}
});
for(string bitmapFileName : fileNames) {
Bitmap bmp = BitmapFactory.decodeFile(dir.getPath() + "/" + bitmapFileName);
// do something with bitmap
}
Not time to test this but should work ;-)
read this link: http://androidsamples.blogspot.com/2009/06/how-to-display-thumbnails-of-images.html
it shows how to use both mediastore and bitmapfactory.
the way you should chose depends on what exactly you need. if you have a static set of images, it's much better idea to put them to drawables, i think, cause this way it's faster and you don't rely on sd card, which can be removed, corrupt or files could be renamed/deleted
if images are dynamic, then use mediastore or bitmap factory. but keep in mind that putting images into array or something it's quite memory consuming, so you can end up having outofmemory exception
Looks like you want custom gallerry, it will take much time for you,
I suggest you get Custom Camera Gallery for your working.
You will get Photos/Videos in Grid View as you want.
for Kotlin code see the answer of this question
the idea is alslo applicable for java (but you need to modify the code)

How to display images from SD card in a GalleryView

I am trying to display all the images stored in SD card in a Gallery View.
I have tried using the content provider (android.provider.MediaStore.images.Media class), but seem to be getting stuck at a point. Not sure if this is the way to go about it.
Here is my code so far:
String[] colsNeeded = new String[]{Media._ID, Media.TITLE};
Uri mMedia = Media.EXTERNAL_CONTENT_URI;
//Create a cursor using the URI & column names needd
Cursor c = managedQuery(mMedia, colsNeeded, null, null, Media.DATE_TAKEN + " ASC");
//What kind of adapter should I create here
//that contains images from the cursor??
SpinnerAdapter sa = null; //This is the point I get stuck
//Set the adapter of the gallery view
Gallery galleryPetPhotos = (Gallery)findViewById(R.id.GalleryPetPhotos);
galleryPetPhotos.setAdapter(sa);
Just a nudge in the right direction would be greatly appreciated.
This blog post has a good example on that. It shows you how to do the adapter: http://mihaifonoage.blogspot.com/2009/09/displaying-images-from-sd-card-in.html
However I would be extending a CursorAdapter instead of a BaseAdapter.

Categories

Resources