Android: display sentence from text file stored in res/raw folder - android

I am new to android and i Struck at this point.My text file contains wordings with number like
1abcd efg hij klmn opqrs.
2hdgh eydg ieuyhd gdhdgl.
3hdgf dhgfhs fhghs dhghj. and so on.
Now i need to display full sentence start with 1. please help me out from this problem.

You can save your text file in "Assets" folder of project and use following code to retrieve that file in java class
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("YOUR_TEXT_FILE.txt")));
StringBuilder total = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
total.append(line);
}
message=total.toString();
System.out.println(message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
After that you have that file in String message and you can retrieve string starting from "1" from that.
EDIT
TO RETRIEVE STRING STARTING WITH 1
use can use following code-
String newString;
for (int i = 0; i < message.length(); i++){
char c = message.charAt(i);
if(c=='1'){
for (int j = i; j < message.length(); j++){
if(c=='2'){
break;
}
else{
newString += message.charAt(j);
}
}
break;
}
}
Now String newString will contain String starting with '1'.
Good Luck

Related

How to Read from text file and Store into an Array in android

Hie Friends
I am developing an android application in that text file should be generated with some numbers. and after this one by one application should call to that numbers.
For eg:
9876452125,
9876452135,
9876452115,
Mostly that text file have 8 numbers which is Separated by "," and New Line "\n"
Now I want to read From that file line by line.
My Code for read file and store to array is:
public void read(String fname)
{
BufferedReader br = null;
try
{
StringBuffer output = new StringBuffer();
String fpath = "/sdcard/" + fname + ".txt";
br = new BufferedReader(new FileReader(fpath));
String line = null;
int index = 0;
String[][] num = new String[15][10];
List<String[]> collection = new ArrayList<String[]>();
while ((line = br.readLine()) != null)
{
if (index < num.length)
{
output.append(line);
// output.append("\n");
num[index] = line.split(",");
if (num.length > 0)
{
collection.add(num[index]);
}
}
Toast.makeText(getApplicationContext(), "" + collection, 5000)
.show();
index++;
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
Now My problem is when I printing collection to Toast it display some random strings. I don't know why??
Does any one have proper idea or sample code for how to read from file line by line and store to Array.
Thanks allot.
If I was you I'd use a scanner. You haven't given information on how you plan to store them: for example, why you use String[][] num = new String[15][10];, but I'll give you an example of if you wanted to store each number in it's own element, and you can adjust if necessary (I am assuming there is only one newline at the end of every line in your file).
public void read(String fname) {
String fpath = "/sdcard/" + fname + ".txt";
File file = new File(fpath);
Scanner scanner = new Scanner(new FileInputStream(file));
List<String[]> collection = new ArrayList<String[]>();
while (scanner.hasNextLine()){
String line = scanner.nextLine();
String.replaceAll("\n", ""); // strip the newline
String[] myList = myString.split(",");
for (i=0; i < myList.length; i++) {
collection.add(myList[i]);
}
}
scanner.close();
}
This doesn't have any android elements in it, but like I said you can adjust as necessary to do what you specifically need it to do.
ArrayList<ArrayList<String>> myArray = new ArrayList<ArrayList<String>>();
ArrayList<String> stringArray = new ArrayList<String>();
String random = "9876452125, 9876452135, 9876452115,";
String[] splitArray = random.split(",");
for (int i = 0; i < splitArray.length; i++) {
stringArray.add(splitArray[i]);
}
myArray.add(stringArray);
// printing all values
for (int i = 0; i < myArray.size(); i++) {
for (int j = 0; j < myArray.get(i).size(); j++) {
System.out.println("values of index " + i + " are :"
+ myArray.get(i).get(j));
}
}

Android Reading Assets depending on selected Activity

I'm developing an app which consists on different tests and for each test (activity) it is needes to read a different txt file. I know doing this but changing it manually. How could be possible to read the proper txt when an specific activity is running. For example for activity 1 I need to read 1.txt and so on.
Here is the code where i read the txts.
String questionFile = "";
questionFile = "1.txt";
questionCount = 20;
Log.i("Question", questionFile + ": " + questionCount);
try {
InputStream is = context.getAssets().open(questionFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
// Skips lines
for (i = 0; i< questionNumber; i++) {
reader.readLine();
}
question = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
you will need to put current code inside separate class and create a method for reading file from Assets depend on Activity currently running as:
public class GetFileAssets {
Context context;
public GetFileAssets(Context context){
this.context=context;
}
public String readFilefromAssets(String str_file_id){
String questionFile = "";
questionFile = str_file_id;
questionCount = 20;
//... your code here
return question;
}
}
and now pass file accoding to Activity .like from Actiivty 1:
GetFileAssets obj=new GetFileAssets(Activity1.this);
String str=obj.readFilefromAssets("1.txt");
same from Activity 2 :
GetFileAssets obj=new GetFileAssets(Activity2.this);
String str=obj.readFilefromAssets("2.txt");

How to read whole chapter from epub files?

I want to make epub reader app.Now i am getting only chapter name in the file but how to get whole data in the chapter.
I think I have already posted this out before.
Using nl.siegmann.epublib which you can google.
In my code I will show you how I did it as you look at Book class which shows how the the epub works.
Using Spine on book class I get the maximum spine of the book which means the entire book.
I then convert it to string.
Here is my code on how I did it.
public String getEntireBook()
{
String line, linez = null;
Spine spine = amBook().getSpine();
Resource res;
List<SpineReference> spineList = spine.getSpineReferences() ;
int count = spineList.size();
int start = 0;
StringBuilder string = new StringBuilder();
for (int i = start; count > i; i = i +1) {
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();
}
} catch (IOException e) {e.printStackTrace();}
} catch (IOException e) {
e.printStackTrace();
}
}
return linez;
}

How to read EPUB book using EPUBLIB?

I found a solution for reading epub books in android using epublib. I am able to read the subtitles of the book. But I didn't find a way to read the line by line of the content. How can I acheive this?
Sample code for getting titles of the book is
private void logTableOfContents(List<TOCReference> tocReferences, int depth) {
if (tocReferences == null) {
return;
}
for (TOCReference tocReference : tocReferences) {
StringBuilder tocString = new StringBuilder();
StringBuilder tocHref=new StringBuilder();
for (int i = 0; i < depth; i++) {
tocString.append("\t");
tocHref.append("\t");
}
tocString.append(tocReference.getTitle());
tocHref.append(tocReference.getCompleteHref());
Log.e("Sub Titles", tocString.toString());
Log.e("Complete href",tocHref.toString());
//logTableOfContents(tocReference.getChildren(), depth + 1);
}
}
Got this code from http://www.siegmann.nl/epublib/android
How can I get the story of the book...
I'm not sure is that is the way to navigate in epub file. As far as I know (till now - I'm still learning), better way to get all book cocntent is based on spine section.
But still - I don't know how to connect this two things (TOC and real spine) with epublib interface.
According to documentation:
"The spine sections are the sections of the book in the order in which the book should be read. This contrasts with the Table of Contents sections which is an index into the Book's sections."
that is something - if You likie - this is a snippet:
Spine spine = new Spine(book.getTableOfContents());
for (SpineReference bookSection : spine.getSpineReferences()) {
Resource res = bookSection.getResource();
try {
InputStream is = res.getInputStream();
//do something with stream
} catch (IOException e) {
Well - i'm not exacly sure about navigating, but also wonder how to do it
For now - i have something like this (it is line - by line read):
private void logTableOfContents(List<TOCReference> tocReferences, int depth) {
if (tocReferences == null) {
return;
}
for (TOCReference tocReference : tocReferences) {
StringBuilder tocString = new StringBuilder();
for (int i = 0; i < depth; i++) {
tocString.append("\t");
}
try{
InputStream is = tocReference.getResource().getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = r.readLine()) != null) {
String line = Html.fromHtml(line).toString();
}
}
catch(IOException e){
}
//logTableOfContents(tocReference.getChildren(), depth + 1);
}
}

Fail to split downloaded txt file

I have a String that I try to split. The following code works
lsSagor = "some text\n Some more text\n More text~Text again\n Text\n text~Some text ..."
final String[] laList = lsSagor.split("~");
String[] laSaga = laList[0].split("\n");
Gives:
laSaga[0] => some text
laSaga[1] => some more text
laSaga[2] => More text
But if I download the textfile, it fails to split and gives:
laSaga[0] => "some text\n Some more text\n More text"
So it seems the first split works, but not the second.
Here is the code I use to download the file
String lsSagor = getFileFromUrl(BASEURL+"/sagor.txt");
public static String getFileFromUrl(String url)
{
InputStream content = null;
try
{
HttpGet httpGet = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
// Execute HTTP Get Request
HttpResponse response = httpclient.execute(httpGet);
content = response.getEntity().getContent();
}
catch (Exception e)
{
//handle the exception !
}
BufferedReader rd = new BufferedReader(new InputStreamReader(content), 4096);
String line;
StringBuilder sb = new StringBuilder();
try {
while ((line = rd.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
rd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
From the documentation
I don't think you will find your string contains any newline character to split on, you would need to do
while ((line = rd.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
to get that and I'm sure there is an easier way to just read it newlines and all in the first place.
Hi I think the problem is in String.split() function
Old method but work :)
public static String[] splitString(String str, char separator)
{
String[] retVal = null;
int length = str.length();
int size = 1;
int jIndx = 0;
int expressionLength = 0;
while ((jIndx = str.indexOf(separator, jIndx + 1)) != -1)
{
size++;
}
retVal = new String[size];
jIndx = 0;
char[] charArray = str.toCharArray() ;
for (int index = 0; index < length; index++)
{
if (charArray[index] == separator)
{
retVal[jIndx] = str.substring(index - expressionLength, index);
jIndx++;
expressionLength = 0;
}
else
expressionLength++;
if (index + 1 == length)
{
retVal[jIndx] = str.substring(index + 1 - expressionLength, index + 1);
}
}
return retVal;
}
This is the (not so beautiful) solution
lsSagor = "some text# Some more text# More text~Text again\n Text# text~Some text ..."
String lsSagor = getFileFromUrl(BASEURL+"/sagor.txt");
final String[] laList = lsSagor.split("~");
giAntalSagor = laList.length;
String[] laSaga = laList[0].split("#");
final String[] guiLaList = new String[giAntalSagor];
for (int i = 0; i < giAntalSagor; i++)
{
guiLaList[i] = laList[i].replaceAll("#", "\n");
}
guiLaList is used for layout with "\n" and the other list laList to get the information I wanted.

Categories

Resources