Parsing SHOUTcast 7.html metadata on Android - android

I am trying to check the status of a SHOUTcast stream using this URL:
http://85.17.167.136:8684/7.html
... which returns data like:
<HTML><meta http-equiv="Pragma" content="no-cache"></head><body>7,1,77,100,7,128,+44(0)7908 340 811 Follow Us #visionradiouk</body></html>
I know that the after the first comma returns 1 if the stream is up and running or returns 0 if the stream is down. My problem is getting the html of that page? I use this code, which works on other websites like Google etc.
TextView tView = (TextView) findViewById(R.id.textView1);
String htmlCode = "";
try {
URL url = new URL("http://85.17.167.136:8684/7.html");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine())!= null)
htmlCode += inputLine;
System.out.println(htmlCode);
tView.setText(htmlCode);
in.close();
} catch (Exception e){
System.out.println("error");
}
}
Any ideas on what I am doing wrong?

Heres Pulsarman325's working solution, tidied up, with a little extra stuff i had to add to get it to work (try/catch and variable initialisations)
String url = "http://molestia.ponify.me:8062";
URL url2=null;
try
{
url2 = new URL(url + "/7.html");
}
catch (MalformedURLException e1)
{
e1.printStackTrace();
}
URLConnection con=null;
try
{
con = url2.openConnection();
}
catch (IOException e1)
{
e1.printStackTrace();
}
con.setRequestProperty("User-Agent", "Mozilla/5.0");
Reader r = null;
try
{
r = new InputStreamReader(con.getInputStream());
}
catch (IOException e)
{
e.printStackTrace();
}
StringBuilder buf = new StringBuilder();
int ch=0;
while (true)
{
try
{
ch = r.read();
}
catch (IOException e)
{
e.printStackTrace();
}
if (ch < 0)
break;
buf.append((char) ch);
}
String str = buf.toString();
String trackinfo = str.split(",")[6].split("</body>")[0];
Log.d("HTML", trackinfo);

Related

Boolean.parseBoolean not working

I am trying to save this boolean array. When I read the array the string array (parts) says that
parts[0]=true;
,but when I use Boolean.parseBoolean array[0] is still false. Can someone help me and tell me what I am doing wrong. Please and Thank You.
public void writeArraytofile() {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("array.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(Arrays.toString(array));
outputStreamWriter.close();
} catch (IOException e) {
Log.v("MyActivity", e.toString());
}
}
public boolean[] read(){
String result = "";
boolean[] array = new boolean[2];
try {
InputStream inputStream = openFileInput("array.txt");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String tempString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((tempString = bufferedReader.readLine()) != null) {
stringBuilder.append(tempString);
}
inputStream.close();
result = stringBuilder.toString();
String[] parts = result.split(" ");
for (int i = 0; i < array.length; i++){
array[i]=Boolean.parseBoolean(parts[i]);
}
}
} catch (FileNotFoundException e) {
Log.v("MyActivity", "File not found" + e.toString());
} catch (IOException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
//here you catch and watch the problem
Log.e("MyActivity", "cant parse string: " + result);
}
return array;
}
Arrays.toString() will print brackets and commas, so when you read the string back in and call .split(" "), the first piece will be "[true,". Since that is not just "true", Boolean.parseBoolean() will return false.

Android Studio - Why does a string array cause my program to stop?

I have been working on this for a while and I am about to pull my hair out!!
If I use this...
public void readFile() {
BufferedReader buffReader = null;
StringBuilder result = new StringBuilder();
try {
FileInputStream fileIn = openFileInput("VariableStore.txt");
buffReader = new BufferedReader(new InputStreamReader(fileIn));
String line;
while ((line = buffReader.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
assert buffReader != null;
buffReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String resultString = result.toString();
String[] controlString = resultString.split("$");
// String wb = controlString[4];
// String sb = controlString[5];
((Button) this.findViewById(R.id.wakeButton)).setText(resultString);
// ((Button) this.findViewById(R.id.sleepButton)).setText(sb);
// ((Button)this.findViewById(R.id.wakeButton)).setText(result);
// ((Button)this.findViewById(R.id.wakeButton)).setText(result);
// ((Button)this.findViewById(R.id.wakeButton)).setText(result);
}
The Button.setText works fine with "resultString" or with "result" which is a string I have input formatted as xxx$xxx$xxx$xxx$xxx so when I read it back in with the readFile() I want to use .Split and put it into an array "controlString" and then assign the array elements to my widgets i.e. setText(controlString[0]); but if I so much as even uncomment the lines String wb = controlString[4]; or String sb = controlString[5]; my program crashes. Why wont the array elemts work here?
Here is my writeFile().... (Which works perfectly.
public void writeFile() {
BufferedWriter buffWriter = null;
String wb = ((Button)this.findViewById(R.id.wakeButton)).getText().toString();
String sb = ((Button)this.findViewById(R.id.sleepButton)).getText().toString();
String tb = ((EditText)this.findViewById(R.id.textHoursBetween)).getText().toString();
String ti = ((EditText)this.findViewById(R.id.textIncrementTime)).getText().toString();
String td = ((EditText)this.findViewById(R.id.textIncrementDays)).getText().toString();
String writeString = wb + "$" + sb + "$" + tb + "$" + ti + "$" + td;
try {
FileOutputStream fileOut = openFileOutput("VariableStore.txt", Context.MODE_PRIVATE);
buffWriter = new BufferedWriter(new OutputStreamWriter(fileOut));
try {
buffWriter.write(writeString);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
try {
assert buffWriter != null;
buffWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I found the problem...
Instead of this:
String[] controlString = resultString.split("$");
I had to use this:
String[] controlString = resultString.split(Pattern.quote("$"));

Android: java.net.protocolException does not support output

I was previously using HttpClient and BasicNameValuePairs, for some reason i have to shift to HttpUrlConnection.
Hence this code, to make a HttpPost request with certain parameters:
public class MConnections {
static String BaseURL = "http://www.xxxxxxxxx.com";
static String charset = "UTF-8";
private static String result;
private static StringBuilder sb;
private static List<String> cookies = new ArrayList<String>();
public static String PostData(String url, String sa[][]) {
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) new URL(BaseURL + url)
.openConnection();
} catch (MalformedURLException e1) {
} catch (IOException e1) {
}
cookies = connection.getHeaderFields().get("Set-Cookie");
try{
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=" + charset);
}catch (Exception e) {
//Here i get Exception that "java.lang.IllegalStateException: Already connected"
}
OutputStream output = null;
String query = "";
int n = sa.length;
for (int i = 0; i < n; i++) {
try {
query = query + sa[i][0] + "="
+ URLEncoder.encode(sa[i][1], "UTF-8");
} catch (UnsupportedEncodingException e) {
}
}
try {
output = connection.getOutputStream();
output.write(query.getBytes(charset));
} catch (Exception e) {
//Here i get Exception that "android: java.net.protocolException: Does not support output"
} finally {
if (output != null)
try {
output.close();
} catch (IOException e) {
}
}
InputStream response = null;
try {
response = connection.getInputStream();
} catch (IOException e) {
//Here i get Exception that "java.io.IOException: BufferedInputStream is closed"
} finally {
//But i am closing it here
connection.disconnect();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
response, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine());
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append("\n" + line);
}
response.close();
result = sb.toString();
} catch (Exception e) {
}
return result;
}
}
But i get such Exceptions as commented in the code.
Actually i am calling MConnections.PostData() twice from my Activity using a AsyncTask. This might cause the Exception: Already Connected but i am using connection.disconnect. But why am i still getting that Exception?
Am i using it the wrong way?
Thank You
For the protocol exception, try adding the following before you call getOutputStream():
connection.setDoOutput(true);
Discovered this answer thanks to Brian Roach's answer here: https://stackoverflow.com/a/14026377/387781
Side note: I was having this issue on my HTC Thunderbolt running Gingerbread, but not on my Nexus 4 running Jelly Bean.

read a text file android

I am trying to make the computer read a text file full of words and add it to an ArrayList. I made it work on a regular Java application, but can't get it to work on Android. Can someone help me out?
try {
FileInputStream textfl = (FileInputStream) getAssets().open("test.txt");
DataInputStream is = new DataInputStream(textfl);
BufferedReader r = new BufferedReader(new InputStreamReader(is));
String strLine;
while ((strLine = r.readLine()) != null) {
tots.add(strLine); //tots is the array list
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I keep getting a error. The text file is 587kb, so could that be a problem?
try this.
private static String readTextFile(String fileName)
{
BufferedReader in = null;
try
{
in = new BufferedReader(new InputStreamReader(getAssets().open(fileName)));
String line;
final StringBuilder buffer = new StringBuilder();
while ((line = in.readLine()) != null)
{
buffer.append(line).append(System.getProperty("line.separator"));
}
return buffer.toString();
}
catch (final IOException e)
{
return "";
}
finally
{
try
{
in.close();
}
catch (IOException e)
{
// ignore //
}
}
}

How to display all pages and all chapters using nl.siegmann.epublib

This is what I tried to perform the task if anyone can help out it would be most appreciated. So in this code it will display just the cover page. I read http://www.siegmann.nl/static/epublib/apidocs/ that you could use getSpine() to get everything but it only displayed one thing on my case which is cover page.
webView = (WebView)findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
AssetManager am = getAssets();
try {
InputStream epubInputStream = am.open(bookName);
book = (new EpubReader()).readEpub(epubInputStream);
} catch (IOException e) {
Log.e("epublib", e.getMessage());
}
Spine spine = book.getSpine();
for (SpineReference bookSection : spine.getSpineReferences()) {
Resource res = bookSection.getResource();
try {
InputStream is = res.getInputStream();
StringBuffer string = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
while ((line = reader.readLine()) != null) {
linez = string.append(line + "\n").toString();
}
} catch (IOException e) {e.printStackTrace();}
//do something with stream
} catch (IOException e) {
e.printStackTrace();
}
}
webView.loadData(linez, "text/html", "utf-8");
So what I figured out using spine on http://www.siegmann.nl/static/epublib/apidocs/ is that it still works by sections. So I tried to figure out how many sections are there by identifying count numbers. Then placed those numbers in Resource res = spine.getResource(i);. If you would do Resource res = spine.getResource(2); It would display the spine of 2 which should be chapter 2 unless someone messes up the format of the epub.
Spine spine = book.getSpine();
List<SpineReference> spineList = spine.getSpineReferences() ;
int count = spineList.size();
tv.setText(Integer.toString(count));
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();
}
} catch (IOException e) {e.printStackTrace();}
//do something with stream
} catch (IOException e) {
e.printStackTrace();
}
}
webView.loadData(linez, "text/html", "utf-8");

Categories

Resources