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

发布于 2024-11-03 05:26:45 字数 13052 浏览 1 评论 0原文

我的问题是,我有一个代码应该接收一个变量,该变量包含一个具有图像的网站,因此每次我发送新链接时该变量都会更改,该代码应该在线并下载图像并将其保存到 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);

                    }



----------

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

                    }



----------

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

☆獨立☆ 2024-11-10 05:26:45

我很确定您将第二个图像名称设置为 reviewImageLink (不确定这是否是类变量或什么)变量。相反,请尝试将 URL 和字符串都传递给 AsyncTask。不是传递 URL...而是传递一个对象...,其中第一个是 URL,第二个是名称,并在 onPostExecute 中使用它。

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.

上课铃就是安魂曲 2024-11-10 05:26:45

您没有显示 ImageLink 是如何设置的。但由于文件名是根据它构建的,我猜您的问题几乎与您在此处显示的代码无关。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文