I just used this to create a .apk file of my website. Is it possible that this file be run without accessing data connections or wifi? But all the same, the website should get updated when the Wifi or data is switched on. Anyone have anything that can help me?
First store your website's file in asset folder.
Now everytime you open the app, check if the website file exists or not to prevent app from crashing.
The code given below checks that and if it doesn't exist, then it calls a method which copies the file from asset to device storage.
File file = new File(YOUR FILE PATH);
if(!file.exists()){
//Doesn't exist. Create it in sdcard
copyAssets();
}
Here are the methods to copy the website file from asset to device storage (put them in your class) -
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(DIRECTORY, filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
}
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);
}
}
Then check internet connection of user (in oncreate method) -
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
//user is connected to internet
//put the code given ahead over here
}
Permission -
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Now if the user is connected to the internet, access the internet and get your website's new source code like this (put this code in internet checking code given above) -
URL url = new URL(YOUR URL);
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream(), "UTF-8"));
String inputLine;
StringBuilder a = new StringBuilder();
while ((inputLine = in.readLine()) != null)
a.append(inputLine);
in.close();
String source = a.toString();
Now once you have the source code, update your HTML file in device storage like this -
File gpxfile = new File(File address, "filename.html");
BufferedWriter bW;
try {
bW = new BufferedWriter(new FileWriter(gpxfile));
bW.write(source); //our new source code
bW.newLine();
bW.flush();
bW.close();
} catch (IOException e) {
e.printStackTrace();
}
You are done! Now load your file to webView from storage like this (in oncreate method after all the code that we wrote before) -
index.loadUrl("file://"+Environment.getExternalStorageDirectory()+ "Your address in storage");
It is recommended to send user requests time to time to turn on their internet to update the website and prevent use of outdated copy of it.
Related
My device is htc one dual sim and for some reason Environment.getExternalStorageDirectory() is my memory of the phone, it's not removable sd card.
I tried to find the real sd card path using this:
public static HashSet<String> getExternalMounts() {
final HashSet<String> out = new HashSet<String>();
String reg = "(?i).*vold.*(vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*";
String s = "";
try {
final Process process = new ProcessBuilder().command("mount")
.redirectErrorStream(true).start();
process.waitFor();
final InputStream is = process.getInputStream();
final byte[] buffer = new byte[1024];
while (is.read(buffer) != -1) {
s = s + new String(buffer);
}
is.close();
} catch (final Exception e) {
e.printStackTrace();
}
// parse output
final String[] lines = s.split("\n");
for (String line : lines) {
if (!line.toLowerCase(Locale.US).contains("asec")) {
if (line.matches(reg)) {
String[] parts = line.split(" ");
for (String part : parts) {
if (part.startsWith("/"))
if (!part.toLowerCase(Locale.US).contains("vold"))
out.add(part);
}
}
}
}
return out;
}
And i got
/mnt/media_rw/ext_sd
I tried to write files to /mnt/media_rw/ext_sd/downloads
but the file didn't appear to be created.
File file = new File("/mnt/media_rw/ext_sd/downloads", "test.txt");
FileWriter writer = null;
try {
writer = new FileWriter(file);
writer.write("sdfsdfsfd");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
02-11 23:12:35.236 9110-9110/www.jenyakirmiza.com.testsdcard W/System.errīš java.io.FileNotFoundException: /mnt/media_rw/ext_sd/downloads/test.txt: open failed: EACCES (Permission denied)
I heard smth about restriction starting from 4.4 so now we can't write files to removable sd card. But they said you can write filed to /sdcardpath/Android/data/your.package.name
ps. of course i added write_external permisssion to manifest.
You can find all external storages with Context.getExternalMediaDirs and can check whether it is removable with Environment.isExternalStorageRemovable(File). Note that Downloads directory will most likely be only in the primary (emulated) external storage.
Try using Environment.getExternalStorageDirectory() method :
File file = new File(Environment.getExternalStorageDirectory() + "/Download/", "test.txt");
and you can evaluate first if your file really exists with exists() method :
File file = new File(Environment.getExternalStorageDirectory() + "/Download/", "test.txt");
if(file.exists()){
FileWriter writer = null;
try {
writer = new FileWriter(file);
writer.write("sdfsdfsfd");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Very important to have this permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
inside your
AndroidManifest.xml
I must transfer a data file necessary for my app.
I read many threads on the subject and I stll don't understand how it works.
1. I'm using android studio 0.8.6. A lot of threads mentions the folder assets which apparently resides in src/main. When I create a new project the folder doesn't exist. I create manually one and I put in it jpg and txt files.
2. I run the following code:
AssetManager am = getAssets();
String[] files = new String[0];
try {
files = am.list("Files ;
} catch (IOException e) {
e.printStackTrace();
}
for(int i=0;i<files.length;i++){
Toast.makeText(getApplicationContext(), "File: "+files[i]+" ", Toast.LENGTH_SHORT).show();
}
And I get a files.length = 0
1. I can create files, write in it and read it but I don know where they reside.
And that's not what I want to do. I want to pass the data with the app.
Sorry for the long email but I'm lost.
Thanks in advance!
The code I have used to read files from assets is listed below:
public String ReadFromfile(String fileName, Context context) {
StringBuilder returnString = new StringBuilder();
InputStream fIn = null;
InputStreamReader isr = null;
BufferedReader input = null;
try {
fIn = context.getResources().getAssets()
.open(fileName, Context.MODE_WORLD_READABLE);
isr = new InputStreamReader(fIn);
input = new BufferedReader(isr);
String line = "";
while ((line = input.readLine()) != null) {
returnString.append(line);
}
} catch (Exception e) {
e.getMessage();
} finally {
try {
if (isr != null)
isr.close();
if (fIn != null)
fIn.close();
if (input != null)
input.close();
} catch (Exception e2) {
e2.getMessage();
}
}
return returnString.toString();
}
This code is not mine and can be found in the answers below:
read file from assets
I did some progress using the following code:
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
File dir = getFilesDir();
File f = new File("/data/data/com.example.bernard.myapp/");
File file[] = f.listFiles();
for(int i=0;i<file.length;i++){
Toast.makeText(getApplicationContext(), "File: "+String.valueOf(file[i]), Toast.LENGTH_SHORT).show();
}
}
I code in hard what seems to me like the root of my app:
File f = new File("/data/data/com.example.bernard.myapp/");
The result is I can see 3 files: lib, cache, files
in "files" appears the files I create running the app.
I still don't know where is assets, neither where I transfer/put the .txt and .jpg files I want to use with my app. I develop using studio.
how to read a specific file from sdcard. i have pushed the file in sdcard through DDMS and i am trying to read it though this way but this give me exception. can anybody tell me how to point exactly on that file?
my code is this.
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
FileInputStream iStream = new FileInputStream(path);
You are trying to read a directory... what you need is the file! Do something like this... then, you can read the file as you want.
File dir = Environment.getExternalStorageDirectory();
File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext");
To read any file(CSV in my case) from External Storage, we need a path for it,once you have path you can do like this...
void readFileData(String path) throws FileNotFoundException
{
String[] data;
File file = new File(path);
if (file.exists())
{
BufferedReader br = new BufferedReader(new FileReader(file));
try
{
String csvLine;
while ((csvLine = br.readLine()) != null)
{
data=csvLine.split(",");
try
{
Toast.makeText(getApplicationContext(),data[0]+" "+data[1],Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Log.e("Problem",e.toString());
}
}
}
catch (IOException ex)
{
throw new RuntimeException("Error in reading CSV file: "+ex);
}
}
else
{
Toast.makeText(getApplicationContext(),"file not exists",Toast.LENGTH_SHORT).show();
}
}
/*
csv file data
17IT1,GOOGLE
17IT2,AMAZON
17IT3,FACEBOOK*/
I am using following code to download and read a PDF file from internal storage on device.
I am able to download the files successfully to the directory:
data/data/packagename/app_books/file.pdf
But I am unable to read the file using a PDF reader application like Adobe Reader.
Code to download file
//Creating an internal dir;
File mydir = getApplicationContext().getDir("books", Context.MODE_WORLD_READABLE);
try {
File file = new File(mydir, outputFileName);
URL downloadUrl = new URL(url);
URLConnection ucon = downloadUrl.openConnection();
ucon.connect();
InputStream is = ucon.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
byte data[] = new byte[1024];
int current = 0;
while ((current = is.read(data)) != -1) {
fos.write(data, 0, current);
}
is.close();
fos.flush();
fos.close();
isFileDownloaded=true;
} catch (IOException e) {
e.printStackTrace();
isFileDownloaded = false;
System.out.println(outputFileName + " not downloaded");
}
if (isFileDownloaded)
System.out.println(outputFileName + " downloaded");
return isFileDownloaded;
Code to read the file
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent,
PackageManager.MATCH_DEFAULT_ONLY);
try {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
File fileToRead = new File(
"/data/data/com.example.filedownloader/app_books/Book.pdf");
Uri uri = Uri.fromFile(fileToRead.getAbsoluteFile());
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
} catch (Exception ex) {
Log.i(getClass().toString(), ex.toString());
Toast.makeText(MainActivity.this,
"Cannot open your selected file, try again later",
Toast.LENGTH_SHORT).show();
}
All works fine but the reader app says "File Path is not valid".
Your path is only valid for your app. Place the file in a place where other apps can 'see' it. Use GetExternalFilesDir() or getExternalStorageDirectory().
Note about files which are created inside the directory created by Context.getDir(String name, int mode) that they will only be accessible by your own application; you can only set the mode of the entire directory, not of individual files.
So you can use Context.openFileOutput(String name, int mode). I'm re-using your code for an example:
try {
// Now we use Context.MODE_WORLD_READABLE for this file
FileOutputStream fos = openFileOutput(outputFileName,
Context.MODE_WORLD_READABLE);
// Download data and store it to `fos`
// ...
You might want to take a look at this guide: Using the Internal Storage.
If you would like to keep the file app specific, you can use PdfRenderer available for Lollipop and above builds. There are great tutorials on google and youtube that work well. The method you are using is a secure way to store a PDF file that is only readable from inside the app ONLY. No outside application like Adobe PDF Reader will be able to even see the file.It took me a lot of seaching but I found a solution to my specific usage by using this site and especially youtube.
How to download PDF file from asset folder to storage by making folder
make sure you have storage permission are given like marshmallow device support etc then follow these steps
private void CopyReadAssets()
{
AssetManager assetManager = getContext().getAssets();
FileInputStream in = null;
FileOutputStream out = null;
File sdcard = Environment.getExternalStorageDirectory();
File dir = new File(Environment.getExternalStorageDirectory()+File.separator+ "A_level");
File dir2;
if (dir.exists() && dir.isDirectory()){
Log.e("tag out", ""+ dir);
}else {
dir.mkdir();
Log.e("tag out", "not exist");
}
File file = new File(dir, mTitle+".pdf");
try
{
Log.e("tag out", ""+ file);
out = new FileOutputStream(file);
in = new FileInputStream (new File(mPath));
Log.e("tag In", ""+ in);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e)
{
Log.e("tag out", ""+ out);
Log.e("tag In", ""+ in);
Log.e("tag", e.getMessage());
Log.e("tag", ""+file);
Log.i("tag",""+sdcard.getAbsolutePath() + "A_level");
}
}
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);
}
}
I am new in android development, and I'm trying to create a simple application which reads some data from a text file and displays it in a ListView. The problem is my reader doesn't find my file. I've debugged my application and that is the conclusion I've come up with. So, where does the text file have to placed in order for the reader to find it?
Heres some code:
try
{
FileInputStream fstream = new FileInputStream("movies.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null)
{
filme.add(strLine);
Log.d(LOG_TAG,"movie name:" + strLine);
}
in.close();
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
Thanks!
Put the file named movies.txt in res/raw, then use the following code
String displayText = "";
try {
InputStream fileStream = getResources().openRawResource(
R.raw.movies);
int fileLen = fileStream.available();
// Read the entire resource into a local byte buffer.
byte[] fileBuffer = new byte[fileLen];
fileStream.read(fileBuffer);
fileStream.close();
displayText = new String(fileBuffer);
} catch (IOException e) {
// exception handling
}
FileInputStream fstream = new FileInputStream("movies.txt");
where is the path for movies.txt ?? You must need to give the path as sd card or internal storage wherever you have stored.
As if, it is in sd card
FileInputStream fstream = new FileInputStream("/sdcard/movies.txt");
Usually when you want to open a file you put it into the res folder of your project.
When you want to open a text file, you can put it into the res/raw directory. Your Android eclipse plugin will generate a Resource class for you containing a handle to your textfile.
To access your file you can use this in your activity:
InputStream ins = getResources().openRawResource(R.raw.movies);
where "movies" is the name of your file without the filetype.
If you store your files on the SD card, then you can get the root of the SD card with Environment.getExternalStorageDirectory().
Note, that you might not be able to access the SD card, if it is mounted to the computer for example.
You can check the state of the external storage like this:
boolean externalStorageAvailable = false;
boolean externalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
externalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
externalStorageAvailable = true;
externalStorageWriteable = false;
} else {
externalStorageAvailable = mExternalStorageWriteable = false;
}
if(externalStorageAvailable && externalStorageWriteable){
File sdRoot = Environment.getExternalStorageDirectory();
File myFile = new File(sdRoot, "path/to/my/file.txt");
}