android webpages in webview - android

i want to store webpages inside the android project folder so that a user does nor needs a internet connection to view the webpages. i am using android webview. i am able to see the webpages with the HTTP protocol . My code is as below:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
WebView webview = (WebView) findViewById(R.id.webView1);
// webview.loadUrl("http://www.mysite.com/index.html");
webview.getSettings().setJavaScriptEnabled(true);
}
but i want to see the webpages offline. is there any way that webpages can be stored as resource in android project folder and view even without internet connection?

yes !
Put them in the /assets folder and access them like this :
webview.loadUrl("file:///android_asset/my_html_page.html");
This questions already have been answered : Webview load html from assets directory

store the webpage in your Asset folder and use
public File getfile(String filename) throws IOException {
// TODO Auto-generated method stub
String externalStorage_path =Environment.getExternalStorageDirectory().toString();
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)){
File dir = new File(externalStorage_path + "/yourfilename");
dir.mkdir();
File mfile = new File(dir,filename);
if( mfile.exists()==true) return mfile;
else{
try{
InputStream myInput = mcontext.getAssets().open(filename);
String path =externalStorage_path+"/yourfilename";
OutputStream myOutput = new FileOutputStream (path);
byte[] buffer = new byte[1024];
int length;
try {
while((length = myInput.read(buffer))>0)
myOutput.write(buffer,0,length);
}catch(FileNotFoundException e){Log.d("error",""+ e.toString());
}finally{
myOutput.flush();
myOutput.close();
myInput.close();
}
}catch(IOException e){ }
File dir1 = new File(externalStorage_path + "/yourfilename");
dir1.mkdir();
File mfile1 = new File(dir,filename);
return mfile1;
}
}else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){
showToast("External storage has readonly access");
} else if (Environment.MEDIA_REMOVED.equals(state)) {
showToast("External storage not present");
} else if (Environment.MEDIA_UNMOUNTABLE.equals(state)){
showToast("External storage cannot be mounted. Sdcard problem");
}
this will write the file in your storage and can be share by another Application like Adobe to open. jUST called this method.

Related

Android - Read pdf and display it using Intent

I am developing an app in that I wanted to display a pdf file from asset. I did so much google and also tried number of permutations and combinations but not working.
CODE:
private void CopyReadAssets()
{
AssetManager assetManager = getActivity().getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/abc.pdf");
try
{
in = assetManager.open("abc.pdf");
out = getActivity().openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch (Exception e)
{
Log.e("tag", e.getMessage());
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
}
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);
}
}
when I click on list, I call CopyReadAssets() function then it prompts me in which viewer you want to open then I click on AdobeReader then it shows following error.
I have check your code There are some mistake that you have to change and May be you have copied code from here.
Replace
AssetManager assetManager = getAssets();
Instead of AssetManager assetManager = getActivity().getAssets();
Direct Use File file = new File(getFilesDir(), "abc.pdf");
Instead of
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/abc.pdf");
Hope its works for you.!!!
You can do this By using web view-
webview = (WebView) findViewById(R.id.prayertimes_webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setPluginsEnabled(true);
webview.getSettings().setSupportZoom(true);
webview.getSettings().setBuiltInZoomControls(true);
String urll = "http://docs.google.com/gview?embedded=true&url=" + url;
webview.setWebViewClient(new WebViewClient());
webview.loadUrl(urll);
The PDF file cannot be seen from the PDF reader because anything inside of your assets are private to your app. You have to make it public in some way. There are several ways for this.
The most sophisticated way is to implement a public ContentProvider and override the openAssetFile method in it. Pass the URL for the file through Intent, and the PDF reader should be able to use ContentResolver and get the PDF file by openAssetFileDescriptor method.
Here's a link.
- http://www.nowherenearithaca.com/2012/03/too-easy-using-contentprovider-to-send.html

reading pdf from url using pdfViewer library in android app

I made an android app for viewing Pdf file fetched from URL by integrating pdfViewer library in my code.Firstly app downloading the file from web to external sd card then from there the app is getting opened with PdfViewer library.It is working fine if the file size is small but if the pdf file contains images and size is more , the downloaded file size shown in sdcard is 0kb.
Can someone help me out why this is so?
Following is java code :
public class MainActivity extends Activity {
static Context applicationContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
applicationContext = getApplicationContext();
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "pdfDownloads");
folder.mkdir();
File file = new File(folder, "android.pdf");
try {
if(!file.exists()) {
file.createNewFile();
}
} catch (IOException e1) {
e1.printStackTrace();
}
boolean downloadFile = downloadFile("http://www.irs.gov/pub/irs-pdf/fw4.pdf", file);
if (file!=null && file.exists() && file.length() > 0){
Intent intent = new Intent(this, com.example.soniapdf.Second.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME,
file.getAbsolutePath());
startActivity(intent);
}
}
public static boolean downloadFile(String fileUrl, File directory) {
try {
FileOutputStream f = new FileOutputStream(directory);
URL u = new URL(fileUrl);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
//
int fileLength = c.getContentLength();
long total = 0;
//
Toast.makeText(applicationContext, "Downloading PDF...", 2000).show();
while ((len = in.read(buffer)) > 0) {
total += len;
//Toast.makeText(applicationContext, "Downloading PDF: remaining " + (fileLength / total )+ "%", 1).show();
f.write(buffer, 0, len);
}
f.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
This is a way for showing PDF in android app that is embedding the PDF document to android webview using support from http://docs.google.com/viewer
pseudo
String doc="<iframe src='http://docs.google.com/viewer?url=+location to your PDF File+'
width='100%' height='100%'
style='border: none;'></iframe>";
a sample is is shown below
String doc="<iframe src='http://docs.google.com/viewer?url=http://www.iasted.org/conferences/formatting/presentations-tips.ppt&embedded=true'
width='100%' height='100%'
style='border: none;'></iframe>";
Code
WebView wv = (WebView)findViewById(R.id.webView);
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setPluginsEnabled(true);
wv.getSettings().setAllowFileAccess(true);
wv.loadUrl(doc);
//wv.loadData( doc, "text/html", "UTF-8");
and in manifest provide
<uses-permission android:name="android.permission.INTERNET"/>
SEE THIS ANSWER
EDIT
If your PDF document is accessible online, use the Google Docs Viewer to open your PDF in a WebView
REFER
wv.loadUrl("https://docs.google.com/gview?embedded=true&url=http://www.irs.gov/pub/irs-pdf/fw4.pdf");
Don't Know how Stable These are
Here is the list of the other open sources PDF readers running on the top of the Android
Android PDF Viewer
APDFViewer
droidreader
android-pdf
Please note that these and any other project derived from MuPDF is bound by the terms of GPL and may not be suitable for the commerical use.
The following is a list of SDKs suitable for commerical use:
PDFTron
Adobe
Qoppa
Radaee

Load the pdf file in app from assets

I have a PDF file stored in my assets. I want to load the PDF from my assets and read it in the app itself without using any 3rd party app to view.
I got the solution in this link. It works fine when selecting files from sdcard.
Following snippet might help you accessing files from asset folder and then open it:
private void ReadFromAssets()
{
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "file.pdf");
try
{
in = assetManager.open("file.pdf");
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e)
{
Log.e("tag", e.getMessage());
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file://" + getFilesDir() + "/file.pdf"),
"application/pdf");
startActivity(intent);
}
and copyFile method is as follows:
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);
}
}
EDIT
For that purpose you'll have to use an ecternal library. It's explained quite well in the link below:
Render a PDF file using Java on Android
Hope this will help you.
Its better if you can open it using a webview
WebView web = (WebView) findViewById(R.id.webView1);
web.loadUrl("file:///android_asset/yourpdf.pdf");
Hope it works.
Ooops just now I checked, the pdf cannot be loaded in the web view
Sorry

I need to use a picture in a webview to zoom it

I succeded to set apicture in the sdcard of the emulator to simulate the work of the picture in a webview but I don't know how to set it in the final apk package.
The picture is called map.png and is set either in drawable and assets but I unsuccessfully tried many way to load it in the ...loadUrl(...)
This is my code I wish someone can help me.
public class Map extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
WebView myWebView = (WebView) findViewById(R.id.webMap);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setBuiltInZoomControls(true);
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl("file://mnt/sdcard/map.png");
This is the new edited code that works in the emulator from asset, where do I have to put your new code to make anything working from the package.
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl("file:///android_asset/map.png");
setContentView(myWebView);
Please, use my picture filename otherwise I don't understand it.
Again. I am...
I have a basic way for this.. just put your files in Assets directory and at runtime copy that files in either Internal storage or External Storage(sdcard).
like,
try {
// Open your local file as the input stream
InputStream myInput = myContext.getAssets().open("image.png");
// Path to the just created empty file
String outFileName = "/data/data/<Package Name>/files/newImage.png";
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0)
{
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
catch (Exception e)
{
Log.e("error", e.toString());
}

Moving asset to /data/data/APP_NAME/files

Quick reference on what I have read
http://thedevelopersinfo.com/2009/11/17/using-assets-in-android/
http://www.wiseandroid.com/post/2010/06/14/Android-Beginners-Intro-to-Resources-and-Assets.aspx
There are more but as a newb can only post 2.
In my app there is a button the will a reboot into the bootloader if the user decides to do so on rooted devices. I have a reboot binary called "reboot" that will allow the commmand to run and it is in /assets/. Using the methods above I can not seem to get "reboot" to move or even create the directory "files" in /data/data/ of my apk. My question is, is there a better guide to school me in the subject or are these the best and I am just to thick headed to understand it. Or if you have some other sample codes I can read through and try and understand would be perfect. Thank you.
Added sample of what I am doing
$ public static String moveReboot = "/data/data/com.DPE.MuchSuck/Files";
public static String reboot = "file:///android_asset/reboot";
public static Context myContext;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
moveFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
$ public void moveFile() throws IOException {
AssetManager assetManager = getAssets();
InputStream myInput = assetManager.open(reboot);
String outFileName = moveReboot + reboot;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte [1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
Upon running the apk nothing shows up in the "Files" nor does "Files even show up.
doug,
it looks like your "outFileName" won't contain a good filename.
Try using getExternalFilesDir() to obtain a path to SDRAM.
see: http://developer.android.com/reference/android/content/Context.html#getExternalFilesDir%28java.lang.String%29
EDIT...
doug, this is my implementation
private void copyAssetToSDRAM(String strFilename)
{
try
{
//complete path to target file
File fileTarget = new File(Environment.getExternalStorageDirectory(), strFilename);
//data source stream
AssetManager assetManager = ApplicationContext.getContext().getAssets();
InputStream istr = assetManager.open(strFilename);
//data destination stream
//NOTE: at this point you'll get an exception if you don't have permission to access SDRAM ! (see manifest)
OutputStream ostr = new FileOutputStream(fileTarget);
byte[] buffer = new byte[1024];
int length;
while ((length = istr.read(buffer))>0)
{
ostr.write(buffer, 0, length);
}
ostr.flush();
ostr.close();
istr.close();
}
catch(Exception e)
{
Toast.makeText(ApplicationContext.getContext(), "File-Copy Error: "+strFilename, Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
to use it, do this:
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
{
copyAssetToSDRAM("myfile.png");
}
else
{
Toast.makeText(ApplicationContext.getContext(), "Unable to copy images. NO SDRAM", Toast.LENGTH_LONG).show();
}

Categories

Resources