Android:在API 8上下载崩溃应用程序的图像

时间:2014-06-03 22:00:59

标签: android android-asynctask imagedownload

我在API 8中遇到了AsyncTask的问题...

这是我的代码......

try{
    new loadPhotos().execute(""+USER._id,"date","DESC");
}catch(Exception e){
    e.printStackTrace();
}

在你问之前......是的,我很绝望,所以我用try {} catch

包围了一切
public class loadPhotos extends AsyncTask<String,Object,Void>{
            ProgressBar pb;

            ImageView img;
            TableRow.LayoutParams paramsImage;

            List<String> urlsOfImages;
            TableLayout tl;
            TableRow tr;
            LayoutParams lp;

            int numberOfPhotos=0;

            @Override
            protected void onPreExecute(){
                urlsOfImages = new ArrayList<String>(); //There is stored urls of all images ( www.example.com/image1.jpg ... etc)

                try {
                    allUserPhotoBitmaps.clear(); //allUserPhotoBitmaps is List<Bitmap>

                    pb = (ProgressBar) findViewById(R.id.profile_photos_progress_bar);
                    pb.setVisibility(View.VISIBLE);

                    tl = (TableLayout) findViewById(R.id.profile_photos_table_layout);
                    tl.removeAllViews();

                    tr = new TableRow(Profile.this);
                    lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

                    tr.setLayoutParams(lp);
                }catch(Exception e){
                    Toast.makeText(Profile.this, "Error in onPreExecute", Toast.LENGTH_LONG).show();
                }

            }

            @Override
            protected Void doInBackground(String... arg) {

                try{
                    // This function basicaly returns List<HashMap<String,String>> with informations about photos ( web_path, latitude, longitude, city, etc...)
                    allUserPhotoInformations = myDb.getUrlsOfUserImages(arg[0],arg[1],arg[2]); 
                }catch(Exception e){
                    Toast.makeText(Profile.this, "Error downloading images", Toast.LENGTH_SHORT).show();
                }

                if ( allUserPhotoInformations != null ) {
                    for (int i=0 ; i < allUserPhotoInformations.size() ; i++){
                        try{
                            Bitmap bm = getBitmapFromURL(allUserPhotoInformations.get(i).get("file_path"));
                            allUserPhotoBitmaps.add(bm);
                            publishProgress(bm,i);
                        }
                        catch(Exception e){
                            return null;
                        }
                    }
                }

                return null;
            }

            @Override
            protected void onProgressUpdate(Object... arg){

                img = new ImageView(getBaseContext());
                paramsImage = new TableRow.LayoutParams( (((int)screenWidth)/2)-16 , (((((int)screenWidth)/2)-15)/16)*11 );
                paramsImage.setMargins(10,10,0,0);

                img.setLayoutParams(paramsImage);
                img.setBackgroundColor(Color.parseColor("#FF000000"));

                try{
                    img.setImageBitmap((Bitmap) arg[0]);
                }catch(Exception e){
                    Toast.makeText(Profile.this,"Cannot put Bitmap into ImageView",Toast.LENGTH_LONG).show();
                }

                img.setVisibility(View.VISIBLE);

                img.setOnClickListener(new ImageListener((Integer)arg[1])); //here I passing index to onClickListener

                tr.addView(img);

                if ( numberOfPhotos==1 ){

                    try{
                        tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
                    }catch(Exception e){
                        e.printStackTrace();
                        Toast.makeText(Profile.this,"Cannot inflate tableLayout",Toast.LENGTH_LONG).show();
                    }

                    tr = new TableRow(Profile.this);
                    tr.setLayoutParams(lp);

                    numberOfPhotos--;
                }
                else {
                    numberOfPhotos++;
                }
            }
            @Override
            protected void onPostExecute(Void arg){
                pb.setVisibility(View.GONE);

                userPhotos.setText("uploaded: "+allUserPhotoBitmaps.size()+" photos");

                if ( numberOfPhotos==1 ){
                    try{
                        tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
                    }catch(Exception e){
                        e.printStackTrace();
                        Toast.makeText(Profile.this,"Cannot inflate tableLayout",Toast.LENGTH_LONG).show();
                    }

                    tr = new TableRow(Profile.this);
                    tr.setLayoutParams(lp);
                }
            }

在我的设备(API&gt; 15)中,一切都运行良好,但在API 10中它会崩溃应用程序...我想要的,我也可以提供OnClickListener或其他一些方法......

是的,这里...... 我如何下载图片

public Bitmap getBitmapFromURL(String src) {
                try {
                    java.net.URL url = new java.net.URL(src);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setDoInput(true);
                    connection.connect();
                    InputStream input = connection.getInputStream();
                    Bitmap myBitmap = BitmapFactory.decodeStream(input);

                    double width;
                    double height;

                    width = (screenWidth)/myBitmap.getRowBytes();

                    if ( myBitmap.getWidth() > myBitmap.getHeight() ){
                        Log.w("size","landscape");
                        height = ((myBitmap.getRowBytes()*width)/16)*11;
                        width = (height/11)*16;
                    }
                    else {
                        Log.w("size","protrait");
                        height = ((myBitmap.getRowBytes()*width)/11)*16;
                        width = (height/16)*11;
                    }

                    Bitmap bitmap = Bitmap.createScaledBitmap(myBitmap, (int)width, (int)height, true);

                    return bitmap;
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(Profile.this, "Error parsing image to bitmap", Toast.LENGTH_LONG).show();
                    return null;
                }
            }

任何帮助?

1 个答案:

答案 0 :(得分:1)

new loadPhotos().execute(""+USER._id,"date","DESC");中呼叫onCreate并使用Asynctask并尝试避免main thread中的加载。您的应用程序崩溃的主要原因之一可能是您在main thread.中调用了方法 例如:

String zoomouturl = "your url";

new ImageDownload().execute(zoomouturl);

尝试

public class ImageDownload extends AsyncTask<String, Void, String> {

            protected String doInBackground(String... params) {
                // TODO Auto-generated method stub
          bmOptions = new BitmapFactory.Options();
                bmOptions.inSampleSize = 1;
                loadBitmap(zoomouturl, bmOptions);
                return zoomouturl;
            }

            protected void onPostExecute(String imageUrl) {

                if (!imageUrl.equals("")) {

                     Constants._image.setImageBitmap(bm);


                } else {
                    Toast.makeText(this,
                            "not found proper bitmap.. ", Toast.LENGTH_LONG)
                            .show();
                }
            }

        }

        public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) {
            InputStream in = null;
            try {
                in = OpenHttpConnection(URL);
                bm = BitmapFactory.decodeStream(in, null, options);
                in.close();
            } catch (IOException e1) {
            }
            return bm;
        }

        private static InputStream OpenHttpConnection(String strURL)
                throws IOException {
            InputStream inputStream = null;
            URL url = new URL(strURL);
            URLConnection conn = url.openConnection();

            try {
                HttpURLConnection httpConn = (HttpURLConnection) conn;
                httpConn.setRequestMethod("GET");
                httpConn.connect();

                if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    inputStream = httpConn.getInputStream();
                }
            } catch (Exception ex) {
            }
            return inputStream;
        }