How to transfer a txt data file to my Android app - android

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.

Related

Problems reading .txt file in 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.

how do you read a file(media) on a users sdcard and display the media on your app (android) [duplicate]

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*/

Load a simple text file in Android Studio

Got a brand new project using Google's new Android Studio IDE.
I'm trying to load a simple text file using an InputStreamReader. I'm getting a file not found exception. Now there isn't any assets/ folder. I tried to create one and add my file at many different spots (at the root of the project, at the root of the .java file, etc...) I've tried to move the file around but still get the file not found.
Now that never was a problem using Eclipse as there is an assets folder created by any template.
Does anyone know where should the assets go to or how to load them?
Here is the code used, it fails at .open():
InputStream iS = resources.getAssets().open("bla.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(iS));
I also tried this code in Eclipse, it works and the file contents get loaded. So there's probably a step needed in Android Studio.
Step 1:
Open in Name_Project-Name_Project.iml file.
See the line :
option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets"
Step 2:
Create a sub-folder "assets" in main folder.
Step 3:
Put file in this folder.
Step 4:
Load it. Done.
The correct answer didn't work for me exactly.
This works:
Go to Project view and then go to app/src/main and create new directory assets
to load the file:
InputStream is = getApplicationContext().getAssets().open("bla.txt");
or:
InputStream is = context.getAssets().open("bla.txt");
and then convert it to string at any way you want, examples here
detailed video of how to do it (not mine)
This code will work for you.It will fetch all data from file.
public class Quiz extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
try {
PlayWithRawFiles();
} catch (IOException e) {
Toast.makeText(getApplicationContext(),
"Problems: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}// onCreate
public void PlayWithRawFiles() throws IOException {
String str="";
StringBuffer buf = new StringBuffer();
InputStream is = this.getResources().openRawResource(R.raw.ashraf);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
if (is!=null) {
while ((str = reader.readLine()) != null) {
buf.append(str + "\n" );
}
}
is.close();
TextView tv=(TextView)findViewById(R.id.tv1);
tv.setText(buf.toString());
}//
}
//Compiled all the codes available in the internet, and this works perfectly fine for reading data from a textfile
//Compiled By: JimHanarose
ArrayList<String> data_base = new ArrayList<String>();
String text = "";
try {
InputStream is = getApplicationContext().getAssets().open("g.txt"); //save this .txt under src/main/assets/g.txt
int size = is.available();
StringBuffer buf = new StringBuffer();
byte [] buffer = new byte[size];
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
if (is!=null) {
while ((text = reader.readLine()) != null) {
data_base.add(text.toString()); //create your own arraylist variable to hold each line being read from g.txt
}
}
is.close();
} catch (IOException e) {
e.printStackTrace();
}

android text file import where do i save text file what folder?

So this is a pretty embarrassing question, but i have a text file and java will read all of the words in it and add it to a array, i don't know where to put the text file, like what folder so the comp can go get it? could someone tell me. my code works in a regular java application, so it should work on android.
you can use
<your-context>.getAssets();
to return an AssetsManager object.
AssetsManager assets = context.getAssets();
You can then open an input stream with the open() method.
InputStream inputStream = assets.open("filename");
The InputStream object is a standard Java object from the IO package. You can decorate this stream with an object decorator you wish (Reader, BufferedReader, etc).
If you wish to move this file out of the APK (that is not inflated) to the phone you can just copy the bytes of the file from the input stream using an output stream. Note you will have to have permissions in your write directory (you can do this if your phone is rooted and you have created a shell interface to run native shell commands through JNI).
UPDATE
try {
InputStream inputStream = this.getAssets().open("test.txt");
BufferedReader buffer = new BufferedReader(new Reader(inputStream));
String line;
while((line = buffer.readLine()) != null) {
tots.add(line);
}
}
catch(IOException e) {
e.printStackTrace();
}
Haven't tested it, but I think this is what you want.
You can put the file to assets folder and use
InputStream stream = getAssets().open(filename);
to get the input stream
I created new raw folder in res folder and put chapter0.txt in here.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.induction);
wordss = new Vector<String>();
TextViewEx helloTxt = (TextViewEx) findViewById(R.id.test);
helloTxt.setText(readTxt());
}
private String readTxt() {
InputStream inputStream = getResources().openRawResource(R.raw.chapter0);
// getResources().openRawResource(R.raw.internals);
System.out.println(inputStream);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1) {
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}

reading a specific file from sdcard in android

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*/

Categories

Resources