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.
Related
I have created an ArrayList. I read text file from Android phone and store String[3] in each array. I used the debugger to trace the value of each variable. The value in ArrayList seem like always follow the value of buffer. Is it any link between them?
ArrayList<String[]> label_list = new ArrayList<>();
try {
FileInputStream fIn = new FileInputStream(getPath());
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
String aDataRow = "";
String[] buffer = new String[3];
int j=0;
while ((aDataRow = myReader.readLine()) != null) {
if(!aDataRow.equals("")){
buffer[j]=aDataRow;
j++;
}else{
label_list.add(buffer);
j=0;
}
}
label_list.add(buffer); //for last one
myReader.close();
for(int i=0;i<label_list.size();i++){
txt_show.append(label_list.get(i)[0]);
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
The text file i read.
The result of debugger. As you can see, all arrays have same value. The value in Arraylist will always follow the value of buffer.
You must put that j++ out of if else condition.
ArrayList<String[]> label_list = new ArrayList<>();
try {
FileInputStream fIn = new FileInputStream(getPath());
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
String aDataRow = "";
String[] buffer = new String[3];
int j=0;
while ((aDataRow = myReader.readLine()) != null) {
if(!aDataRow.equals("")){
buffer[j]=aDataRow;
}else{
label_list.add(buffer);
}
j++;
}
label_list.add(buffer); //for last one
myReader.close();
for(int i=0;i<label_list.size();i++){
txt_show.append(label_list.get(i)[0]);
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
hope it helps
I found my mistake. Add buffer = new String[3]; will solve my problem but I do not know why. Can anyone explain to me?
try {
FileInputStream fIn = new FileInputStream(getPath());
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
String aDataRow = "";
String[] buffer = new String[3];
int j=0;
while ((aDataRow = myReader.readLine()) != null) {
if(!aDataRow.equals("")){
buffer[j]=aDataRow;
j++;
}else{
label_list.add(buffer);
j=0;
**buffer = new String[3];**
}
}
myReader.close();
for(int i=0;i<label_list.size();i++){
txt_show.append(label_list.get(i)[0]);
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
I'm trying to parse some XML to a string and I'm getting an outofbounds exception. I'm fairly new to android as well as trying to get text from a website, namely the CTA Bus Tracker API . One block of the XML looks like this:
<route>
<rt>1</rt>
<rtnm>Bronzeville/Union Station</rtnm>
</route>
This is my method:
class loadRoutes extends AsyncTask<String, String, String[]> {
#Override
protected String[] doInBackground(String... strings) {
try {
URL routesURL = new URL(strings[0]);
BufferedReader in = new BufferedReader(new InputStreamReader(routesURL.openStream()));
String [] result = new String[2];
String line;
while((line = in.readLine()) != null) {
if(line.contains("<rt>")) {
int firstPos = line.indexOf("<rt>");
String tempNum = line.substring(firstPos);
tempNum = tempNum.replace("<rt>", "");
int lastPos = tempNum.indexOf("</rt>");
result[0] = tempNum.substring(0, lastPos);
in.readLine();
firstPos = line.indexOf("<rtnm>");
String tempName = line.substring(firstPos);
tempName = tempName.replace("<rtnm>", "");
lastPos = tempName.indexOf("</rtnm>");
result[1] = tempName.substring(0, lastPos);
}
}
in.close();
return result;
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
The first readline() gets to the line with an rt and grabs that line, then in the if statement, readline() should get the next line, which should contain rtnm. I keep getting indexoutofbounds on the line firstPos = line.indexOf("rtnm").
The while loop is already reading in the next line, so you don't need to in.readLine(); in the if statement. Try running it like this:
while((line = in.readLine()) != null) {
if(line.contains("<rt>")) {
int firstPos = line.indexOf("<rt>");
String tempNum = line.substring(firstPos);
tempNum = tempNum.replace("<rt>", "");
int lastPos = tempNum.indexOf("</rt>");
result[0] = tempNum.substring(0, lastPos);
} else if (line.contains("<rtnm>") {
firstPos = line.indexOf("<rtnm>");
String tempName = line.substring(firstPos);
tempName = tempName.replace("<rtnm>", "");
lastPos = tempName.indexOf("</rtnm>");
result[1] = tempName.substring(0, lastPos);
}
}
Also, it might be easier to write your own XML parser in a different class. This XML parser android documentation has an example of exactly what you are trying to do.
How can I ping some web server in Android to test if I've Internet connection?
So I need the method which pings the given site and returns false if I've no Internet and true if I have.
See this method, it's the best way to check for connectivity to a given server:
http://developer.android.com/reference/java/net/InetAddress.html#isReachable(int)
Use these methods to ping the server
public static void inSomeWhere()
{
String pingResult = getPingResult("168.126.63.1");
boolean isNetOk = true;
if (pingResult == null) {
// not reachable!!!!!
isNetOk = false;
}
}
public static String getPingResult(String a) {
String str = "";
String result = "";
BufferedReader reader = null;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
try {
Runtime r = Runtime.getRuntime();
Process process = r.exec("/system/bin/ping -c 3 " + a);
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
int i;
while ((i = reader.read(buffer)) > 0)
output.append(buffer, 0, i);
str = output.toString();
final String[] b = str.split("---");
final String[] c = b[2].split("rtt");
if (b.length == 0 || c.length == 0)
return null;
if(b.length == 1 || c.length == 1)
return null;
result = b[1].substring(1, b[1].length()) + c[0] + c[1].substring(1, c[1].length());
} catch (IOException e) {
return null;
} catch (Exception e) {
return null;
}
finally
{
if(reader != null)
{
try{reader.close();}catch(IOException ie){}
}
}
return result;
}
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;
}
I am having an issue while parsing a CSV file. It is only 2 rows of data with a comma separating them. Row one is a date and row 2 is a value. The date field will always have dates in it but sometimes the value is blank (or null?). When it gets to the null value I get a StringIndexOutOfBoundsException and the app crashes. I am logging each loop and can see the data but as soon as I get to a null value it stops looping and gives the error. If there are no null values then it works perfect. Here is my code:
BufferedReader buf = new BufferedReader(new StringReader(file));
String line = null;
while ((line = buf.readLine()) != null) {
try {
String date = null, value = null;
String[] RowData = line.split(",");
date = RowData[0];
value = RowData[1]; (this is the row it crashes on)
This is what the CSV looks like:
2011-08-28 09:16,8.23
2011-08-28 09:15,8.24
2011-08-28 09:14,8.26
2011-08-28 09:13,8.34
2011-08-28 09:12,
2011-08-28 09:11,10.72
2011-08-28 09:10,
2011-08-28 09:09,
the value at 09:13 is the last thing in logcat before I get the error.
This fixed it:
if(RowData.length == 2) {
date = RowData[0];
value = RowData[1];
} else {
date = RowData[0];
value = "0";
}
I wrote a 0 in the value field so later processes will not choke on the null value. Thanks for all your help guys!
You want to do this or something like it:
String date = null, value = null;
String[] RowData = line.split(",");
date = RowData[0];
if(RowData.length ==2)value = RowData[1]; (this is the row it crashes on)
Or some variation of it e.g. if(RowData.length < 2) dont attempt to read the value. Its a pretty standard thing - if you ask an array for an index of a value it doesn't have Java will crash.
Why write your own CSV parsing when you could use a library that has already been written which will do it for you? Perhaps OpenCSV would help you achieve your CSV parsing goal.
Check the length of RowData before you try to access it. It looks like split() is returning an array with a single object but you're trying to access the second object, which is indeed out of bounds.
public class CityParser {
DocumentBuilderFactory factory;
DocumentBuilder builder;
Document doc;
Element ele;
int mediaThumbnailCount;`enter code here`
boolean urlflag;
CityListBean objBean = null;
Vector<CityListBean> vecCityList;
public CityParser() {
}
public Vector<CityListBean> getCityData() {
vecCityList = new Vector<CityListBean>();
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(
"http://heresmyparty.com/cms/index.php?option=com_chronocontact&chronoformname=add_event_form_download");
HttpResponse response = httpClient.execute(httpGet, localContext);
// String result = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
CSVReader csvreader = new CSVReader(reader);
String[] nextLine;
while ((nextLine = csvreader.readNext()) != null) {
CityListBean objcitylist = new CityListBean();
// nextLine[] is an array of values from the line
objcitylist.setText_title(nextLine[5]);
objcitylist.setText_host(nextLine[6]);
objcitylist.setText_price(nextLine[7]);
objcitylist.setDate(nextLine[8]);
objcitylist.setText_venue(nextLine[11]);
objcitylist.setAddress(nextLine[12]);
objcitylist.setLatitude(nextLine[13]);
objcitylist.setLongitude(nextLine[14]);
objcitylist.setFile(nextLine[15]);
objcitylist.setText_description(nextLine[16]);
objcitylist.setCity(nextLine[17]);
vecCityList.addElement(objcitylist);
}
/*for (int i = 0; i < vecCityList.size(); i++) { CityListBean
objcity = (CityListBean) vecCityList.get(i);
System.out.println("Cf_id : " + objcity.getCityName());
System.out.println("-----------------------------------"); }*/
} catch (Exception ex) {
ex.printStackTrace();
}
return vecCityList;
}
}
==========================================================================================
public class CSVReader {
private BufferedReader br;
private boolean hasNext = true;
private char separator;
private char quotechar;
private int skipLines;
private boolean linesSkiped;
public static final char DEFAULT_SEPARATOR = ',';
public static final char DEFAULT_QUOTE_CHARACTER = '"';
public static final int DEFAULT_SKIP_LINES = 0;
public CSVReader(Reader reader) {
this(reader, DEFAULT_SEPARATOR, DEFAULT_QUOTE_CHARACTER,
DEFAULT_SKIP_LINES);
}
public CSVReader(Reader reader, char separator, char quotechar, int line) {
this.br = new BufferedReader(reader);
this.separator = separator;
this.quotechar = quotechar;
this.skipLines = line;
}
public String[] readNext() throws IOException {
String nextLine = getNextLine();
return hasNext ? parseLine(nextLine) : null;
}
private String getNextLine() throws IOException {
if (!this.linesSkiped) {
for (int i = 0; i < skipLines; i++) {
br.readLine();
}
this.linesSkiped = true;
}
String nextLine = br.readLine();
if (nextLine == null) {
hasNext = false;
}
return hasNext ? nextLine : null;
}
private String[] parseLine(String nextLine) throws IOException {
if (nextLine == null) {
return null;
}
List<String> tokensOnThisLine = new ArrayList<String>();
StringBuffer sb = new StringBuffer();
boolean inQuotes = false;
do {
if (inQuotes) {
// continuing a quoted section, reappend newline
sb.append("\n");
nextLine = getNextLine();
if (nextLine == null)
break;
}
for (int i = 0; i < nextLine.length(); i++) {
char c = nextLine.charAt(i);
if (c == quotechar) {
// this gets complex... the quote may end a quoted block, or escape another quote.
// do a 1-char lookahead:
if( inQuotes // we are in quotes, therefore there can be escaped quotes in here.
&& nextLine.length() > (i+1) // there is indeed another character to check.
&& nextLine.charAt(i+1) == quotechar ){ // ..and that char. is a quote also.
// we have two quote chars in a row == one quote char, so consume them both and
// put one on the token. we do *not* exit the quoted text.
sb.append(nextLine.charAt(i+1));
i++;
}else{
inQuotes = !inQuotes;
// the tricky case of an embedded quote in the middle: a,bc"d"ef,g
if(i>2 //not on the begining of the line
&& nextLine.charAt(i-1) != this.separator //not at the begining of an escape sequence
&& nextLine.length()>(i+1) &&
nextLine.charAt(i+1) != this.separator //not at the end of an escape sequence
){
sb.append(c);
}
}
} else if (c == separator && !inQuotes) {
tokensOnThisLine.add(sb.toString());
sb = new StringBuffer(); // start work on next token
} else {
sb.append(c);
}
}
} while (inQuotes);
tokensOnThisLine.add(sb.toString());
return (String[]) tokensOnThisLine.toArray(new String[0]);
}
public void close() throws IOException{
br.close();
}
}
Have you tried to check first
if (RowData[1]!=null) or possibly if (RowData[1]!="")
I don't see why that would cause your app to crash though,
it should just set value to null or ""