下载内容和图像并将其保存到android中的SD卡中

时间:2014-07-15 07:53:36

标签: android download

嗨在我的应用程序中,我通过传递URL并显示包含内容的图像来解析数据。

之后我添加了一个按钮如果我点击按钮我想下载内容和图像并将其保存到sdcard.Now,如果我按下载按钮它显示不幸的错误。

现在我想如果我按下载按钮我想下载包含图像的完整内容并保存到SD卡。

任何人都可以帮助我。

notify_image类

public class notify_image extends Activity {


    Activity av=notify_image.this;
     ImageView imageView;
     View content;
     Button download;
     Activity activity;
     Button btnShowProgress;
     private ProgressDialog pDialog;
     ImageView my_image;

    public static final int progress_bar_type = 0; 
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.notify_image);


         imageView = (ImageView) findViewById(R.id.iv_imageview);
         btnShowProgress = (Button) findViewById(R.id.button1);
         my_image = (ImageView) findViewById(R.id.my_image);
        // download = (Button) findViewById(R.id.button1);
         Intent in = getIntent();

         String title = in.getStringExtra("TAG_TITLE");
         String url = in.getStringExtra("TAG_URL");
         String name = in.getStringExtra("TAG_NAME");
         String place = in.getStringExtra("TAG_PLACE");
         String date = in.getStringExtra("TAG_DATE");
         final String URL =url;
         TextView stitle = (TextView) findViewById(R.id.tv_title);
         TextView sname = (TextView) findViewById(R.id.tv_name);
         TextView splace = (TextView) findViewById(R.id.tv_place);
         TextView sdate = (TextView) findViewById(R.id.tv_date);  

         // displaying selected product name
         stitle.setText(title);
         sname.setText(name);
         splace.setText(place);
         sdate.setText(date);






         // Create an object for subclass of AsyncTask
         GetXMLTask task = new GetXMLTask();
         // Execute the task
         task.execute(new String[] { URL });
         btnShowProgress.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // starting new Async Task
                new DownloadFileFromURL().execute(URL);
            }
        });
         //download();

     }
     class DownloadFileFromURL extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread
         * Show Progress Bar Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(progress_bar_type);
        }
        protected void onProgressUpdate(String... progress) {
            // setting progress percentage
            pDialog.setProgress(Integer.parseInt(progress[0]));
       }
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after the file was downloaded
            dismissDialog(progress_bar_type);

            // Displaying downloaded image into image view
            // Reading image path from sdcard
            String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
            // setting downloaded into image view
            my_image.setImageDrawable(Drawable.createFromPath(imagePath));
        }
        /**
         * Downloading file in background thread
         * */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection conection = url.openConnection();
                conection.connect();
                // getting file length
                int lenghtOfFile = conection.getContentLength();

                // input stream to read file - with 8k buffer
                InputStream input = new BufferedInputStream(url.openStream(), 8192);

                // Output stream to write file
                OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress(""+(int)((total*100)/lenghtOfFile));

                    // writing data to file
                    output.write(data, 0, count);
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

            return null;
        }   



      }


     //image url convert to bitmap

     private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
         @Override
         protected Bitmap doInBackground(String... urls) {
             Bitmap map = null;
             for (String url : urls) {
                 map = downloadImage(url);
             }
             return map;
         }

         // Sets the Bitmap returned by doInBackground
         @Override
         protected void onPostExecute(Bitmap result) {
             imageView.setImageBitmap(result);
         }

         // Creates Bitmap from InputStream and returns it
         private Bitmap downloadImage(String url) {
             Bitmap bitmap = null;
             InputStream stream = null;
             BitmapFactory.Options bmOptions = new BitmapFactory.Options();
             bmOptions.inSampleSize = 1;

             try {
                 stream = getHttpConnection(url);
                 bitmap = BitmapFactory.
                         decodeStream(stream, null, bmOptions);
                 stream.close();
             } catch (IOException e1) {
                 e1.printStackTrace();
             }
             return bitmap;
         }

         // Makes HttpURLConnection and returns InputStream
         private InputStream getHttpConnection(String urlString)
                 throws IOException {
             InputStream stream = null;
             URL url = new URL(urlString);
             URLConnection connection = url.openConnection();

             try {
                 HttpURLConnection httpConnection = (HttpURLConnection) connection;
                 httpConnection.setRequestMethod("GET");
                 httpConnection.connect();

                 if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                     stream = httpConnection.getInputStream();
                 }
             } catch (Exception ex) {
                 ex.printStackTrace();
             }
             return stream;
         }
     }
 }

Logcat错误

07-15 14:27:26.457: E/AndroidRuntime(14670): FATAL EXCEPTION: main
07-15 14:27:26.457: E/AndroidRuntime(14670): java.lang.NullPointerException
07-15 14:27:26.457: E/AndroidRuntime(14670):    at com.politicalmileage.vel.notify_image$DownloadFileFromURL.onProgressUpdate(notify_image.java:122)
07-15 14:27:26.457: E/AndroidRuntime(14670):    at com.politicalmileage.vel.notify_image$DownloadFileFromURL.onProgressUpdate(notify_image.java:1)
07-15 14:27:26.457: E/AndroidRuntime(14670):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:647)
07-15 14:27:26.457: E/AndroidRuntime(14670):    at android.os.Handler.dispatchMessage(Handler.java:107)
07-15 14:27:26.457: E/AndroidRuntime(14670):    at android.os.Looper.loop(Looper.java:194)
07-15 14:27:26.457: E/AndroidRuntime(14670):    at android.app.ActivityThread.main(ActivityThread.java:5371)
07-15 14:27:26.457: E/AndroidRuntime(14670):    at java.lang.reflect.Method.invokeNative(Native Method)
07-15 14:27:26.457: E/AndroidRuntime(14670):    at java.lang.reflect.Method.invoke(Method.java:525)
07-15 14:27:26.457: E/AndroidRuntime(14670):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
07-15 14:27:26.457: E/AndroidRuntime(14670):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
07-15 14:27:26.457: E/AndroidRuntime(14670):    at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

您致电pDialog.setProgress(Integer.parseInt(progress[0]));pDialog未设置且等于null。您必须在LOG CAT中为错误设置变量。

pDialog = new ProgressDialog(this);