简体   繁体   中英

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

my question is that i have a code that is suppose to receive a variable that contains a website that has an image so this variable changes every time i send a new link this code should go online and download the image and save it to the sd-card then i read it and display it

so my problem with the code is if im sending 2 links to it, it downloads 1 of the images and it always stores it with the second image name (example: im sending image1 and image2 the code downloads image1 two times and stores it as "image2") when i mount the sd-card and check the image directory there is only 1 image there named image2, i thought that doInBackground was causing the problem but im also using onPostExecute() so please if someone can help me i would be thankful for his help Note this is how i call it: Note: i have no errors in the code // no red marks This is all the code:

        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);

                    }



----------

I'm pretty sure you're setting the second image name to the reviewImageLink (not sure if this is a class variable or what) variable. Instead, try passing both the URL and the String to the AsyncTask. Instead of passing a URL... pass in an Object... where the first one is the URL and the second is the name, and use that in the onPostExecute.

You don't show how ImageLink is set up. But as the filename is constructed from it, I guess your problem has almost nothing to do with the code you showed here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM