簡體   English   中英

android下載圖像,然后使用sqlite從SD卡讀取圖像

[英]android download image and then read it from sd-card using sqlite

我的問題是,我有一個代碼,該代碼應該接收一個包含具有圖片的網站的變量,因此每次我發送新鏈接時,此變量都會更改,該代碼應上線並下載圖片並將其保存到sd-卡,然后我讀並顯示它

因此,我的代碼問題是,如果我發送2個鏈接,它會下載其中的1張圖片,並且始終將其與第二個圖片名稱一起存儲(例如:我發送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);

                    }



----------

我很確定您將第二個圖像名稱設置為reviewImageLink(不確定這是類變量還是什么)變量。 而是嘗試將URL和String 傳遞給AsyncTask。 而不是傳遞URL ...傳遞對象...,其中第一個是URL,第二個是名稱,然后在onPostExecute中使用它。

您沒有顯示如何設置ImageLink 但是,由於是從文件名構造文件名的,所以我想您的問題幾乎與此處顯示的代碼無關。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM