public class ImageLoader {
Context ctx;
// Initialize MemoryCache
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
//Create Map (collection) to store image and image url in key value pair
private Map<ImageView, String> imageViews = Collections.synchronizedMap(
new WeakHashMap<ImageView, String>());
ExecutorService executorService;
//handler to display images in UI thread
Handler handler = new Handler();
public ImageLoader(Context context){
fileCache = new FileCache(context);
ctx=context;
// Creates a thread pool that reuses a fixed number of
// threads operating off a shared unbounded queue.
executorService=Executors.newFixedThreadPool(5);
}
// default image show in list (Before online image download)
final int stub_id=R.drawable.index;
public void DisplayImage(String url, ImageView imageView)
{
//Toast.makeText(ctx, "IMAGE URL in loader=="+url, Toast.LENGTH_SHORT).show();
//Store image and url in Map
imageViews.put(imageView, url);
//Check image is stored in MemoryCache Map or not (see MemoryCache.java)
Bitmap bitmap = memoryCache.get(url);
if(bitmap!=null){
// if image is stored in MemoryCache Map then
// Show image in listview row
imageView.setImageBitmap(bitmap);
}
else
{
//queue Photo to download from url
queuePhoto(url, imageView);
//Before downloading image show default image
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView)
{
// Store image and url in PhotoToLoad object
PhotoToLoad p = new PhotoToLoad(url, imageView);
// pass PhotoToLoad object to PhotosLoader runnable class
// and submit PhotosLoader runnable to executers to run runnable
// Submits a PhotosLoader runnable task for execution
executorService.submit(new PhotosLoader(p));
}
//Task for the queue
private class PhotoToLoad
{
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i){
url=u;
imageView=i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad){
this.photoToLoad=photoToLoad;
}
@Override
public void run() {
try{
//Check if image already downloaded
if(imageViewReused(photoToLoad))
return;
// download image from web url
Bitmap bmp = getBitmap(photoToLoad.url);
// set image data in Memory Cache
memoryCache.put(photoToLoad.url, bmp);
if(imageViewReused(photoToLoad))
return;
// Get bitmap to display
BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
// Causes the Runnable bd (BitmapDisplayer) to be added to the message queue.
// The runnable will be run on the thread to which this handler is attached.
// BitmapDisplayer run method will call
handler.post(bd);
}catch(Throwable th){
th.printStackTrace();
}
}
}
private Bitmap getBitmap(String url)
{
File f=fileCache.getFile(url);
//from SD cache
//CHECK : if trying to decode file which not exist in cache return null
Bitmap b = decodeFile(f);
if(b!=null)
return b;
// Download image file from web
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
// Constructs a new FileOutputStream that writes to file
// if file not exist then it will create file
OutputStream os = new FileOutputStream(f);
// See Utils class CopyStream method
// It will each pixel from input stream and
// write pixels to output stream (file)
Utils.CopyStream(is, os);
os.close();
conn.disconnect();
//Now file created and going to resize file with defined height
// Decodes image and scales it to reduce memory consumption
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex){
ex.printStackTrace();
if(ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
//Decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
o.inSampleSize =2;
FileInputStream stream1=new FileInputStream(f);
BitmapFactory.decodeStream(stream1,null,o);
stream1.close();
//Find the correct scale value. It should be the power of 2.
// Set width/height of recreated image
final int REQUIRED_SIZE=85;
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2 < REQUIRED_SIZE || height_tmp/2 < REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//decode with current scale values
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize= scale;
FileInputStream stream2=new FileInputStream(f);
Bitmap bitmap=BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
return bitmap;
} catch (FileNotFoundException e) {
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
boolean imageViewReused(PhotoToLoad photoToLoad){
String tag=imageViews.get(photoToLoad.imageView);
//Check url is already exist in imageViews MAP
if(tag==null || !tag.equals(photoToLoad.url))
return true;
return false;
}
//Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable
{
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
public void run()
{
if(imageViewReused(photoToLoad))
return;
// Show bitmap on UI
if(bitmap!=null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
//Clear cache directory downloaded images and stored data in maps
memoryCache.clear();
fileCache.clear();
}
}
广告类
中的Advertise()
private void getAdvertise()
{
SQLiteDatabase sd=dbHelper.getReadableDatabase();
String sql1="select * from "+ Advrtise.TABLE_ADVRTISE ;
String sql= sql1;
//Log.e("****", sql+ "** **advt **");
Cursor cc=sd.rawQuery(sql, null);
while(cc.moveToNext())
{
ad_id.add(cc.getString(0));//ad_id
ad_imgurl.add(cc.getString(1));//ad_img
ad_use.add(cc.getString(2));//ad_use
}
imageLoader = new ImageLoader(getApplicationContext());
final Handler mHandler = new Handler();
// Create runnable for posting
final Runnable mUpdateResults = new Runnable() {
private int index=0;
public void run() {
if(index < ad_use.size()){
//Log.i("-=-=-=-=-", index+"-=-=-=---ad use:"+ad_use.get(index));
if(ad_use.get(index).equals("android")){
imageLoader.DisplayImage(ad_imgurl.get(index), advt);
}
index++;
}else {
index=0;
}
}
};
int delay =0;// 1000; // delay for 1 sec.
int period = 4000; // repeat every 4 sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
mHandler.post(mUpdateResults);
}
}, delay, period);
}
protected void animation1() {
TranslateAnimation animation = new TranslateAnimation(0.0f, 400.0f,
0.0f, 0.0f); // new TranslateAnimation(xFrom,xTo, yFrom,yTo)
animation.setDuration(5000); // animation duration
animation.setRepeatCount(5); // animation repeat count
animation.setRepeatMode(2); // repeat animation (left to right, right to left )
advt.startAnimation(animation); // start animation
}
活动类中的getRelatedNews ///正常工作在imageview中显示图像
private void getRelatedNews() {
//from related id get news title and img to display
SQLiteDatabase sd=dbHelper.getReadableDatabase();
String sql1="select * from "+ News.TABLE_NAME ;
String sql= sql1;
Log.e("****", sql+ "** **related **");
Cursor cc=sd.rawQuery(sql, null);
while(cc.moveToNext())
{
related_id.add(cc.getString(1));//n_id
related_title.add(cc.getString(2));
related_desc.add(cc.getString(3));
related_imgurl.add(cc.getString(5));
//Log.e("====",cc.getString(1)+"");
}
for (int i = 0; i < related_id.size(); i++) {
if(!(related_id.get(i)).isEmpty()){
//Log.e("====",a+"---check--"+select);
//if( (related_id.get(i)).equals(bundle_id.get(i)) ) {
for (int j = 0; j < bundle_id.size(); j++) {
if((bundle_id.get(j)).equals(related_id.get(i)) ) {
Log.e("====",related_id.get(i)+"---match--"+bundle_id.get(j));
related_imgurl.add(imgurl.get(i));
related_title.add(n_title.get(i));
}
}// j for
}/*else {
Log.e("---NO MATCH--", related_id+"---"+bundle_id.get(i));
} */
}//for
final Handler mHandler = new Handler();
// Create runnable for posting
final Runnable mUpdateResults = new Runnable() {
public void run() {
if(index < related_imgurl.size()){
imageLoader.DisplayImage(related_imgurl.get(index), rel_image);
relatedTit.setText(""+related_title.get(index));
index++;
}else {
index=0;
}
}
};
int delay =0;// 1000; // delay for 1 sec.
int period = 5000; // repeat every 4 sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
mHandler.post(mUpdateResults);
}
}, delay, period);
}
protected void animation() {
TranslateAnimation animation = new TranslateAnimation(0.0f, 400.0f,
0.0f, 0.0f); // new TranslateAnimation(xFrom,xTo, yFrom,yTo)
animation.setDuration(5000); // animation duration
animation.setRepeatCount(5); // animation repeat count
animation.setRepeatMode(2); // repeat animation (left to right, right to left )
rel_image.startAnimation(animation); // start animation
}
在数据库文件中广告表
// -----------------------------表到商店新闻------------ ------------
private static final String SQL_CREATE_ADVERTISETBL = "CREATE TABLE " + Advrtise.TABLE_ADVRTISE + " ( " +
Advrtise._ID+" INTEGER PRIMARY KEY AUTOINCREMENT," +
Advrtise.COLUMN_advt_id +" INTEGER," +
Advrtise.COLUMN_advt_img + " TEXT," +
Advrtise.COLUMN_advt_useby + " TEXT" +
" ) ";
请检查所有代码并回复我错误的地方..... 我正在尝试几天..