android下载图像,然后使用sqlite从SD卡读取它

时间:2011-04-24 04:51:08

标签: android image sqlite download save

我的问题是我有一个代码,假设接收一个变量,其中包含一个有图像的网站,所以这个变量每次发送新链接时都会更改,此代码应该联机并下载图像并将其保存到sd-card然后我读它并显示它

所以我的代码问题是如果我发送2个链接,它下载1个图像,它总是用第二个图像名称存储它(例如:im发送image1和image2代码下载image1两次并存储它作为“image2”)当我挂载SD卡并检查图像目录时只有1个图像名为image2,我认为doInBackground导致问题,但我也使用onPostExecute()所以,如果有人可以帮助我我会感谢他的帮助请注意这就是我所说的: 注意:我的代码没有错误//没有红色标记 这就是所有代码:

        private void UpdateAds(String Bookinfo,TextView myText){
                elhgsdatabase db = new elhgsdatabase(this);

                if (Bookinfo != "didn't read titels"){

                    String debContent=""; 
                    String output ="";
                    int NUMBEROFFIELDS = 5;
                    String s = addressString;
                    long idx;

                    String [] buffer = new String[NUMBEROFFIELDS];
                    output = "";

                    int l = 0;
                    while (s.indexOf("[")>-1){
                        int fk = s.indexOf("[");
                        int fl = s.indexOf("]");

                        if(fk > -1){
                             buffer[l] = s.substring(fk+1, fl);
                            s = s.substring(fl+1);
                            l++;

                            if (l == NUMBEROFFIELDS){
                    //1. Query the database to check if the book exists
                                //---get all titles---
                                db.open();        


   Cursor c = db.getBookTitle (buffer[0]); 
   if (c.getCount()==1) 
{ myText.setText("This Books Exist \n"); }
      else if(c.getCount()==0)
    { String locLink;  
      locLink = getLocalLink(buffer[3], buffer[0]);
      c.moveToFirst();

    if (!locLink.equalsIgnoreCase("-1")){
    idx= db.insertTitle(buffer[0], buffer[1], buffer[2], getDate(buffer[3]), buffer[4], locLink);
    }
    else { //there was a problem with retrieval-saving of the Book info locally
    myText.setText("There was a problem with retrieval-saving of the Book info locally\n");
                                          }
                                          }//if(c.getCount()==0)


        else{//The table has two Books with the same Name. Do something
     myText.setText("The table has two Books with the same Name\n");
                                    }

                                c.close();

                            l = 0;
                            }//if(l == NUMBEROFFIELDS)

                        } //if (fk>-1)
                    }//while    
                    db.close();
                } //of if(BookInfo...
                else {
                    myText.setText("Nothing is Done\n");
                }

            }
            //This method gets the local link field of the active book records
            // it goes on the web, gets the content and stores it in a place 
            // and saves the path of that place in the database for that
            //it returns -1 if something wrong happened during the process

            public String getLocalLink(String image_URL, String BookName){
                /** This is what we do with this method:
                 * Go online, according to the link, get the content, call the method to save, get the local link
                 * and return it
                 */

                setContentView(R.layout.main);

                reviewImageLink = image_URL;
                URL reviewImageURL;
                String name = reviewImageLink.substring(reviewImageLink.lastIndexOf("/") + 1);
                try {
                    reviewImageURL = new URL(reviewImageLink);
                    if (!hasExternalStoragePublicPicture(name)) {
                        isImage = false;
                        new DownloadImageTask().execute(reviewImageURL);
                        Log.v("log_tag", "if");
                        isImage = true;
    File sdImageMainDirectory = new File(Environment.getExternalStorageDirectory(), getResources()
                                .getString(R.string.directory));
                        sdImageMainDirectory.mkdirs();
                        File file = new File(sdImageMainDirectory, name);
                        Log.v("log_tag", "Directory created");
                    }

                } catch (MalformedURLException e) {
                    Log.v(TAG, e.toString());
                }
                return ("/sdcard/Hanud/"+BookName+".jpg");


            }


            private class DownloadImageTask extends AsyncTask<URL, Integer, Bitmap> {
                // This class definition states that DownloadImageTask will take String
                // parameters, publish Integer progress updates, and return a Bitmap
                protected Bitmap doInBackground(URL... paths) {
                    URL url;
                    try {
                        url = paths[0];
       HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                        int length = connection.getContentLength();
                        InputStream is = (InputStream) url.getContent();
                        byte[] imageData = new byte[length];
       int buffersize = (int) Math.ceil(length / (double) 100);
                        int downloaded = 0;
                        int read;
                        while (downloaded < length) {
        if (length < buffersize) {
    read = is.read(imageData, downloaded, length);} 
    else if ((length - downloaded) <= buffersize) {
    read = is.read(imageData, downloaded, length- downloaded);
        } 
    else {read = is.read(imageData, downloaded, buffersize);}
                downloaded += read;
        publishProgress((downloaded * 100) / length);
                        }
                        Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0,
                                length);
                        if (bitmap != null) {
                            Log.i(TAG, "Bitmap created");
                        } else {
                            Log.i(TAG, "Bitmap not created");
                        }
                        is.close();
                        return bitmap;
                    } catch (MalformedURLException e) {
                        Log.e(TAG, "Malformed exception: " + e.toString());
                    } catch (IOException e) {
                        Log.e(TAG, "IOException: " + e.toString());
                    } catch (Exception e) {
                        Log.e(TAG, "Exception: " + e.toString());
                    }
                    return null;

                }

                protected void onPostExecute(Bitmap result) {
                    String name = reviewImageLink.substring(reviewImageLink
                            .lastIndexOf("/") + 1);
                    if (result != null) {
                        hasExternalStoragePublicPicture(name);
                        saveToSDCard(result, name);
                        isImage = true;

                    } else {
                        isImage = false;

                    }
                }
            }

            public void saveToSDCard(Bitmap bitmap, String name) {
                boolean mExternalStorageAvailable = false;
                boolean mExternalStorageWriteable = false;
                String state = Environment.getExternalStorageState();
                if (Environment.MEDIA_MOUNTED.equals(state)) {
                    mExternalStorageAvailable = mExternalStorageWriteable = true;
                    Log.v(TAG, "SD Card is available for read and write "
                            + mExternalStorageAvailable + mExternalStorageWriteable);
                    saveFile(bitmap, name);
                } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
                    mExternalStorageAvailable = true;
                    mExternalStorageWriteable = false;
                    Log.v(TAG, "SD Card is available for read "
                            + mExternalStorageAvailable);
                } else {
                    mExternalStorageAvailable = mExternalStorageWriteable = false;
                    Log.v(TAG, "Please insert a SD Card to save your Video "
                            + mExternalStorageAvailable + mExternalStorageWriteable);
                }
            }

            private void saveFile(Bitmap bitmap, String name) {
                String filename = name;
                ContentValues values = new ContentValues();
                File sdImageMainDirectory = new File(Environment
                        .getExternalStorageDirectory(), getResources().getString(
                        R.string.directory));
                sdImageMainDirectory.mkdirs();
                File outputFile = new File(sdImageMainDirectory, filename);
                values.put(MediaStore.MediaColumns.DATA, outputFile.toString());
                values.put(MediaStore.MediaColumns.TITLE, filename);
                values.put(MediaStore.MediaColumns.DATE_ADDED, System
                        .currentTimeMillis());
                values.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
                Uri uri = this.getContentResolver().insert(
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,

                        values);
                try {
                    OutputStream outStream = this.getContentResolver()
                            .openOutputStream(uri);
                    bitmap.compress(Bitmap.CompressFormat.PNG, 95, outStream);

                    outStream.flush();
                    outStream.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            private boolean hasExternalStoragePublicPicture(String name) {
                File sdImageMainDirectory = new File(Environment
                        .getExternalStorageDirectory(), getResources().getString(
                        R.string.directory));
                File file = new File(sdImageMainDirectory, name);
                if (file != null) {
                    file.delete();
                }
                return file.exists();
            }

            public void showAllBooks(  )
               {      
                   final elhgsdatabase db = new elhgsdatabase(this);

                   Handler handler = new Handler();
                   handler.postDelayed(new Runnable() {
                   public void run() {
                       // Get new entry

                   db.open();
             long currTime = System.currentTimeMillis();

                   String p_query = "select * from ads where timeFrom<=?";

        Cursor c = db.rawQuery(p_query, new String[] {             Long.toString(currTime)});
                if (c.moveToFirst())
               {
                   do {                         
                    DisplayTitle(c);

                  } while (c.moveToNext());
               } 
               db.close();  


                   }
                   }, 5000);  // 5000 miliseconds
               }

    public long getDate(String s){   
                String[] formats = new String[] {
                    "yyyy-MM-dd HH:mm:ss"
                     };

                SimpleDateFormat sdf=null;
                String st;

                for (String format : formats) {
              sdf = new SimpleDateFormat(format, Locale.US);
             sdf.setTimeZone(TimeZone.getTimeZone("EST"));//UTC or EST
                       st = new String(sdf.format(new Date(0)));
                       System.err.format(format, st);
                }

                Calendar c = Calendar.getInstance();
                   Date dt;
                try {
                    dt = sdf.parse(s);
                    c.setTime(dt);
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }   

                   return c.getTimeInMillis() ;      
             }  


        public void DisplayTitle(final Cursor c)
            {
                 Toast.makeText(this,
                        "Title: " + c.getString(0) + "\n" +
                        "isbn: " + c.getString(1) + "\n" +
                        "Publisher: " + c.getString(2) + "\n" +
                        "Year:  " + c.getString(3) + "\n" +
                        "Image On Line:  " + c.getString(4) + "\n" +
                        "Image On SD " + c.getString(5) + "\n" ,
                        Toast.LENGTH_LONG).show(); 

                    String imageInSD = c.getString(5); 
                    Bitmap bitmap = BitmapFactory.decodeFile(imageInSD);
                    myImageView=(ImageView)findViewById(R.id.imageview1);
                        myImageView.setImageBitmap(bitmap);

                    }



----------

2 个答案:

答案 0 :(得分:1)

我很确定你将第二个图像名称设置为reviewImageLink(不确定这是一个类变量还是什么)变量。相反,尝试将两者 URL和String传递给AsyncTask。而不是传递URL ...传入一个Object ...其中第一个是URL,第二个是名称,并在onPostExecute中使用它。

答案 1 :(得分:0)

您没有显示ImageLink的设置方式。但是由于文件名是由它构造的,我猜你的问题几乎与你在这里展示的代码无关。