简体   繁体   English

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

[英]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 我的问题是,我有一个代码,该代码应该接收一个包含具有图片的网站的变量,因此每次我发送新链接时,此变量都会更改,该代码应上线并下载图片并将其保存到sd-卡,然后我读并显示它

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: 因此,我的代码问题是,如果我发送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);

                    }



----------

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. 我很确定您将第二个图像名称设置为reviewImageLink(不确定这是类变量还是什么)变量。 Instead, try passing both the URL and the String to the AsyncTask. 而是尝试将URL和String 传递给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. 而不是传递URL ...传递对象...,其中第一个是URL,第二个是名称,然后在onPostExecute中使用它。

You don't show how ImageLink is set up. 您没有显示如何设置ImageLink But as the filename is constructed from it, I guess your problem has almost nothing to do with the code you showed here. 但是,由于是从文件名构造文件名的,所以我想您的问题几乎与此处显示的代码无关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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