following is my code,
From Activity class
Intent intent = new Intent(this, DownloadService.class);
// Create a new Messenger for the communication back
Messenger messenger = new Messenger(handler);
intent.putExtra("MESSENGER", messenger);
intent.setData(Uri.parse("http://www.abc.ezy.asia/E-MobApps/op.apk"));
intent.putExtra("urlpath", "http://www.abc.ezy.asia/E-MobApps/op.apk");
startService(intent);
I have overrided Service Class method onHandle Event
// DownloadService Class
#Override
protected void onHandleIntent(Intent intent) {
Uri data = intent.getData();
String urlPath = intent.getStringExtra("urlpath");
String fileName = data.getLastPathSegment();
File output = new File(Environment.getExternalStorageDirectory(),fileName);
if (output.exists()) {
output.delete();
}
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
stream = url.openConnection().getInputStream();
fos = new FileOutputStream(output.getPath());
byte dataB[] = new byte[1024];
InputStreamReader reader = new InputStreamReader(stream);
int next = -1;
while ((next = reader.read()) != -1) {
fos.write(next);
}
fos.flush();
result = Activity.RESULT_OK;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Bundle extras = intent.getExtras();
if (extras != null) {
Messenger messenger = (Messenger) extras.get("MESSENGER");
Message msg = Message.obtain();
msg.arg1 = result;
msg.obj = output.getAbsolutePath();
try {
messenger.send(msg);
} catch (android.os.RemoteException e1) {
Log.w(getClass().getName(), "Exception sending message", e1);
}
}
}
}
In above code I used File Streams & Input stream reader for downloading
when tried to download html file then complete file was downloaded to my sdcard.But when I tried for APK. The File downloaded of 2.2 mb instead of 2.4 mb Parsing problem is there. Kindly help me to resolve the issue.
try this piece of code :
URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(output.getPath());
byte data[] = new byte[1024];
int count;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
input.close();
result = Activity.RESULT_OK;
Related
I have already succeeded with this operation with images, but I cannot do it with other type of file, in my case I try to insert a database.
Here is an example of the code for the images:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
try {
try {
pictures = assetManager.list("photos/dataset1");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
if (pictures != null) {
for (String filename : pictures) {
InputStream in;
OutputStream out;
InputStream inputStream = assetManager.open("photos/dataset1/"+filename);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
saveImageToGallery(bitmap);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
This method below works for the images :
public void saveImageToGallery(Bitmap bitmap) {
OutputStream outputStream;
Context myContext = requireContext();
try {
if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.Q){
ContentResolver contentResolver = requireContext().getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME,"Image_"+".jpg");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
Uri imageUri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
outputStream = contentResolver.openOutputStream(Objects.requireNonNull(imageUri));
bitmap.compress(Bitmap.CompressFormat.JPEG,100, outputStream);
Objects.requireNonNull(outputStream);
}
}catch (FileNotFoundException e) {
e.printStackTrace();
}
}
and there my try for the other type of file :
AssetManager assetManager = Objects.requireNonNull(requireContext()).getAssets();
Context myContext = requireContext();
//Essential for creating the external storage directory for the first launch
myContext.getExternalFilesDir(null);
File databasesFolder = new File(myContext.getExternalFilesDir(null).getParent(), "com.mydb.orca/databases");
databasesFolder.mkdirs();
if (files!= null) {
for (String filename : files) {
InputStream in;
OutputStream out;
try {
in = assetManager.open("database/test/" + filename);
File outFile = new File(databasesFolder, filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
out.flush();
out.close();
} catch (IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
} else {
Log.e("Error NPE", "files is null");
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
This code above is not working, I mean, I don't get any errors or the desired result. I want something like this or a function similary as the function for my images but for any type of file.
When I run my application I have no error however nothing happens
I finally find a solution, I pretty sure it's not the best way but it work.
I give me access to all files acccess by this way :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
try {
Intent intentFiles = new Intent();
intentFiles.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
Uri uriFiles = Uri.fromParts("package", myContext.getPackageName(), null);
intentFiles.setData(uriFiles);
myContext.startActivity(intentFiles);
} catch (Exception e)
{
Intent intentFiles = new Intent();
intentFiles.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
myContext.startActivity(intentFiles);
}
add this line to your manifest:
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
after that, this code below work :
AssetManager assetManager = Objects.requireNonNull(requireContext()).getAssets();
Context myContext = requireContext();
//Essential for creating the external storage directory for the first launch
myContext.getExternalFilesDir(null);
File databasesFolder = new File(myContext.getExternalFilesDir(null).getParent(), "com.mydb.orca/databases");
databasesFolder.mkdirs();
if (files!= null) {
for (String filename : files) {
InputStream in;
OutputStream out;
try {
in = assetManager.open("database/test/" + filename);
File outFile = new File(databasesFolder, filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
out.flush();
out.close();
} catch (IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
} else {
Log.e("Error NPE", "files is null");
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
if someone have a best solution it should be nice
I tested on android 11 and it work
I'm working on sample project. I'm trying to download apk from Google drive (by sharable link) and trying to install an update to already existing application
This is my code to download and install the update:
class DownloadApkTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL("https://drive.google.com/file/d/0B2U-9Im6jS66dHFXLTFIX0JQbnM/view?usp=sharing");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
String error = "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// download the file
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/tcr_update.apk");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
output.write(data, 0, count);
}
} catch (Exception e) {
Log.d("TAG", "doInBackground: "+e.getMessage());
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
Below code is for opening the application installer
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
File apkFile = new File("/sdcard/tcr_update.apk");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
startActivity(intent);
}
}
I want to add a feature to my app in which the users can upload files (PDF files) from their mobile to the database, then download this file back to the app and display it.
I have no idea how to start doing this and what is the right code to use.
I tried using this code,
ParseObject pObject = new ParseObject("ExampleObject");
pObject.put("myNumber", number);
pObject.put("myString", name);
pObject.saveInBackground(); // asynchronous, no callback
- EDIT -
I tried this code but the app crashes when I click the button:
public class Test extends Activity {
Button btn;
File PDFFile;
ParseObject po;
String userPDFFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
po = new ParseObject("pdfFilesUser");
btn = (Button) findViewById(R.id.button);
PDFFile = new File("res/raw/test.pdf");
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadPDFToParse(PDFFile, po, userPDFFile);
}
});
}
private ParseObject uploadPDFToParse(File PDFFile, ParseObject po, String columnName){
if(PDFFile != null){
Log.d("EB", "PDFFile is not NULL: " + PDFFile.toString());
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(PDFFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int read;
byte[] buff = new byte[1024];
try {
while ((read = in.read(buff)) > 0)
{
out.write(buff, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
byte[] pdfBytes = out.toByteArray();
// Create the ParseFile
ParseFile file = new ParseFile(PDFFile.getName() , pdfBytes);
po.put(columnName, file);
// Upload the file into Parse Cloud
file.saveInBackground();
po.saveInBackground();
}
return po;
}
}
You can upload a file manually via REST API. Take a look at this docs here
Can try this code:
private ParseObject uploadPDFToParse(File PDFFile, ParseObject po, String columnName){
if(PDFFile != null){
Log.d("EB", "PDFFile is not NULL: " + PDFFile.toString());
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(PDFFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int read;
byte[] buff = new byte[1024];
try {
while ((read = in.read(buff)) > 0)
{
out.write(buff, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
byte[] pdfBytes = out.toByteArray();
// Create the ParseFile
ParseFile file = new ParseFile(PDFFile.getName() , pdfBytes);
po.put(columnName, file);
// Upload the file into Parse Cloud
file.saveInBackground();
po.saveInBackground();
}
return po;
}
For more details check this
I would strongly suggest you quickly get up to speed with the Parse Java development wiki.
To answer your question. You want to be using:
byte[] data = "Working at Parse is great!".getBytes();
ParseFile file = new ParseFile("resume.txt", data);
file.saveInBackground();
First declare your file etc then save it using that. But once again, first read the guidelines to better understand the framework you working with.
https://parseplatform.github.io/docs/android/guide/
I simply want to download mp4 or .3gp files from server to android device. I have tried multiple ways to achieve but in some cases it gives IOException and some time give ProtocolException
First Method to download Video using DownloadVideoTask.class
public class DownloadVideoTask extends AsyncTask<String, Integer, Boolean>
{
String nameOfSong;
Context context;
Boolean flage = true;
ProgressDialog progressDialog2;
#SuppressLint("InlinedApi")
public DownloadVideoTask(Context context,String trackTitle)
{
this.context = context;
nameOfSong = trackTitle;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
progressDialog2 = new ProgressDialog(context, AlertDialog.THEME_HOLO_LIGHT);
}
else
{
progressDialog2 = new ProgressDialog(context);
}
progressDialog2.setIndeterminate(false);
progressDialog2.setMax(100);
progressDialog2.setTitle("Please wait...");
try
{
progressDialog2.setMessage("Downloding.. " + nameOfSong.substring(0, 20));
}
catch (Exception e)
{
progressDialog2.setMessage("Downloding Song...." );
}
progressDialog2.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog2.show();
}
#Override
protected Boolean doInBackground(String... params)
{
/* String trackTitle = params[0];
nameOfSong = trackTitle;
*/
String trackUrl = params[0];
try
{
File root;// = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
{
root = Environment.getExternalStorageDirectory();
}
else
{
root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
}
File dir = new File(root.getAbsolutePath() + "/XarDownloder");
if (dir.exists() == false)
{
dir.mkdirs();
}
URL url = new URL(trackUrl);
File file = new File(dir, nameOfSong);
URLConnection urlConnection = url.openConnection();
int fileLength = urlConnection.getContentLength();//ye statement inputStream k bad likhi thi
InputStream inputStream = urlConnection.getInputStream();
OutputStream outputStream = new FileOutputStream(
root.getAbsolutePath() + "/XarDownloder/" + nameOfSong
+ ".mp4");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = inputStream.read(data)) != -1)
{
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / fileLength));
outputStream.write(data, 0, count);
}
outputStream.flush();
outputStream.close();
inputStream.close();
try
{
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
{
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
}
else
{
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC))));
}
context.sendBroadcast(new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri
.fromFile(file)));
}
catch (Exception e)
{
}
return true;
}
catch (IOException e)
{
flage = false;
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean result)
{
super.onPostExecute(result);
if (result)
{
try
{
Toast.makeText(context,
nameOfSong.substring(0, 30) + "Downloaded...",
Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Toast.makeText(context,
"Song Downloaded...",
Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(context, "Sorry, song is not downloadable",
Toast.LENGTH_LONG).show();
}
progressDialog2.dismiss();
}
#Override
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
progressDialog2.setProgress(values[0]);
}
}
Second Method using DownloadFile
public class DownloadFile extends AsyncTask<String, Integer, String>
{
String videoToDownload = "http://r2---sn-u2oxu-f5f6.googlevideo.com/videoplayback?expire=1438261718&fexp=901816,9405637,9407538,9407942,9408513,9408710,9409172,9413020,9414764,9414856,9414935,9415365,9415485,9416126,9416355,9417009,9417719,9418201,9418204&id=d813f7f3bef428da&mn=sn-u2oxu-f5f6&mm=31&mime=video/mp4&upn=82UaibRK7EM&itag=18&pl=24&dur=148.189&ip=167.114.5.145&key=yt5&ms=au&mt=1438239687&mv=u&source=youtube&ipbits=0&pcm2cms=yes&sparams=dur,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,pcm2cms,pl,ratebypass,source,upn,expire&lmt=1428049239028653&signature=39087CBD9BDC9EBD612CA0E8E82AC692B427FFE3.18C23CD0AEC8410CFBE4F35F532199DFF21E7DFA&ratebypass=yes&sver=3&signature=&title=How+To+Train+Your+Dragon+2+Official+Trailer+%231+%282014%29+-+Animation+Sequel+HD&filename=How_To_Train_Your_Dragon_2_Official_Trailer_1_2014__Animation_Sequel_HD.mp4";
public DownloadFile()
{
}
#Override
protected String doInBackground(String... params)
{
int count;
try
{
mp4load(videoToDownload);
}
catch (Exception e)
{
// TODO: handle exception
}
/*try
{
URL url = new URL(videoToDownload);
URLConnection conexion = url.openConnection();
conexion.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = conexion.getContentLength();
// downlod the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/xarwere/firstdownload.mp4");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1)
{
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
catch (Exception e)
{
e.printStackTrace();
}*/
return null;
}
public void mp4load(String urling)
{
try
{
URL url = new URL(urling);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
//c.setDoOutput(true);
con.connect();
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
//Log.v(LOG_TAG, "PATH: " + PATH);
File file = new File(PATH);
file.mkdirs();
String fileName = "test.mp4";
File outputFile = new File(file, fileName);
if (!outputFile.exists())
{
outputFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(outputFile);
int status = con.getResponseCode();//my doctory
InputStream is = con.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (ProtocolException e)
{
e.printStackTrace();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
Where videoToDownload in DownloadFile.class is the URLi want to download. but at inputStream it gives exception.
And I call these AsyncTask like
new DownloadFile().execute();
new DownloadVideoTask(TestingActivity.this, "nameofsong").execute("http://r2---sn-u2oxu-f5f6.googlevideo.com/videoplayback?expire=1438261718&fexp=901816,9405637,9407538,9407942,9408513,9408710,9409172,9413020,9414764,9414856,9414935,9415365,9415485,9416126,9416355,9417009,9417719,9418201,9418204&id=d813f7f3bef428da&mn=sn-u2oxu-f5f6&mm=31&mime=video/mp4&upn=82UaibRK7EM&itag=18&pl=24&dur=148.189&ip=167.114.5.145&key=yt5&ms=au&mt=1438239687&mv=u&source=youtube&ipbits=0&pcm2cms=yes&sparams=dur,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,pcm2cms,pl,ratebypass,source,upn,expire&lmt=1428049239028653&signature=39087CBD9BDC9EBD612CA0E8E82AC692B427FFE3.18C23CD0AEC8410CFBE4F35F532199DFF21E7DFA&ratebypass=yes&sver=3&signature=&title=How+To+Train+Your+Dragon+2+Official+Trailer+%231+%282014%29+-+Animation+Sequel+HD&filename=How_To_Train_Your_Dragon_2_Official_Trailer_1_2014__Animation_Sequel_HD.mp4");
I slighthly modified your code, but it downloads the file well. Did you add the internet permission?
public class DownloadFile extends AsyncTask<String, Integer, String> {
String videoToDownload = "http://r2---sn-u2oxu-f5f6.googlevideo.com/videoplayback?expire=1438261718&fexp=901816,9405637,9407538,9407942,9408513,9408710,9409172,9413020,9414764,9414856,9414935,9415365,9415485,9416126,9416355,9417009,9417719,9418201,9418204&id=d813f7f3bef428da&mn=sn-u2oxu-f5f6&mm=31&mime=video/mp4&upn=82UaibRK7EM&itag=18&pl=24&dur=148.189&ip=167.114.5.145&key=yt5&ms=au&mt=1438239687&mv=u&source=youtube&ipbits=0&pcm2cms=yes&sparams=dur,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,pcm2cms,pl,ratebypass,source,upn,expire&lmt=1428049239028653&signature=39087CBD9BDC9EBD612CA0E8E82AC692B427FFE3.18C23CD0AEC8410CFBE4F35F532199DFF21E7DFA&ratebypass=yes&sver=3&signature=&title=How+To+Train+Your+Dragon+2+Official+Trailer+%231+%282014%29+-+Animation+Sequel+HD&filename=How_To_Train_Your_Dragon_2_Official_Trailer_1_2014__Animation_Sequel_HD.mp4";
#Override
protected String doInBackground(String... params) {
int count;
try {
mp4load(videoToDownload);
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
public void mp4load(String urling) {
try {
URL url = new URL(urling);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
//c.setDoOutput(true);
con.connect();
String downloadsPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
String fileName = "test.mp4";
File outputFile = new File(downloadsPath, fileName);
if (!outputFile.exists()) {
outputFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(outputFile);
int status = con.getResponseCode();
InputStream is = con.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am using http://www.siegmann.nl/epublib to read epub file. My code is mentioned below.
try {
book = epubReader.readEpub(new FileInputStream("/sdcard/EpubTesting.epub"));
Resource res;
Spine contents = book.getSpine();
List<SpineReference> spinelist = contents.getSpineReferences();
StringBuilder string = new StringBuilder();
String line = null;
int count = spinelist.size();
for (int i=0;i<count;i++){
res = contents.getResource(i);
try {
InputStream is = res.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
while ((line = reader.readLine()) != null) {
linez = (string.append(line+"\n")).toString();
}
} catch (IOException e) {e.printStackTrace();}
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(linez);
s1.loadDataWithBaseURL("/sdcard/",linez, "text/html", "UTF-8",null);
}catch (FileNotFoundException e) {
Toast.makeText(mContext, "File not found.", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(mContext, "IO Exception.", Toast.LENGTH_SHORT).show();
}
Also tried
s1.loadDataWithBaseURL("",linez, "text/html", "UTF-8",null);
s1.loadDataWithBaseURL("file://mnt/sdcard/",linez, "text/html", "UTF-8",null);
But result is sifar. Please tell me what I have to do to show the contained images in file. I have gone through FAQ says Make a subclass of android.webkit.WebView that overloads the loadUrl(String) method in such a way that it loads the image from the Book instead of the internet. But till I don't where they extract the file how can I locate the path. Please tell me. I am very confused. Thanks in advance.
public class EpubBookContentActivity extends Activity{
private static final String TAG = "EpubBookContentActivity";
WebView webview;
Book book;
int position = 0;
String line;
int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content);
webview = (WebView) findViewById(R.id.webView);
webview.getSettings().setJavaScriptEnabled(true);
AssetManager assetManager = getAssets();
String[] files;
try {
files = assetManager.list("books");
List<String> list =Arrays.asList(files);
if (!this.makeDirectory("books")) {
debug("faild to make books directory");
}
copyBookToDevice(list.get(position));
String basePath = Environment.getExternalStorageDirectory() + "/books/";
InputStream epubInputStream = assetManager.open("books/"+list.get(position));
book = (new EpubReader()).readEpub(epubInputStream);
DownloadResource(basePath);
String linez = "";
Spine spine = book.getSpine();
List<SpineReference> spineList = spine.getSpineReferences() ;
int count = spineList.size();
StringBuilder string = new StringBuilder();
for (int i = 0; count > i; i++) {
Resource res = spine.getResource(i);
try {
InputStream is = res.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
while ((line = reader.readLine()) != null) {
linez = string.append(line + "\n").toString();
}
} catch (IOException e) {e.printStackTrace();}
} catch (IOException e) {
e.printStackTrace();
}
}
linez = linez.replace("../", "");
// File file = new File(Environment.getExternalStorageDirectory(),"test.html");
// file.createNewFile();
// FileOutputStream fileOutputStream = new FileOutputStream(file);
// fileOutputStream.write(linez.getBytes());
// fileOutputStream.close();
webview.loadDataWithBaseURL("file://"+Environment.getExternalStorageDirectory()+"/books/", linez, "text/html", "utf-8", null);
} catch (IOException e) {
Log.e("epublib exception", e.getMessage());
}
}
public boolean makeDirectory(String dirName) {
boolean res;
String filePath = new String(Environment.getExternalStorageDirectory()+"/"+dirName);
debug(filePath);
File file = new File(filePath);
if (!file.exists()) {
res = file.mkdirs();
}else {
res = false;
}
return res;
}
public void debug(String msg) {
// if (Setting.isDebug()) {
Log.d("EPub", msg);
// }
}
public void copyBookToDevice(String fileName) {
System.out.println("Copy Book to donwload folder in phone");
try
{
InputStream localInputStream = getAssets().open("books/"+fileName);
String path = Environment.getExternalStorageDirectory() + "/books/"+fileName;
FileOutputStream localFileOutputStream = new FileOutputStream(path);
byte[] arrayOfByte = new byte[1024];
int offset;
while ((offset = localInputStream.read(arrayOfByte))>0)
{
localFileOutputStream.write(arrayOfByte, 0, offset);
}
localFileOutputStream.close();
localInputStream.close();
Log.d(TAG, fileName+" copied to phone");
}
catch (IOException localIOException)
{
localIOException.printStackTrace();
Log.d(TAG, "failed to copy");
return;
}
}
private void DownloadResource(String directory) {
try {
Resources rst = book.getResources();
Collection<Resource> clrst = rst.getAll();
Iterator<Resource> itr = clrst.iterator();
while (itr.hasNext()) {
Resource rs = itr.next();
if ((rs.getMediaType() == MediatypeService.JPG)
|| (rs.getMediaType() == MediatypeService.PNG)
|| (rs.getMediaType() == MediatypeService.GIF)) {
Log.d(TAG, rs.getHref());
File oppath1 = new File(directory, rs.getHref().replace("OEBPS/", ""));
oppath1.getParentFile().mkdirs();
oppath1.createNewFile();
System.out.println("Path : "+oppath1.getParentFile().getAbsolutePath());
FileOutputStream fos1 = new FileOutputStream(oppath1);
fos1.write(rs.getData());
fos1.close();
} else if (rs.getMediaType() == MediatypeService.CSS) {
File oppath = new File(directory, rs.getHref());
oppath.getParentFile().mkdirs();
oppath.createNewFile();
FileOutputStream fos = new FileOutputStream(oppath);
fos.write(rs.getData());
fos.close();
}
}
} catch (Exception e) {
}
}
}
For that you have to download all resources of epub files (i.e. images,stylesheet) in location where you downloaded .epub file in sdcard. please check below code to download images and css files from .epub files itself using epublib.
for that u have to send parameter of File objects where you want to store those images.
private void DownloadResource(File FileObj,String filename) {
try {
InputStream epubis = new FileInputStream(FileObj);
book = (new EpubReader()).readEpub(epubis);
Resources rst = book.getResources();
Collection<Resource> clrst = rst.getAll();
Iterator<Resource> itr = clrst.iterator();
while (itr.hasNext()) {
Resource rs = itr.next();
if ((rs.getMediaType() == MediatypeService.JPG)
|| (rs.getMediaType() == MediatypeService.PNG)
|| (rs.getMediaType() == MediatypeService.GIF)) {
File oppath1 = new File(directory, "Images/"
+ rs.getHref().replace("Images/", ""));
oppath1.getParentFile().mkdirs();
oppath1.createNewFile();
FileOutputStream fos1 = new FileOutputStream(oppath1);
fos1.write(rs.getData());
fos1.close();
} else if (rs.getMediaType() == MediatypeService.CSS) {
File oppath = new File(directory, "Styles/"
+ rs.getHref().replace("Styles/", ""));
oppath.getParentFile().mkdirs();
oppath.createNewFile();
FileOutputStream fos = new FileOutputStream(oppath);
fos.write(rs.getData());
fos.close();
}
}
} catch (Exception e) {
Log.v("error", e.getMessage());
}
}
after this use this your code to set path of images in webview.
if stored in sd card then
s1.loadDataWithBaseURL("file:///sdcard/",linez, "text/html",null,null);
or
s1.loadDataWithBaseURL("file://mnt/sdcard/",linez, "text/html", "UTF-8",null);
if in internal storage then
s1.loadDataWithBaseURL("file:///data/data/com.example.project/app_mydownload/",linez, "text/html",null,null);