Working with ePub files in android - android

I referred this siegmann android tutorial
and successfully logged the Title, Author name and Table of contents.
Now I read that the whole book can be viewed in WebView.
But I don't find any tutorial for Dispalying an ePub file.
When it comes to creating an ePub file, I found this from SO
But I'm unable to implement it as I don't have any idea about main.xml.
Kindly suggest any tutorial to create and display an ePub file.
For creating ePub, I tried to refer this siegmann eg
but I'm not able to understand it properly.
Do I need to provide .html for each chapter and .css in order to create an ePub file?
I know I'm little unclear in this qustion as I'm absolute beginner when it comes to working with ePub, so any suggestions/help appreciated.

Try this in logTableOfContents()
while ((line = r.readLine()) != null) {
line1 = line1.concat(Html.fromHtml(line).toString());
}
finalstr = finalstr.concat("\n").concat(line1);

You can also spine the epub content with the help of
Spine spine = book.getSpine();
List<SpineReference> spineList = spine.getSpineReferences() ;
int count = spineList.size();
StringBuilder string = new StringBuilder();
for (int i = 0; count > i; i++) {
Resource res = spine.getResource(i);
try {
InputStream is = res.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
while ((line = reader.readLine()) != null) {
linez = string.append(line + "\n").toString();
System.err.println("res media"+res.getMediaType());
htmlTextStr = Html.fromHtml(linez).toString();
Log.e("Html content.",htmlTextStr);
speak(htmlTextStr);
}
} catch (IOException e) {e.printStackTrace();}
//do something with stream
} catch (IOException e) {
e.printStackTrace();
}
}
webview.getSettings().setAllowFileAccess(true);
webview.getSettings().setBuiltInZoomControls(true);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadDataWithBaseURL("file:///android_asset/", linez, "application/xhtml+xml", "UTF-8", null);

Related

Android, reading in multiline text file groups the text together, need assistance

I have a working filereader for a text file in my Raw Dir. The user should see the text file in the same format as I have formatted it in word but when the application is played, the text file is tightly grouped together with no paragraphs.
This is the file reader method below, as I said it does work but I just want the format to be as I have made it.
Your advice and guidance will be greatly appricated
#Override
protected void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_support);
InputStreamReader isr = new InputStreamReader(this.getResources().openRawResource(R.raw.supporttext));
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String s;
try{
while ((s = br.readLine()) != null){
sb.append(s);
}
}catch (IOException e) {
e.printStackTrace();
}
TextView tv = (TextView)findViewById(R.id.supporttxt);
tv.setText(sb.toString());
From BufferedReader#readline java doc :
A String containing the contents of the line, not including any line-termination characters
So using readline strips the line-termination characters, that's why you do not see them in your Text View. You can add them back like this :
try{
while ((s = br.readLine()) != null){
sb.append(s);
sb.append("\n");
}
}catch (IOException e) {
e.printStackTrace();
}
Also, you should probably use getText instead of openRawResource

Reading CSV file in resources folder android

I am developing an android app in netbeans. I am trying to read CSV file using opencsv. When I put the file in resources folder and try to read it from there, there's an error while building saying invalid resource directory. Where should I store csv file so that it can be read each time the app starts?
you should put csv file in assets folder ..
InputStreamReader is = new InputStreamReader(getAssets()
.open("filename.csv"));
BufferedReader reader = new BufferedReader(is);
reader.readLine();
String line;
while ((line = reader.readLine()) != null) {
}
Some advices;
Create an object for holding one row data into the csv. ( Ex: YourSimpleObject . It provides you to manage the data easily.)
Read file row by row and assign to object. Add the object to list. (Ex: ArrayList<YourSimpleObject >)
Code:
private void readAndInsert() throws UnsupportedEncodingException {
ArrayList<YourSimpleObject > objList= new ArrayList<YourSimpleObject >();
AssetManager assetManager = getAssets();
InputStream is = null;
try {
is = assetManager.open("questions/question_bank.csv");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String line = "";
StringTokenizer st = null;
try {
while ((line = reader.readLine()) != null) {
st = new StringTokenizer(line, ",");
YourSimpleObject obj= new YourSimpleObject ();
//your attributes
obj.setX(st.nextToken());
obj.setY(st.nextToken());
obj.setZ(st.nextToken());
obj.setW(st.nextToken());
objList.add(sQuestion);
}
} catch (IOException e) {
e.printStackTrace();
}
}
As an alternative, take a look at uniVocityParsers. It provides a vast number of ways to parse delimited files. The example bellow loads a Csv File (see in the picture below) from a res/raw folder into a InputStream object, and read it in a colunar manner (a map where key=Column & value=ColumnValues).
calendario_bolsa.csv
//Gets your csv file from res/raw dir and load into a InputStream.
InputStream csvInputStream = getResources().openRawResource(R.raw.calendario_bolsa);
//Instantiate a new ColumnProcessor
ColumnProcessor columnProcessor = new ColumnProcessor();
//Define a class that hold the file configuration
CsvParserSettings parserSettings = new CsvParserSettings();
parserSettings.getFormat().setLineSeparator("\n");
parserSettings.setHeaderExtractionEnabled(true);
parserSettings.setProcessor(columnProcessor);
//Creates a new CsvParser, passing the settings into its construtor:
CsvParser csvParser = new CsvParser(parserSettings);
//Calls parse method, instantiating an InputStreamReader, passing to its constructor the InputStream object
csvParser.parse(new InputStreamReader(csvInputStream));
//Gets the csv data as a Map of Column / column values.
Map<String, List<String>> columnarCsv = columnProcessor.getColumnValuesAsMapOfNames();
To add univocityParsers into your Android Project:
compile group: 'com.univocity', name: 'univocity-parsers', version: '2.3.0'
Using opencsv:
InputStream is = context.getAssets().open(path);
InputStreamReader reader = new InputStreamReader(is, Charset.forName("UTF-8"));
List<String[]> csv = new CSVReader(reader).readAll();
you may use this code
try {
InputStream csvStream = assetManager.open(CSV_PATH);
InputStreamReader csvStreamReader = new InputStreamReader(csvStream);
CSVReader csvReader = new CSVReader(csvStreamReader);
String[] line;
// throw away the header
csvReader.readNext();
while ((line = csvReader.readNext()) != null) {
questionList.add(line);
}
} catch (IOException e) {
e.printStackTrace();
}
you may download csvreader file from
http://sourceforge.net/projects/opencsv/files/latest/download
and import in your project

How to load a csv file into android for read/write

I am building an app which needs to read and edit items from a .csv file.
I can place the .csv in the assets folder but would rather the ability to search for it in the external storage as it will change regularly.
A friend has given me this code for placing it in the assets folder, but I am relatively new to android and this code doesn't make sense to me and I cant get it to work.
public ArrayList<String> Job = new ArrayList<String>();
try {
is = res.getAssets().open("Job.csv");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null)
Job.add(line);
} catch (IOException ex) {
// handle exception
} finally {
try {
is.close();
} catch (IOException e) {
// handle exception
}
}

Error fetching website source-code

I am trying to create a simple Android app that will have the possibility to fetch the source code of a website. Anyways, I have written the following:
WebView webView = (WebView) findViewById(R.id.webView);
try {
webView.setWebViewClient(new WebViewClient());
InputStream input = (InputStream) new URL(url.toString()).getContent();
webView.loadDataWithBaseURL("", "<html><body><p>"+input.toString()+"</p></body></html>", "text/html", Encoding.UTF_8.toString(),"");
setContentView(webView);
} catch (Exception e) {
Alert alert = new Alert(getApplicationContext(),
"Error fetching data", e.getMessage());
}
I've tried to change the 3rd line several times to other methods that will fetch the source code, but they all redirect me to the alert (error with no message, only the title).
What am I doing wrong?
Is there a particular reason why you can't just use this to load the webpage?
webView.loadUrl("www.example.com");
If you really want to grab the source code into a string so you can manipulate it and display it as you are trying to do, try opening a stream to the content and then using standard java methods to read in the data to a String, to which you can then do whatever you want:
InputStream is = new URL("www.example.com").openStream();
InputStreamReader is = new InputStreamReader(in);
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(is);
String read = br.readLine();
while(read != null) {
sb.append(read);
read = br.readLine();
}
String sourceCodeString = sb.toString();
webView.loadDataWithBaseURL("www.example.com/", "<html><body><p>"+sourceCodeString+"</p></body></html>", "text/html", Encoding.UTF_8.toString(),"about:blank");

Replacing a line of text in an android external text file

I just want to delete 2 lines of text from a text file that I created. Currently, this is what I'm trying to get rid of the 2 lines:
private void deleteDataFromFile(String title, String Date) {
try {
//open the file
FileInputStream myIn= openFileInput(FILENAME);
//the reader given the input file stream.
InputStreamReader inputReader = new InputStreamReader(myIn);
//Aftert he inputstream is open, need also a bufferedReader
BufferedReader BR = new BufferedReader(inputReader);
//holds a line of input
String line;
//used for only erasing one date.
int counter = 0;
while ((line = BR.readLine()) != null && counter < 1) {
if (line.equals(title)) {
line.replace(title, "" + "\n");
line = BR.readLine();
line.replace(Date, "" + "\n");
counter++;
}
}
BR.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I realize that since I'm using the replace function on a string it has no effect on the actual file itself, but I can not find any other function in the IO library to affect the text file. What I'm thinking about doing is creating a new file on the phone with the exact contents of this file and just deleting the 2 lines from it. That seems troublesome and inefficient though, and I'd like to avoid it. Any suggestions?

Categories

Resources