Problems reading .txt file in Android - android

I am trying to read a file i download from Dropbox (using Dropbox CORE API).
private void downloadropboxfile(final String filename)
{
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
File file = new File(getCacheDir(),filename);
if(!file.exists())
file.createNewFile();
FileOutputStream outputStream = new FileOutputStream(file);
DropboxAPI.DropboxFileInfo info=mDBApi.getFile("/" + filename, null, outputStream, null);
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
Then in another function i call the downloaddropbox function and try to read the file content on Onclick event.
String filename = "info.txt";
downloadropboxfile(filename);
String strLine = "";
try {
InputStream instream = new FileInputStream(new File(getCacheDir(),filename));
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader bReader = new BufferedReader(inputreader);
/** Reading the contents of the file , line by line */
while ((strLine = bReader.readLine()) != null) {
mTestOutput.setText(strLine);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
My problem is that i don't get the file content immediately. I need to click the button 3-4 times in order to read the file content. What's the problem with my code?

You're calling downloaddropboxfile, which starts a new thread to download the file. But then you're immediately trying to read the local file (before it's downloaded).
If you haven't worked with threading before, the important thing to understand is that downloaddropboxfile returns almost immediately, but the thread it starts keeps running in the background. You'll need to wait for it to finish before trying to do something with the downloaded file.

Related

FileNotFoundException although the text file exist (readable and writable)

I am trying to save data into text file in the internal storage and read it again .. It works fine in my mobile with android 11 but when i tried at android 8 it gives me this error
java.io.FileNotFoundException:/data/user/0/com.example.example/test.txt
(No such file or directory)
It appears at the first time to open the activity but i can clear it - as normal text - and write a new text and save it so the file is there and usable
here is read code
File path = getApplicationContext().getFilesDir();
File readFrom = new File(path, fileName);
byte[] content = new byte[(int) readFrom.length()];
try {
FileInputStream stream = new FileInputStream(readFrom);
stream.read(content);
return new String(content);
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
and this write code
public void writeToFile(String fileName, String content) {
File path = getApplicationContext().getFilesDir();
try {
FileOutputStream writer = new FileOutputStream(new File(path, fileName));
writer.write(content.getBytes());
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}

How to transfer a txt data file to my Android app

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 append data in android (each data in new line)

I am making a bookmark for web browser app this code is saving and loading the data but it is not appending data in new line...every time i am pressing the button it is overwriting previous data ..I want that every time i call bookmarkload(); method in main activity it should save data in new line instead of overwriting it..Please help me as i am new to android tell what line to enter where..so that it start appending data..Thanks in advance ..please give answer in detail if possible.
public class Bookmark {
FileOutputStream fos;
FileInputStream fis = null;
public void bookmarksave(Context context,String FILENAME,String data){
try {
fos = context.openFileOutput(FILENAME, 0);
fos.write(data.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public String bookmarkload(Context context,String FILENAME){
String collected =null;
try{
fis =context.openFileInput(FILENAME);
byte[] dataArray = new byte[fis.available()];
while(fis.read(dataArray) != -1){
collected = new String(dataArray);
fis.close();
}
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return collected;
}
}
fos.write(System.getProperty("line.separator").getBytes());
Try this one... new data will be appended in new line..
change the Line fos = context.openFileOutput(FILENAME, 0); to
fos = context.openFileOutput(FILENAME, Context.MODE_APPEND);
This will open your file in append mode, instead of the default (override) mode.
You should also add a new line, otherwise you continue in the same line as before:
fos.write(System.getProperty("line.separator").getBytes());
You can use SharedPreferences to save your bookmark.It's very convenience.And if you want to use File to store them.You can use new FileOutputStream(filename,true) ,true means bytes will be written to the end of the file rather than the beginning.

Working with files: read and write many times

I am newbie in Android development and I cant know that is going with files.
That's about audio information.
So, if I create new file and write in it, after it i read from this file.
And new iteration: I don't create new file (cuz i already got this file), and write in this file. Now I gonna read from file (after second write) that I can get from file?
I need get second written information, can I get it on this way?
yes, you have read again the file
let say you use a textfile to save your data.
Ex.
this is how i save it
File temf=new File(getCacheDir()+"/data/mytext.txt");
Writer out=null;
if(temf.exists()){
temf.delete();
}
try {
out = new BufferedWriter(new FileWriter(temf));
out.write("sample text") + "\r\n");
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
and this is how i retrieve it
FileInputStream fs;
try {
File temf=new File(getCacheDir()+"/data/mytext.txt");
if (temf.exists()) {
fs = new FileInputStream(temf);
DataInputStream dis = new DataInputStream(fs);
BufferedReader br = new BufferedReader(new InputStreamReader(
dis));
String str=br.readLine();
while(str!=null)
{
if(str=="text you want to compare"){
break;
}else{
str=br.readLine();
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Save Internal File for Login

Hy!!
I have a login form in my app, but i want to save/restore the textfile internal in the app not on the internal phone memory.
Are there some code snippets?
I made a internal file saving/restoring but it don't work.
if (cb.isChecked())
{
File file = new File("/mmt/sdcard/login.skip");
Writer output = null;
try
{
output = new BufferedWriter(new FileWriter(file));
output.write(etuser.getText().toString()+ ";" + etpw.getText().toString());
output.close();
}
catch (Exception e) {
// TODO: handle exception
}
}
File file = new File("/mmt/sdcard/login.skip");
if(file.exists())
{ try
{
BufferedReader input = new BufferedReader(new FileReader(file));
while (( line = input.readLine()) != null){
line2 = line;
}
etuser.setText(line2.split(";")[0]);
etpw.setText(line2.split(";")[1]);
input.close();
}
catch (Exception e) {
// TODO: handle exception
}
}
Edit: See Internal Storage
Alternative,
Use SharedPreference It'll be Private to you're Application. And cannot be accessed otherwise. (For a non-rooted phone, atleast)

Categories

Resources