I am a fresher in Android, I just tried to read an excel file, but have some troubles reading the Excel file in assets,
it returns the log:
I/System.out: ************** I/System.out:
file:/android_asset/data.xls
**************
[File not found..!]
here is my code:
MainActivity.java
public List<String> read(String key) throws IOException {
List<String> resultSet = new ArrayList<String>();
File inputWorkbook = new File("file:///android_asset/data.xls");
System.out.println("**************");
System.out.println(inputWorkbook);
System.out.println("**************");
if(inputWorkbook.exists()){
Workbook w;
try {
w = Workbook.getWorkbook(inputWorkbook);
// Get the first sheet
Sheet sheet = w.getSheet(0);
// Loop over column and lines
for (int j = 0; j < sheet.getRows(); j++) {
Cell cell = sheet.getCell(0, j);
if(cell.getContents().equalsIgnoreCase(key)){
for (int i = 0; i < sheet.getColumns(); i++) {
Cell cel = sheet.getCell(i, j);
resultSet.add(cel.getContents());
}
}
continue;
}
} catch (BiffException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
else
{
resultSet.add("File not found..!");
}
if(resultSet.size()==0){
resultSet.add("Data not found..!");
}
return resultSet;
}
Here is the structure of my project:
Could anyone help me figure out what's the problem?
You can add asset folder by
Go to Files.
Step 2 : Go to Folders.
Step 3 : Create Assets Folder.
if you have added an asset folder properly than you put your Xls files in it. If it is done properly then you can get the file as an input stream from asset folder like this as below,
AssetManager assetManager = getAssets();
// open excel sheet
InputStream inputStream = assetManager.open("data.xls");
than this inputStream can help you ahead to solve your purpose
You can add the assets inside the raw folder of your project.
Below would be project structure once you change it.
This line of code can be used to get the handler towards it
try {
InputStream im =
getApplicationContext().getResources().openRawResource(R.raw.savings);
} catch (Exception e) {
Log.e("ERROR", e.getMessage());
}
Related
I need some help in writing to an existing json file. I can parse the data and read from it using GSON or just json in this example. I did it this way to filter the results by id displayed on screen. So it grabs the add and searches my list of over 900 videos and then gives the ones selected. Only issue is i don't want to display them i want to save them :)
final Button button = findViewById(R.id.buttonx);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// load json parse json and grab fields...
// then write to new file!
try {
//Load File
BufferedReader jsonReader = new BufferedReader(new InputStreamReader(getResources().openRawResource(R.raw.movielist)));
StringBuilder jsonBuilder = new StringBuilder();
for (String line = null; (line = jsonReader.readLine()) != null;) {
jsonBuilder.append(line).append("\n");
}
//Parse Json
JSONTokener tokener = new JSONTokener(jsonBuilder.toString());
JSONArray jsonArray = new JSONArray(tokener);
ArrayList<String> fields = new ArrayList<String>();
for (int index = 0; index < jsonArray.length(); index++) {
//Set both values into the listview
JSONObject jsonObject = jsonArray.getJSONObject(index);
String series = jsonObject.getString("id");
if (series.equals(tvId.getText())) {
fields.add(jsonObject.getString("movie"));
fields.add(jsonObject.getString("year"));
fields.add(jsonObject.getString("duration"));
fields.add(jsonObject.getString("director"));
fields.add(jsonObject.getString("image"));
fields.add(jsonObject.getString("id"));
}
}
} catch (FileNotFoundException e) {
Log.e("jsonFile", "file not found");
} catch (IOException e) {
Log.e("jsonFile", "ioerror");
} catch (JSONException e) {
Log.e("jsonFile", "error while parsing json");
}
Toast.makeText(DetailActivity.this, "The following movie has been saved " + tvId.getText(), Toast.LENGTH_LONG).show();
// Toast.makeText(DetailActivity.this, "This features is not working", Toast.LENGTH_LONG).show();
}
});
My issue is once I get the data I want to be able to write this to an existing JSON file. my api is 18 so can't use FILEwriter i am trying to make the app available to pretty much everyone. A point in the right direction would be great.
If you want to write to a file packaged in the raw folder, you will have to copy it to the local file system first. Resources contained in your raw directory in your project will be packaged inside your APK and will not be writeable at runtime. Consider looking at the Internal or External Data Storage APIs.
Update raw resources is not possible
Assets
|-man
| |-myhtml.html
|
|-women
| |-myhtml.html
this is my folder structure some times i need to check the file exist in men some times i need to check the file exist in women what can i do.
try {
fileExist = Arrays.asList(getResources().getAssets().list("")).contains(pathInAssets);
} catch (FileNotFoundException e) {
fileExist = false;
} catch (IOException e) {
e.printStackTrace();
}
this give only the list man and women i cant go inside it and check the existance.
Is their any other way to check this
use below method to get file from assets folder.
i provide code get all .mp4 file and store file into string list.
private List<String> videoList=new ArrayList<>();
private boolean listAssetFiles(String path) {
String [] list;
try {
list = getAssets().list(path);
if (list.length > 0) {
// This is a folder
for (String file : list) {
if (!listAssetFiles(path + "/" + file))
return false;
else {
// This is a file
// TODO: add file name to an array list
if (file.contains(".mp4") || file.contains(".mp3") ) {
videoList.add(file);
}
}
}
}
} catch (IOException e) {
return false;
}
return true;
}
when you call this method pass only ..
listAssetFiles(""); // you can pass your path if is empty then it scan root.
Just open an input stream for the file. As if you were going to read the file.
If you manage to open it the file does exist. Otherwise you get an exception.
Hello,
I am trying to read a file with a Scanner so I can use the input of the strings to construct other objects. However my scanner is always throwing a NullPointerException when trying to create it. I have a pig.txt text file in the res/raw folder but my scanner can not seem to access it. I do not know what I am doing wrong. I have comment out other code of the method but still get an exception.
public void loadAchievements() {
try {
Scanner s = new Scanner(getResources().openRawResource(R.raw.pig));
/**
* s = s.useDelimiter("."); Scanner StringScanner; StringScanner =
* new Scanner(s.next()); StringScanner =
* StringScanner.useDelimiter(":"); String keep =
* StringScanner.next(); String StringKeeper = StringScanner.next();
* this.achievementBoard.add(new Achievement_Item(keep,
* StringKeeper)); StringScanner.close(); s.close();
**/
} catch (NullPointerException e) {
e.printStackTrace();
System.out.println("NULLPOINTER");
}
}
I had this problem today, and I resolved somehow.
I know that old question, but I would share it if others have stuck.
public class Question {
private int numberOfQuestion;
private String[] myquestion;
public Question(InputStream file_name) {
Scanner scanner = null;
try {
scanner = new Scanner(file_name);
} catch (Exception e) {
Log.d("Question", "Scanner :" + e);
System.exit(1);
}
this.numberOfQuestion = scanner.nextInt();
scanner.nextLine();
myquestion = new String[numberOfQuestion];
for (int i = 0; i < numberOfQuestion; ++i) {
myquestion[i] = scanner.nextLine();
}
scanner.close();
}
---------------------------------------------------------
call:
try {
MyScanner myScanner = new MyScanner(getResources().openRawResource( R.raw.input_question));
} catch (Exception e) {
Log.d("Error", "input_question.txt");
}
openRawResource() method can only be used to open drawable, sound, and raw resources; it will fail on string and color resources. Since your pig.txt is a text file that contains a String, openRawResource() won't be able to open a new stream therefore your stream is null.
I'm trying to read excel contents in android, but always get file not found exception
The project is in:
C:\AndroidWorkSpace\AntenaProject
And the code is:
public void TestClick(View view)
{
File inputWorkbook = new File("shidur.xls");
Workbook w;
StringBuilder sb = new StringBuilder("starting");
try {
w = Workbook.getWorkbook(inputWorkbook);
// Get the first sheet
Sheet sheet = w.getSheet(0);
// Loop over first 10 column and lines
for (int j = 0; j < sheet.getColumns(); j++) {
for (int i = 0; i < sheet.getRows(); i++) {
Cell cell = sheet.getCell(j, i);
//CellType type = cell.getType();
sb.append(cell.getContents());
}
}
} catch (Exception e) {
e.printStackTrace();
}
TextView tv = (TextView)findViewById(R.id.testText);
tv.setText(sb.toString());
}
i tried to put shidur.xls in the following folders:
C:\AndroidWorkSpace\AntenaProject\res\raw
C:\AndroidWorkSpace\AntenaProject\res
but still getting this exception.
i'm using jxl.jar from http://jexcelapi.sourceforge.net/
thanks for the help
The path that you provide to the File constructor needs to be the absolute path of the file, or you need to use the overload that takes another File object as the first parameter which represents the directory the file lives in.
That being said, constructing a file in this way is for files that are either in local storage (ie. phone's main memory) or external storage (ie. SD card).
To open a file from the res/raw directory, get an InputStream in the following way
InputStream in = getResources().openRawResource(R.raw.file_name);
Then, you will need code that reads the contents of your input stream. I use a static helper method that looks like this, but this could run you into problems if the file is huge. Hasn't happened to me yet, but in principle that's always a risk when loading the entire content of a file into memory
public static String readStream(InputStream in)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch(Exception ex) { }
finally
{
// NOTE: you don't have my IOUtils class,
// but all these methods do is check for null and catch the exceptions that Closeable.close() can throw
IOUtils.safeClose(in);
IOUtils.safeClose(reader);
}
return sb.toString();
}
You should use the following code to open file in the /res/raw
getResources().openRawResource(R.raw.shidur.xls)
I have a CSV file in drawable/asset folder. In the CSV file there are four columns. First one is for date and rest three are for integer data.
I need to parse this CSV file and save the data in separate arrays.
I have searched for a solution, but I don't get proper idea on how to do this.
I like this csv reader: https://mvnrepository.com/artifact/net.sf.opencsv/opencsv/2.3
Just add it to your project.
Example code (assuming there is the file assets/test.csv):
String next[] = {};
List<String[]> list = new ArrayList<String[]>();
try {
CSVReader reader = new CSVReader(new InputStreamReader(getAssets().open("test.csv")));
while(true) {
next = reader.readNext();
if(next != null) {
list.add(next);
} else {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
You can access the imported data with, for example,
list.get(1)[1]
That would return a string.