java - Download Zip file in Android returns Corrupt file -


i'm trying make application in java downloads zip file, unzips download folder on android device. problem when program downloads it, zip file downloads corrupted , has nothing inside and, of course, unzipped folder empty. have 3 main classes "download file", "unzip", , of course "mainactivity". here are:

mainactivity:

package com.nautgames.xecta.app;  import android.os.bundle; import android.support.v7.app.actionbaractivity; import android.view.menu; import android.view.menuitem; //chat bot library import org.alicebot.ab.chat; import org.alicebot.ab.bot; import android.widget.edittext;  import java.io.file; import android.view.view; import android.widget.button; import android.os.environment; import android.widget.textview; import android.widget.toast;  import android.app.progressdialog;  public class mainactivity extends actionbaractivity {  button clickdownload; textview input; string dpath = environment.getexternalstoragedirectory().getpath() ;  private progressdialog mprogressdialog;  @override public void oncreate(bundle savedinstancestate) {     super.oncreate(savedinstancestate);     setcontentview(r.layout.activity_main);     clickdownload = (button)findviewbyid(r.id.btn_download); }  //edittext medit = (edittext)findviewbyid(r.id.edittext1);  public void buttononclick(view v) {     input = (textview) findviewbyid(r.id.edittext1);      string dbpath = environment.getexternalstoragedirectory().getabsolutepath() + "/download/ab";      button button=(button) v;      //creating bot     string botname="xecta";     string path= dbpath;     bot xecta = new bot(botname, path);      chat chatsession = new chat(xecta);      string request = input.gettext().tostring();     string response = chatsession.multisentencerespond(request);     ((button) v).settext(response); }  /**  * button starts download unzip.  */ public void onclickdownload(view v) {     button clickdownload = (button) v;      string dpath = environment.getexternalstoragedirectory().getabsolutepath() + "/download";      ((button) v).settext("downloading");     //to download zip     //url     string url = "http://download1642.mediafire.com/hn64kc18pafg/ojajp9o26scdbwd/files.zip";     //path save     string savepath = dpath + "/files";     //name save     string savename = "xecta.zip";     downloadfile download = new downloadfile();     download.downloadfile(url, savepath, savename);      //to unzip files     string zipfile = dpath + "/files/files";     string unziplocation = dpath + "/files";      unzip d = new unzip(zipfile, unziplocation);     d.unzip(); }  @override public boolean oncreateoptionsmenu(menu menu) {      // inflate menu; adds items action bar if present.     getmenuinflater().inflate(r.menu.main, menu);     return true; }  @override public boolean onoptionsitemselected(menuitem item) {     // handle action bar item clicks here. action bar     // automatically handle clicks on home/up button, long     // specify parent activity in androidmanifest.xml.     int id = item.getitemid();     if (id == r.id.action_settings) {         return true;     }     return super.onoptionsitemselected(item); } } 

downloadfile:

package com.nautgames.xecta.app;  import android.os.bundle; import android.support.v7.app.actionbaractivity; import android.widget.button;  import java.io.file; import java.io.fileoutputstream; import java.io.inputstream; import java.net.url; import java.net.urlconnection;  public class downloadfile extends actionbaractivity{  button download;  string file_download_connect = "connecting..."; string file_download_update = "downloading"; string file_download_complete = "complete!"; string file_download_error = "error downloading";  @override public void oncreate(bundle savedinstancestate) {     super.oncreate(savedinstancestate);     setcontentview(r.layout.activity_main);     download = (button)findviewbyid(r.id.btn_download); }  public void downloadfile(final string url, final string savepath, final string savename) {     new thread(new runnable() {         public void run() {             try {                 //download.settext(file_download_connect);                 url sourceurl = new url(url);                 urlconnection conn = sourceurl.openconnection();                 conn.connect();                 inputstream inputstream = conn.getinputstream();                  int filesize = conn.getcontentlength();                  file savefilepath = new file(savepath);                 if (!savefilepath.exists()) {                     savefilepath.mkdirs();                 }                 file savefile = new file(savepath+savename);                 if (savefile.exists()) {                     savefile.delete();                 }                 savefile.createnewfile();                  fileoutputstream outputstream = new fileoutputstream(                         savepath+savename, true);                  byte[] buffer = new byte[1024];                 int readcount = 0;                 int readnum = 0;                 int prevpercent = 0;                 while (readcount < filesize && readnum != -1) {                     readnum = inputstream.read(buffer, 0, readnum);                     if (readnum > -1) {                         outputstream.write(buffer);                          readcount = readcount + readnum;                          int percent = (int) (readcount * 100 / filesize);                         if (percent > prevpercent) {                             system.out.print(percent);                              prevpercent = percent;                         }                     }                 }                 outputstream.flush();                 outputstream.close();                 inputstream.close();                 //thread.sleep(50);                 //download.settext(file_download_complete);              } catch (exception e) {                 //download.settext(file_download_error);             }         }     }).start(); } } 

unzip:

package com.nautgames.xecta.app;  import android.util.log; import java.io.file; import java.io.fileinputstream; import java.io.fileoutputstream; import java.util.zip.zipentry; import java.util.zip.zipinputstream;  public class unzip { private string _zipfile; private string _location;  public unzip(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());                 (int c = zin.read(); c != -1; c = zin.read()) {                     fout.write(c);                 }                  zin.closeentry();                 fout.close();             }          }         zin.close();     } catch(exception e) {         log.e("decompress", "unzip", e);     }  }  private void _dirchecker(string dir) {     file f = new file(_location + dir);      if(!f.isdirectory()) {         f.mkdirs();     } } } 

btw running android studio (preview) 0.4.6 in advance.

update still not working, looking answer.

update got working now.

here working code lets see..

mainactivity.java

import android.app.activity; import android.os.bundle; import android.os.environment; import android.view.view; import android.view.view.onclicklistener; import android.widget.button;  public class mainactivity extends activity {      private button button;      @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         setcontentview(r.layout.activity_main);         button=(button)findviewbyid(r.id.button1);         button.setonclicklistener(new onclicklistener() {              @override             public void onclick(view arg0) {                 // todo auto-generated method stub                 utils.createdir(environment.getexternalstoragedirectory().tostring(),"downloads");                 utils.createdir(environment.getexternalstoragedirectory().tostring()+"/downloads", "files");                  string unziplocation = environment.getexternalstoragedirectory() +"/"+"downloads"+"/"+"files"+"/";                 string zipfile =environment.getexternalstoragedirectory() +"/"+"downloads"+"/"+"files"+"."+"zip";                 string url="https://eventfo.com.au/index.php/userapi/api/eventdetaildownload/eventid/162/accesskey/534ccbcc10ab2/deviceid/85d2a504b2be7af4/devicetype/android";                 try {                     new utils().downloadeventdata(mainactivity.this,zipfile, unziplocation, url);                 } catch (exception e) {                     // todo auto-generated catch block                     e.printstacktrace();                 }             }         });     } } 

unziputil.java

import android.util.log;  import java.io.file;  import java.io.fileinputstream;  import java.io.fileoutputstream;  import java.util.zip.zipentry;  import java.util.zip.zipinputstream;    public class unziputil {    private string _zipfile;    private string _location;     public unziputil(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());         //   (int c = zin.read(); c != -1; c = zin.read()) {           //   fout.write(c);                byte[] buffer = new byte[8192];              int len;              while ((len = zin.read(buffer)) != -1) {                  fout.write(buffer, 0, len);              }              fout.close();          //  }             zin.closeentry();           // fout.close();          }         }        zin.close();      } catch(exception e) {        log.e("decompress", "unzip", e);      }     }     private void _dirchecker(string dir) {      file f = new file(_location + dir);       if(!f.isdirectory()) {        f.mkdirs();      }    }  }  

utils.java

import java.io.bufferedinputstream; import java.io.bufferedoutputstream; import java.io.file; 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.security.cert.certificateexception; import java.security.cert.x509certificate; import java.util.enumeration; import java.util.zip.zipentry; import java.util.zip.zipfile;  import javax.net.ssl.hostnameverifier; import javax.net.ssl.httpsurlconnection; import javax.net.ssl.sslcontext; import javax.net.ssl.sslsession; import javax.net.ssl.trustmanager; import javax.net.ssl.x509trustmanager;  import android.annotation.suppresslint; import android.app.alertdialog; import android.app.progressdialog; import android.content.context; import android.content.dialoginterface; import android.graphics.color; import android.os.asynctask; import android.util.log; import android.view.gravity; import android.widget.textview; public class utils     {             public static void createdir(string path,string dirname)             {                   string newfolder = "/"+dirname;                   file mynewfolder = new file(path + newfolder);                   mynewfolder.mkdir();             }              public void downloadeventdata(context context,string zipfile,string unziplocation,string url) throws ioexception             {                 try {                         new downloadmapasync(context,zipfile,unziplocation).execute(url);                 } catch (exception e) {                     // todo auto-generated catch block                     e.printstacktrace();                 }             }                 private class downloadmapasync extends asynctask<string, string, string> {                     string result ="";                     context context;                     string zipfile;                     string unziplocation;                     private progressdialog progressdialog;                     string string;                     public downloadmapasync(context context,string zipfile,string unziplocation) {                         // todo auto-generated constructor stub                         this.context=context;                         this.zipfile=zipfile;                         this.unziplocation=unziplocation;                     }                     @override                     protected void onpreexecute() {                         super.onpreexecute();                         progressdialog = new progressdialog(context);                         progressdialog.setmessage("downloading zip file..");                         progressdialog.setprogressstyle(progressdialog.style_horizontal);                         progressdialog.setcancelable(false);                         progressdialog.show();                     }                      @override                     protected string doinbackground(string... aurl) {                         int count;                         httpurlconnection http = null;                     try {                         url url = new url(aurl[0]);                         if (url.getprotocol().tolowercase().equals("https")) {                             trustallhosts();                             httpsurlconnection https = (httpsurlconnection) url.openconnection();                             https.sethostnameverifier(do_not_verify);                             http = https;                         } else {                             http = (httpurlconnection) url.openconnection();                         }                     http.connect();                     if (http.getresponsecode()==200)                     {                         int lenghtoffile = http.getcontentlength();                         inputstream input = new bufferedinputstream(url.openstream());                          outputstream output = new fileoutputstream(zipfile);                          byte data[] = new byte[1024];                         long total = 0;                              while ((count = input.read(data)) != -1) {                                 total += count;                                 publishprogress(""+(int)((total*100)/lenghtoffile));                                 output.write(data, 0, count);                             }                             output.close();                             input.close();                             result = "true";                     }                      else if (http.getresponsecode()==401)                     {                         result = "false";                         string= "download limit exceed.";                        }                       else                      {                         result = "false";                         string=http.getresponsemessage();                     }                      } catch (exception e) {                         e.printstacktrace();                         result = "false";                         try {                             if (http.getresponsecode()==401)                             {                                 string= "download failed";                               } else {                                 string=e.tostring();                             }                          } catch (ioexception e1) {                             // todo auto-generated catch block                             e1.printstacktrace();                         }                     }                     return result;                      }                     protected void onprogressupdate(string... progress) {                          log.d("andro_async",progress[0]);                          progressdialog.setprogress(integer.parseint(progress[0]));                     }                      @override                     protected void onpostexecute(string unused) {                         progressdialog.dismiss();                         if(result.equalsignorecase("true"))                         {                         try {                             unzip(context,zipfile,unziplocation);                         } catch (ioexception e) {                             // todo auto-generated catch block                             e.printstacktrace();                         }                         }                         else                         {                             customalert(context, string);                         }                     }                 }                 @suppresslint("newapi")                 public void customalert(context context,string msgstring)                 {                     alertdialog.builder alertdialog2 = new alertdialog.builder(context,alertdialog.theme_device_default_light);                     textview title = new textview(context);                     title.settext("message");                     title.setpadding(10, 10, 10, 10);                     title.setgravity(gravity.center);                     title.settextcolor(color.black);                     title.settextsize(20);                     alertdialog2.setcustomtitle(title);                     textview msg = new textview(context);                     msg.settext(msgstring);                     msg.setpadding(10, 10, 10, 10);                     msg.setgravity(gravity.center);                     msg.settextsize(18);                     msg.settextcolor(color.black);                     alertdialog2.setview(msg);                     alertdialog2.setpositivebutton("ok",                         new dialoginterface.onclicklistener() {                             public void onclick(dialoginterface dialog, int which) {                                 dialog.cancel();                             }                         });                     alertdialog2.show();                 }                   public void unzip(context context,string zipfile,string unziplocation) throws ioexception                    {                         new unziptask(context,zipfile).execute(unziplocation);                   }                  private class unziptask extends asynctask<string, void, boolean> {                     context context;                     string zipfile;                     progressdialog progressdialog;                   public unziptask(context context,string zipfile) {                     // todo auto-generated constructor stub                      this.context=context;                      this.zipfile=zipfile;                     }                   @override                     protected void onpreexecute() {                         super.onpreexecute();                         progressdialog = new progressdialog(context);                         progressdialog.setmessage("please wait...extracting zip file ... ");                         progressdialog.setprogressstyle(progressdialog.style_spinner);                         progressdialog.setcancelable(false);                         progressdialog.show();                      }                   protected boolean doinbackground(string... params)                    {                       string filepath = zipfile;                       string destinationpath = params[0];                        file archive = new file(filepath);                       try {                            zipfile zipfile = new zipfile(archive);                           (@suppresswarnings("rawtypes")                         enumeration e = zipfile.entries(); e.hasmoreelements();) {                               zipentry entry = (zipentry) e.nextelement();                               unzipentry(zipfile, entry, destinationpath);                           }                               unziputil d = new unziputil(zipfile,params[0]);                              d.unzip();                        } catch (exception e) {                           e.printstacktrace();                           return false;                       }                        return true;                   }                    @override                   protected void onpostexecute(boolean result)                   {                       progressdialog.dismiss();                       file file=new file(zipfile);                       file.delete();                       customalert(context,"unzipping completed");                   }                    private void unzipentry(zipfile zipfile, zipentry entry,string outputdir) throws ioexception                      {                        if (entry.isdirectory()) {                           createdir(new file(outputdir, entry.getname()));                           return;                       }                        file outputfile = new file(outputdir, entry.getname());                       if (!outputfile.getparentfile().exists()) {                           createdir(outputfile.getparentfile());                       }                        bufferedinputstream inputstream = new bufferedinputstream(zipfile.getinputstream(entry));                       bufferedoutputstream outputstream = new bufferedoutputstream(new fileoutputstream(outputfile));                        try {                        } {                         outputstream.flush();                         outputstream.close();                         inputstream.close();                         }                   }                    public void createdir(file dir)                   {                       if (dir.exists()) {                           return;                       }                       if (!dir.mkdirs()) {                           throw new runtimeexception("can not create dir " + dir);                       }                   }                    }                   final static hostnameverifier do_not_verify = new hostnameverifier()                  {                         public boolean verify(string hostname, sslsession session) {                             return true;                         }                 };                 private static void trustallhosts() {                     // create trust manager not validate certificate chains                     trustmanager[] trustallcerts = new trustmanager[] { new x509trustmanager() {                         public java.security.cert.x509certificate[] getacceptedissuers() {                             return new java.security.cert.x509certificate[] {};                         }                          public void checkclienttrusted(x509certificate[] chain,                                 string authtype) throws certificateexception {                         }                          public void checkservertrusted(x509certificate[] chain,                                 string authtype) throws certificateexception {                         }                     } };                      // install all-trusting trust manager                     try {                         sslcontext sc = sslcontext.getinstance("tls");                         sc.init(null, trustallcerts, new java.security.securerandom());                         httpsurlconnection                                 .setdefaultsslsocketfactory(sc.getsocketfactory());                     } catch (exception e) {                         e.printstacktrace();                     }                 }    } 

manifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="com.example.downloadzipunzip"     android:versioncode="1"     android:versionname="1.0" >      <uses-sdk         android:minsdkversion="8"         android:targetsdkversion="18" />      <uses-permission android:name="android.permission.internet" />     <uses-permission android:name="android.permission.write_external_storage" />      <application         android:allowbackup="true"         android:icon="@drawable/ic_launcher"         android:label="@string/app_name"         android:theme="@style/apptheme" >         <activity             android:name="com.example.downloadzipunzip.mainactivity"             android:label="@string/app_name" >             <intent-filter>                 <action android:name="android.intent.action.main" />                  <category android:name="android.intent.category.launcher" />             </intent-filter>         </activity>     </application>  </manifest> 

hope code you..


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -