Friday 26 August 2016

Copy Folder from Android Assets to Phone Storage with AsyncTask

Add below permission to AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

MainActivity.java


import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;


public class MainActivity extends AppCompatActivity {

    AsyncTaskRunner taskRunner;
    Activity ctx;

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

        taskRunner = new AsyncTaskRunner(this);
        taskRunner.execute();
    }
public void gotoUpdate(View view)
{
    taskRunner = new AsyncTaskRunner(this);
    taskRunner.execute();
}
}



Create new java file

AsyncTaskRunner.java



import android.app.ProgressDialog;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.AsyncTask;
import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/** * Created by pkm1 on 8/26/2016. */public  class AsyncTaskRunner extends AsyncTask<Void,String,Void> {

    ProgressDialog progressDialog;

    private Context ctx;
    public AsyncTaskRunner(Context myContext) {
        this.ctx = myContext;
    }

    @Override    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = ProgressDialog.show(ctx,"Image Transferring",  "Wait for  seconds");
    }

    @Override    protected Void doInBackground(Void... voids) {

        publishProgress("Sleeping..."); // Calls onProgressUpdate()
        try {
            copyDirorfileFromAssetManager("imagesrc", "cms");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        // execution of result of Long time consuming operation        progressDialog.dismiss();
    }

    public String copyDirorfileFromAssetManager(String arg_assetDir, String arg_destinationDir) throws IOException {

        System.out.print(arg_assetDir);   System.out.print(arg_destinationDir);

        File sd_path = Environment.getExternalStorageDirectory();
        String dest_dir_path = sd_path + addLeadingSlash(arg_destinationDir);
        File dest_dir = new File(dest_dir_path);

        createDir(dest_dir);

        AssetManager asset_manager = ctx.getAssets();
        String[] files = asset_manager.list(arg_assetDir);

        for (int i = 0; i < files.length; i++) {

            String abs_asset_file_path = addTrailingSlash(arg_assetDir) + files[i];
            String sub_files[] = asset_manager.list(abs_asset_file_path);

            if (sub_files.length == 0) {
                // It is a file                String dest_file_path = addTrailingSlash(dest_dir_path) + files[i];
                copyAssetFile(abs_asset_file_path, dest_file_path);
            } else {
                // It is a sub directory                copyDirorfileFromAssetManager(abs_asset_file_path, addTrailingSlash(arg_destinationDir) + files[i]);
            }
        }

        return dest_dir_path;
    }


    public void copyAssetFile(String assetFilePath, String destinationFilePath) throws IOException {
        InputStream in = ctx.getAssets().open(assetFilePath);
        OutputStream out = new FileOutputStream(destinationFilePath);

        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0)
            out.write(buf, 0, len);
        in.close();
        out.close();
    }

    public String addTrailingSlash(String path) {
        if (path.charAt(path.length() - 1) != '/') {
            path += "/";
        }
        return path;
    }

    public String addLeadingSlash(String path) {
        if (path.charAt(0) != '/') {
            path = "/" + path;
        }
        return path;
    }

    public void createDir(File dir) throws IOException {
        if (dir.exists()) {
            if (!dir.isDirectory()) {
                throw new IOException("Can't create directory, a file is in the way");
            }
        } else {
            dir.mkdirs();
            if (!dir.isDirectory()) {
                throw new IOException("Unable to create directory");
            }
        }
    }


}


Copy Folder from Assets to Phone Storage



Add below permission to AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>







import android.content.res.AssetManager;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class MainActivity extends AppCompatActivity {

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


        try {
            copyDirorfileFromAssetManager("imagesrc","cms");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public String copyDirorfileFromAssetManager(String arg_assetDir, String arg_destinationDir) throws IOException
    {
        File sd_path = Environment.getExternalStorageDirectory();
        String dest_dir_path = sd_path + addLeadingSlash(arg_destinationDir);
        File dest_dir = new File(dest_dir_path);

        createDir(dest_dir);

        AssetManager asset_manager = getApplicationContext().getAssets();
        String[] files = asset_manager.list(arg_assetDir);

        for (int i = 0; i < files.length; i++)
        {

            String abs_asset_file_path = addTrailingSlash(arg_assetDir) + files[i];
            String sub_files[] = asset_manager.list(abs_asset_file_path);

            if (sub_files.length == 0)
            {
                // It is a file                String dest_file_path = addTrailingSlash(dest_dir_path) + files[i];
                copyAssetFile(abs_asset_file_path, dest_file_path);
            } else            {
                // It is a sub directory                copyDirorfileFromAssetManager(abs_asset_file_path, addTrailingSlash(arg_destinationDir) + files[i]);
            }
        }

        return dest_dir_path;
    }


    public void copyAssetFile(String assetFilePath, String destinationFilePath) throws IOException
    {
        InputStream in = getApplicationContext().getAssets().open(assetFilePath);
        OutputStream out = new FileOutputStream(destinationFilePath);

        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0)
            out.write(buf, 0, len);
        in.close();
        out.close();
    }

    public String addTrailingSlash(String path)
    {
        if (path.charAt(path.length() - 1) != '/')
        {
            path += "/";
        }
        return path;
    }

    public String addLeadingSlash(String path)
    {
        if (path.charAt(0) != '/')
        {
            path = "/" + path;
        }
        return path;
    }

    public void createDir(File dir) throws IOException
    {
        if (dir.exists())
        {
            if (!dir.isDirectory())
            {
                throw new IOException("Can't create directory, a file is in the way");
            }
        } else        {
            dir.mkdirs();
            if (!dir.isDirectory())
            {
                throw new IOException("Unable to create directory");
            }
        }
    }
}

Thursday 25 August 2016

File transfer from Assets folder to Phone Storage with AsyncTask


Add below permission to AndroidManifest.xml


<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


MainActivity.java



import java.io.File;
import java.util.ArrayList;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends Activity {
// this where your file will be stored in sdcard in this case in folder (YOUR_FILE)
static String BASE_FILE = Environment.getExternalStorageDirectory()+"/YOUR_FILE/";
ArrayList<String> TmpList = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// create dynamic array to add your files
ArrayList<String> MyFiles = new ArrayList<String>();
MyFiles.add("demo_voice.mp3");
MyFiles.add("demo_img.jpg");
// add your files here
// create base folder if not exists
File f = new File(BASE_FILE);
if(!f.exists())
f.mkdir();
// this loop to check if files already coped or not or any file delete
for(int i=0;i<MyFiles.size();i++){
File check = new File(BASE_FILE,MyFiles.get(i));
if(!check.exists())
TmpList.add(MyFiles.get(i)); // copy not coped items to other list
}
// now check if not all files copy or something remove
if(TmpList.size()>0)
new AsyncCopy(this, BASE_FILE, TmpList).execute("");
else
Toast.makeText(getApplicationContext(), "all files coped ",Toast.LENGTH_LONG).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

AsyncCopy.java


import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.widget.Toast;
public class AsyncCopy extends AsyncTask<String, String, String>{
String savePath;
Activity ctx;
private ProgressDialog pDialog;
ArrayList<String> arr;
AsyncCopy(Activity _ctx,String _savePath,ArrayList<String> Files){
this.ctx = _ctx;
this.savePath = _savePath;
this.arr = Files;
}
@Override
protected void onPreExecute() {
pDialog = new ProgressDialog(ctx);
pDialog.setMessage("Copying files from asset to sdcard");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
super.onPreExecute();
}
@Override
protected String doInBackground(String... urls) {
File f = new File(savePath);
if(!f.exists())
f.mkdir();
for(int i=0;i<arr.size();i++)
Copy(arr.get(i));
return null;
}
@Override
protected void onPostExecute(String unused) {
Toast.makeText(ctx,"Copy Done",Toast.LENGTH_LONG).show();
pDialog.hide();
}
void Copy(String fname){
try{
int count;
InputStream input= ctx.getAssets().open(fname);
OutputStream output = new FileOutputStream(savePath+"/"+fname);
byte data[] = new byte[1024];
while ((count = input.read(data))>0) {
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}catch(Exception e){
// error while copying
}
}
}