0
    download.java
    -----------
    import java.io.BufferedInputStream;
    import java.io.ByteArrayInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLConnection;
    import java.util.HashMap;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipInputStream;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.util.EntityUtils;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import android.app.Activity;
    import android.app.Dialog;
    import android.app.ListActivity;
    import android.app.ProgressDialog;
    import android.content.Context;
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.os.Environment;
    import android.os.Handler;
    import android.os.Message;
    import android.sax.StartElementListener;
    import android.util.Base64;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.LayoutInflater.Filter;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.Button;
    import android.widget.Filterable;
    import android.widget.GridView;
    import android.widget.ImageView;
    import android.widget.TableLayout;
    import android.widget.TextView;

    public class MainActivity extends ListActivity  
    {
        static Handler handler,handler2;
        Thread thread;
        static Thread thread2;
        TableLayout tablLayout;
        private static EfficientAdapter adap;
        ProgressDialog pd;
        public DBHelper db;
        GridView gridview;
        int total_row=0;
        public  final int DIALOG_DOWNLOAD_PROGRESS = 0;
        private ProgressDialog mProgressDialog;
        String FILE_NAME="";
        static int Current_position=0;

        private static String url = "d:/reader/shelf.json";

        JSONArray contacts = null;

        @Override
        protected void onCreate(Bundle savedInstanceState) 
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.listview);


            db = new DBHelper(this);

            gridview = (GridView) findViewById(R.id.MyGrid);

            total_row=db.CountRow();
            db.GetData();

            thread2 = new Thread()
            {
                @Override
                public void run() 
                {
                    handler2.sendEmptyMessage(0);
                }
            };

            handler2 = new Handler() 
            {
                @Override
                public void handleMessage(Message msg)
                {

                    FILE_NAME=Static_class.Select_URL.substring(Static_class.Select_URL.lastIndexOf('/') + 1);
                    Log.w("File Name....",""+FILE_NAME);
                    Log.w("url....",""+Static_class.Select_URL);

                    startDownload();
                }
            };

            handler = new Handler()
            {
                @Override
                public void handleMessage(Message msg) {
                    switch (msg.what) {
                    case 1:
                        pd = ProgressDialog.show(MainActivity.this, null,
                                "Please Wait...", true, false);
                        pd.setCancelable(false);
                        break;
                    case 2:
                        pd.dismiss();
                        break;
                    case 3:
                        Display_magazine();
                        break;
                    }

                }
            };
            thread = new Thread() {
                @Override
                public void run() {
                    try {
                        handler.sendEmptyMessage(1);

                        JSONParser jParser = new JSONParser();

                        JSONObject json = jParser.getJSONFromUrl(url);  
                        contacts = json.getJSONArray("Magazine");

                        Static_class.Magazine_total =contacts.length();

                        Static_class.name = new String[Static_class.Magazine_total];
                        Static_class.title = new String[Static_class.Magazine_total];
                        Static_class.info = new String[Static_class.Magazine_total];
                        Static_class.date = new String[Static_class.Magazine_total];
                        Static_class.cover_image = new Bitmap[Static_class.Magazine_total];
                        Static_class.url = new String[Static_class.Magazine_total];
                        Static_class.id = new String[Static_class.Magazine_total];
                        Static_class.Button_text = new String[Static_class.Magazine_total];


                        // looping through All Contacts
                        for(int i = 0; i < contacts.length(); i++)
                        {
                            JSONObject c = contacts.getJSONObject(i);

                            Static_class.name[i]=c.getString("name");
                            Static_class.title[i]=c.getString("title");
                            Static_class.info[i]=c.getString("info");
                            Static_class.date[i]=c.getString("date");
                            Static_class.cover_image[i]=getBitmapFromURL(c.getString("cover"));
                            Static_class.url[i]=c.getString("url");
                            Static_class.id[i]=c.getString("product_id");                           
                            Static_class.Button_text[i]="Read";



                            int temp=0;
                            String temp_url="";
                            for (int j=0;j<total_row;j++)
                            {
                                if(Static_class.id[i].equals(Static_class.Stored_id[j]))
                                {
                                    temp=1; 
                                    temp_url=""+Static_class.Stored_url[j];
                                }                           
                            }
                            if(temp == 1)
                            {   
                                Static_class.Button_text[i]="Read";
                                Static_class.url[i]=temp_url;
                            }
                            else
                            {
                                Static_class.Button_text[i]="Download";
                            }
                        }

                        handler.sendEmptyMessage(2);
                        handler.sendEmptyMessage(3);


                    }
                    catch (Exception e)
                    {
                        handler.sendEmptyMessage(2);
                        e.printStackTrace();
                    }
                }

            };
            thread.start();


        }
        public Bitmap getBitmapFromURL(String src) 
        {
            try {
                URL url = new URL(src);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.connect();
                InputStream input = connection.getInputStream();
                Bitmap myBitmap = BitmapFactory.decodeStream(input);
                return myBitmap;
            }
            catch (IOException e)
            {
                e.printStackTrace();
                return null;
            }
        }

        public void Display_magazine()
        {
            adap = new EfficientAdapter(this);
            setListAdapter(adap);



        }

        public void Show_magazine()
        {
        //  Intent go = new Intent(this,Display.class);
        //  startActivity(go);
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu)
        {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.activity_main, menu);
            return true;
        }

        public static class EfficientAdapter extends BaseAdapter implements
        Filterable {
    private LayoutInflater mInflater;
    private Context context;

    public EfficientAdapter(Context context) {

        mInflater = LayoutInflater.from(context);
        this.context = context;
    }

            @Override
            public View getView(final int position, View convertView,
                    ViewGroup parent) {

                ViewHolder holder;

                if (convertView == null) {
                    convertView = mInflater.inflate(
                            R.layout.adaptercontrol, null);

                    holder = new ViewHolder();
                    holder.txt_info = (TextView) convertView
                            .findViewById(R.id.textView_info);
                    holder.txt_title = (TextView) convertView
                            .findViewById(R.id.textView_title);
                    holder.txt_remove = (TextView) convertView
                    .findViewById(R.id.textView_remove);
                    holder.image = (ImageView) convertView
                    .findViewById(R.id.image);
                    holder.read = (Button) convertView
                    .findViewById(R.id.button_download);


                    holder.read.setOnClickListener(new OnClickListener() 
                    {

                        @Override
                        public void onClick(View v) 
                        {
                            Current_position=position;
                            if (Static_class.Button_text[position].equals("Download"))
                            {

                                Static_class.Select_URL=Static_class.url[position];                     

                                if (Static_class.First_Time_Thread == 0)
                                {
                                    thread2.start();
                                    Static_class.First_Time_Thread=1;
                                }
                                else
                                {
                                    thread2.run();
                                }
                            }
                            else
                            {

                            }
                        }
                    });

                    holder.txt_remove.setOnClickListener(new OnClickListener() 
                    {
                        private int pos = position;
                        @Override
                        public void onClick(View v) 
                        {

                        }
                    });

                    // holder.next_image.setOnClickListener(new OnClickListener() {
                    // private int pos = position;
                    //
                    // public void onClick(View v) {
                    // Toast.makeText(context, "Click-" + String.valueOf(pos),
                    // Toast.LENGTH_SHORT).show();
                    // }
                    // });

                    convertView.setTag(holder);
                } else {

                    holder = (ViewHolder) convertView.getTag();
                }

                holder.image.setImageBitmap(Static_class.cover_image[position]);
                holder.txt_info.setText("" + Static_class.info[position]);
                holder.txt_title.setText("" + Static_class.title[position]);
                holder.read.setText(""+ Static_class.Button_text[position]);

                return convertView;
            }

    static class ViewHolder 
    {
        TextView txt_title,txt_info,txt_remove;
        ImageView image;
        Button read;
    }



    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public int getCount() {
        return Static_class.Magazine_total;
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public android.widget.Filter getFilter() {
        // TODO Auto-generated method stub
        return null;
    }
    }




         private void delete_file()
            {        
                File file = new File("/sdcard/"+FILE_NAME);
            //  String temp_name=Static_class.url[Current_position].replace(".hpub","");
    //          db.Insert(Static_class.id[Current_position],"file://"+Environment.getExternalStorageDirectory()+"/LivingNow/"+temp_name+"/index.html");
                db.GetData();
                db.Insert(Static_class.name[Current_position], Static_class.title[Current_position], Static_class.info[Current_position], Static_class.date[Current_position], Static_class.cover_image[Current_position],Static_class.url[Current_position],Static_class.id[Current_position]);
                total_row=db.CountRow();
                Static_class.Button_text[Current_position]="Read";          
                boolean deleted = file.delete();

                Intent call = new Intent(this,MainActivity.class);
                startActivity(call);
                System.exit(0);
            }

         private void Decompress() 
         {
                String zipFile = Environment.getExternalStorageDirectory() + "/"+FILE_NAME; 
                String unzipLocation = Environment.getExternalStorageDirectory() + "/reader/"+FILE_NAME; 
                Decompress d = new Decompress(zipFile, unzipLocation); 
                d.unzip();  
         }

         public void startDownload() 
         {
                new DownloadFileAsync().execute(Static_class.Select_URL);
         }

            @Override
            protected Dialog onCreateDialog(int id) 
            {
                switch (id) {
                case DIALOG_DOWNLOAD_PROGRESS:
                    mProgressDialog = new ProgressDialog(this);
                    mProgressDialog.setMessage("Downloading Magazine..");
                    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                    mProgressDialog.setCancelable(false);
                    mProgressDialog.show();
                    return mProgressDialog;
                default:
                    return null;
                }
            }

        class DownloadFileAsync extends AsyncTask<String, String, String> {

            @Override
            protected void onPreExecute() 
            {

                super.onPreExecute();
                showDialog(DIALOG_DOWNLOAD_PROGRESS);
            }

            @Override
            protected String doInBackground(String... aurl) {
                int count;

            try {

            URL url = new URL(aurl[0]);
            URLConnection conexion = url.openConnection();
            conexion.connect();

            int lenghtOfFile = conexion.getContentLength();
            //Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream("/sdcard/"+FILE_NAME);

            byte data[] = new byte[4096];

            long total = 0;

                while ((count = input.read(data)) != -1)
                {
                    total += count;
                    publishProgress(""+(int)((total*100)/lenghtOfFile));
                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                input.close();
            } catch (Exception e) {}
            return null;

            }
            protected void onProgressUpdate(String... progress)
            {
            //   Log.d("ANDRO_ASYNC",progress[0]);
                 mProgressDialog.setProgress(Integer.parseInt(progress[0]));
            }

            @Override
            protected void onPostExecute(String unused) 
            {
                Decompress();
                dismissDialog(DIALOG_DOWNLOAD_PROGRESS);        
            }       
        }

        public class Decompress { 
              private String _zipFile; 
              private String _location; 

              public Decompress(String zipFile, String location) { 
                _zipFile = zipFile; 
                _location = location; 

                _dirChecker(""); 
              } 

              public void unzip() { 
                try  { 
                  FileInputStream fin = new FileInputStream(_zipFile); 
                  ZipInputStream zin = new ZipInputStream(fin); 
                  ZipEntry ze = null; 


                  while ((ze = zin.getNextEntry()) != null) 
                  { 
                    Log.v("Decompress", "Unzipping " + ze.getName());

                    if(ze.isDirectory()) 
                    { 
                      _dirChecker(ze.getName()); 
                    }
                    else 
                    { 
                      FileOutputStream fout = new FileOutputStream(_location + ze.getName()); 

    //                for (int c = zin.read(); c != -1; c = zin.read()) 
    //                { 
    //                  fout.write(c); 
    //                } 

                      byte[] buffer = new byte[4096]; 
                      for (int c = zin.read(buffer); c != -1; c = zin.read(buffer)) 
                      {
                          fout.write(buffer, 0, c); 
                      }
                      zin.closeEntry(); 
                      fout.close(); 
                    } 

                  } 
                  zin.close(); 
                  delete_file();
                } catch(Exception e) { 
                  Log.e("Decompress", "unzip", e); 
                } 

              } 

              private void _dirChecker(String dir)
              { 
                File f = new File(_location + dir); 

                if(!f.isDirectory()) { 
                  f.mkdirs(); 
                } 
              } 
            } 
    }

log cat
-------
 02-21 16:20:29.155: E/Decompress(846): java.io.FileNotFoundException: /mnt/sdcard/reader.zip (Permission denied)
    02-21 16:20:29.155: E/Decompress(846):  at org.apache.harmony.luni.platform.OSFileSystem.open(Native Method)
    02-21 16:20:29.155: E/Decompress(846):  at dalvik.system.BlockGuard$WrappedFileSystem.open(BlockGuard.java:232)
    02-21 16:20:29.155: E/Decompress(846):  at java.io.FileInputStream.<init>(FileInputStream.java:80)
    02-21 16:20:29.155: E/Decompress(846):  at java.io.FileInputStream.<init>(FileInputStream.java:132)
    02-21 16:20:29.155: E/Decompress(846):  at com.reader.MainActivity$Decompress.unzip(MainActivity.java:588)
    02-21 16:20:29.155: E/Decompress(846):  at com.reader.MainActivity.Decompress(MainActivity.java:493)
    02-21 16:20:29.155: E/Decompress(846):  at com.reader.MainActivity.access$1(MainActivity.java:488)
    02-21 16:20:29.155: E/Decompress(846):  at com.reader.MainActivity$DownloadFileAsync.onPostExecute(MainActivity.java:570)
    02-21 16:20:29.155: E/Decompress(846):  at com.reader.MainActivity$DownloadFileAsync.onPostExecute(MainActivity.java:1)
    02-21 16:20:29.155: E/Decompress(846):  at android.os.AsyncTask.finish(AsyncTask.java:417)
    02-21 16:20:29.155: E/Decompress(846):  at android.os.AsyncTask.access$300(AsyncTask.java:127)
    02-21 16:20:29.155: E/Decompress(846):  at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
    02-21 16:20:29.155: E/Decompress(846):  at android.os.Handler.dispatchMessage(Handler.java:99)
    02-21 16:20:29.155: E/Decompress(846):  at android.os.Looper.loop(Looper.java:123)
    02-21 16:20:29.155: E/Decompress(846):  at android.app.ActivityThread.main(ActivityThread.java:3683)
    02-21 16:20:29.155: E/Decompress(846):  at java.lang.reflect.Method.invokeNative(Native Method)
    02-21 16:20:29.155: E/Decompress(846):  at java.lang.reflect.Method.invoke(Method.java:507)
    02-21 16:20:29.155: E/Decompress(846):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
    02-21 16:20:29.155: E/Decompress(846):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
    02-21 16:20:29.155: E/Decompress(846):  at dalvik.system.NativeStart.main(Native Method)

ダウンロードボタンを押したときにパスからzipをダウンロードしたいのですが、プロセスは何も進行せず、プログレスバーをフリップしてホームに戻るだけです。あらかじめ

4

1 に答える 1

1

クイックアンサー:Logcatはあなたに解決策を提供します

02-21 16:20:29.155:E / Decompress(846):java.io.FileNotFoundException:/mnt/sdcard/reader.zip(アクセスが拒否されました)

AndroidManifestファイルに必要なすべての権限があることを確認してください。

たぶん、以下のリンクがあなたを助けるでしょう(例えば):

java.io.FileNotFoundException(許可が拒否されました)AndroidSDカードに書き込もうとしたとき

java.io.FileNotFoundException:AndroidManifestに権限を設定したにもかかわらず、アクセスが拒否されました

于 2013-02-21T11:57:38.710 に答える