Basic android http get - android

I'm a android noob on programming, but with some help of a few programms I can learn the basics. I would like to do a basic http get request to an arduino ethernetshield.
For this I've found some code, but I can't get it to work.
I'm allways stuck on the getResponse part with the code I've tried from several pages.
I've found the following page which gave me readable code:
How to work with an image using url in android?
Now I've created the following:
Press on a button and do a get to an url:
package adhttpget.test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class AdhttpgetActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void pushbutton1(View view) {
Toast.makeText(getBaseContext(), "button press", Toast.LENGTH_SHORT).show();
Log.e("button", "pressed");
URL connectURL = new URL("http://192.168.0.48/?out=13&status=2");
HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
// do some setup
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
// connect and flush the request out
conn.connect();
conn.getOutputStream().flush();
// now fetch the results
String response = getResponse(conn); // <-- THIS IS MY PROBLEM
}
private String getResponseOrig(HttpURLConnection conn)
{
InputStream is = null;
try
{
is = conn.getInputStream();
// scoop up the reply from the server
int ch;
StringBuffer sb = new StringBuffer();
while( ( ch = is.read() ) != -1 ) {
sb.append( (char)ch );
}
return sb.toString();
}
catch(Exception e)
{
Log.e("http", "biffed it getting HTTPResponse");
}
finally
{
try {
if (is != null)
is.close();
} catch (Exception e) {}
}
return "";
}
}
Where can I find information to learn how to write the code correctly?
Or do you happen to have the answer in some kind of hint so I can learn from it?

You must create a BufferedReader passing the InputStream, then you can read strings
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Then I recommend you make the connection (or read/write file) with a separeted thread from the Thread UI (use Thread, AsyncTask, Handler, etc) because that will improve your app.
http://developer.android.com/intl/es/guide/components/processes-and-threads.html

Related

how to post json data to the restful API in header to get json response android

I want to make connection to the api and post the string data to the api to get the json result but i dont know howit is done here is my code , can anyone tell me how to put json data in this url connection and pass it
package practise.c.practise;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class API extends AppCompatActivity {
String USERID;
String APIKEY;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_api);
Log.d("oncreate", "onCreate: ");
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
Log.d("threadrun", "onCreate: ");
URL url = new URL("https://api.api.com/v1");
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
String userCredentials = "2223:6c005hhhh1eggggf4447b59bfed";
String basicAuth = Base64.encodeToString(userCredentials.getBytes(),Base64.DEFAULT);
httpURLConnection.setRequestProperty ("Authorization","Basic" + basicAuth);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Accept-Language", "en");
int responseCode = httpURLConnection.getResponseCode();
Log.d("responsecode", "run: "+responseCode);
if(responseCode == 200){
InputStream inputStr = httpURLConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStr));
StringBuilder result = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("API:DATA", "run: "+result);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
Try the following code template. What you need is explained in comments within the code.
/**
* Created by sibidharan on 18/11/14.
* Sample class
*/
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.StringBody;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.UnknownHostException;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLPeerUnverifiedException;
/*
Usage of the class
Create all the necessary API Call methods you need.
And either use a Thread or AsyncTask to call the following.
JSONObject response = ApiUrlCalls.login("username", "passowrd");
After the response is obtained, check for status code like
if(response.getInt("status_code") == 200){
//TODO: code something
} else {
//TODO: code something
}
*/
public class ApiUrlCalls {
private String HOST = "https://domain/path/"; //This will be concated with the function needed. Ref:1
/*
Now utilizing the method is so simple. Lets consider a login function, which sends username and password.
See below for example.
*/
public static JSONObject login(String username, String password){
String functionCall = "login";
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("username", username)
.appendQueryParameter("password", password);
/*
The return calls the apiPost method for processing.
Make sure this should't happen in the UI thread, orelse, NetworkOnMainThread exception will be thrown.
*/
return apiPost(builder, functionCall);
}
/*
This method is the one which performs POST operation. If you need GET, just change it
in like Connection.setRequestMethod("GET")
*/
private static JSONObject apiPost(Uri.Builder builder, String function){
try {
int TIMEOUT = 15000;
JSONObject jsonObject = new JSONObject();
try {
URL url = null;
String response = "";
/*
Ref:1
As mentioned, here below, in case the function is "login",
url looks like https://domain/path/login
This is generally a rewrited form by .htaccess in server.
If you need knowledge on RESTful API in PHP, refer
http://stackoverflow.com/questions/34997738/creating-restful-api-what-kind-of-headers-should-be-put-out-before-the-response/35000332#35000332
I have answered how to create a RESTful API. It matches the above URL format, it also includes the .htaccess
*/
url = new URL(HOST + function);
HttpsURLConnection conn = null;
conn = (HttpsURLConnection) url.openConnection();
assert conn != null;
conn.setReadTimeout(TIMEOUT);
conn.setConnectTimeout(TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
int responseCode = conn.getResponseCode();
String responseMessage = conn.getResponseMessage();
jsonObject.put("status_code", responseCode);
jsonObject.put("status_message", responseMessage);
/*The if condition below will check if status code is greater than 400 and sets error status
even before trying to read content, because HttpUrlConnection classes will throw exceptions
for status codes 4xx and 5xx. You cannot read content for status codes 4xx and 5xx in HttpUrlConnection
classes.
*/
if (jsonObject.getInt("status_code") >= 400) {
jsonObject.put("status", "Error");
jsonObject.put("msg", "Something is not good. Try again later.");
return jsonObject;
}
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
//Log.d("RESP", response);
/*
After the actual payload is read as a string, it is time to change it into JSON.
Simply when it starts with "[" it should be a JSON array and when it starts with "{"
it is a JSONObject. That is what hapenning below.
*/
if(response.startsWith("[")) {
jsonObject.put("content", new JSONArray(response));
}
if(response.startsWith("{")){
jsonObject.put("content", new JSONObject(response));
}
} catch(UnknownHostException e) {
//No explanation needed :)
jsonObject.put("status", "UnknownHostException");
jsonObject.put("msg", "Check your internet connection");
} catch (SocketTimeoutException){
//This is when the connection timeouts. Timeouts can be modified by TIMEOUT variable above.
jsonObject.put("status", "Timeout");
jsonObject.put("msg", "Check your internet connection");
} catch (SSLPeerUnverifiedException se) {
//When an untrusted SSL Certificate is received, this happens. (Only for https.)
jsonObject.put("status", "SSLException");
jsonObject.put("msg", "Unable to establish secure connection.");
se.printStackTrace();
} catch (IOException e) {
//This generally happens when there is a trouble in connection
jsonObject.put("status", "IOException");
jsonObject.put("msg", "Check your internet connection");
e.printStackTrace();
} catch(FileNotFoundException e){
//There is no chance that this catch block will execute as we already checked for 4xx errors
jsonObject.put("status", "FileNotFoundException");
jsonObject.put("msg", "Some 4xx Error");
e.printStackTrace();
} catch (JSONException e){
//This happens when there is a troble reading the content, or some notice or warnings in content,
//which generally happens while we modify the server side files. Read the "msg", and it is clear now :)
jsonObject.put("status", "JSONException");
jsonObject.put("msg", "We are experiencing a glitch, try back in sometime.");
e.printStackTrace();
} return jsonObject;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
I just made changes in two lines of my code and my code started working
URL url = new URL("http://api.api.com/v1");// http instead of https
httpURLConnection.setRequestProperty ("Authorization","Basic " + basicAuth);//gave space after Basic

How to resolve android.os.networkonmainthreadexception

I am new to android and I am trying to read data from a server. I use a util and call that util like this
private void ParseSource(String Url){
String source = new Cls_SourceGrabber().grabSource(Url);
}
But I am getting a android.os.networkonmainthreadexception. How can I reduce that?
My SourceGrabber util:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class Cls_SourceGrabber {
private HttpGet mRequest;
private HttpClient mClient;
private BufferedReader mReader;
private StringBuffer mBuffer;
private String mNewLine;
public Cls_SourceGrabber() {
mRequest = new HttpGet();
InitializeClient();
mReader = null;
mBuffer = new StringBuffer(10000);
mNewLine = System.getProperty("line.separator");
}
private void InitializeClient() {
if (mClient == null || mClient.getConnectionManager() == null) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 4500);
HttpConnectionParams.setSoTimeout(httpParameters, 10000);
// HttpConnectionParams.setTcpNoDelay(httpParameters, true);
mClient = new DefaultHttpClient(httpParameters);
}
}
/*
*Grab the full source
*/
public String grabSource(String url) {
mBuffer.setLength(0);
InitializeClient();
String source = "";
try {
mRequest.setURI(new URI(url));
HttpResponse response = mClient.execute(mRequest);
mReader = new BufferedReader(new InputStreamReader(response
.getEntity().getContent()));
String line = "";
while ((line = mReader.readLine()) != null) {
mBuffer.append(line);
mBuffer.append(mNewLine);
source = mBuffer.toString();
if (Thread.interrupted()) {
break;
}
}
} catch (ConnectTimeoutException e) {
source = "Connection Timed Out.";
} catch (java.net.UnknownHostException e) {
source = "No Internet Connection available!";
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
source = "Site Parsing Exception.";
} catch (ClientProtocolException e) {
source = "Protocol Exception.";
} catch (IOException e) {
source = "Server not responding.";
} catch (URISyntaxException e) {
source = "Wrong URL!";
} catch (Exception e) {
source = "Exception - " + e.toString() + " - "
+ e.getMessage();
e.printStackTrace();
} finally {
closeReader();
}
return source;
}
}
First of all, I would not recommend on using HTTPClient any more, since it is not supported any more from sdk version 23.
So, it will be better to migrate the network operations to URL Connection.
Now, android never allows network operations on Main thread since it will block the UI thread for a considerable time, hence may cause crash or bad user experience.
You can take a look on these docs : Doc 1
The better way to do Network operations is by creating an AsyncTask.
Just take care not to access any UI thread element in the doInBackground method. You can modify UI Thread elements on onPreExecute or onPostExecute Methods.
I have created a NetworkOps Util. You can take a look on that, whether it may be any use for you :
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import com.csehelper.variables.Constants;
import com.csehelper.variables.Keys;
import com.csehelper.variables.Url;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
public class NetworkOps {
public final String EXCEPTION = "~Exception~";
/****************************
* Method to Grab Source
****************************/
public static String GrabSource(String URL) {
return PostData(URL, null);
}
/**
* *****************************************
* Method to Grab Source code from URL
* Posting Data
* *****************************************
*/
private static String PostData(String url, Uri.Builder uribuilder) {
String Source;
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) new URL(url).openConnection();
urlConnection.setDoOutput(true);
urlConnection.setConnectTimeout(10000);
if(uribuilder != null) {
String query = uribuilder.build().getEncodedQuery();
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
}
urlConnection.connect();
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
String line;
StringBuilder builder = new StringBuilder();
InputStreamReader isr = new InputStreamReader(
urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Source = builder.toString();
} else {
Source = EXCEPTION + "Server unreachable. Check network connection.";
}
} catch (SocketTimeoutException e) {
Source = EXCEPTION + "Connection timed out.";
} catch (java.net.UnknownHostException e) {
Source = EXCEPTION + Constants.EXCEPTION_NO_NET;
} catch (ArrayIndexOutOfBoundsException e) {
Source = EXCEPTION + "Server error";
} catch (ProtocolException e) {
Source = EXCEPTION + "Protocol error";
} catch (IOException e) {
Source = EXCEPTION + "Server unreachable. Check network connection.";
} catch (Exception e) {
Source = EXCEPTION + "Error:" + e.toString() + " - "
+ e.getMessage();
e.printStackTrace();
} finally {
if (urlConnection != null) urlConnection.disconnect();
}
return Source;
}
}
Call these Static Functions from AsyncTask:
/*********************************
* AsyncTask to GrabSource
********************************/
class AsyncTask_GrabSource extends AsyncTask<Void, Void, Void> {
String Source = null;
String url = "https://enigmatic-woodland-35608.herokuapp.com/pager.json";
#Override
protected void onPreExecute() {
//Runs on Main Thread. You can access your UI elements here.
}
#Override
protected Void doInBackground(Void... params) {
// Don't access any UI elements from this function
Source = NetworkOps.GrabSource(this.url);
return null;
}
#Override
protected void onPostExecute(Void result) {
if (Source != null) {
if (!Source.contains("~Exception~")) {
//Show Error Message or do whatever you want
} else {
//Do Whatever with your Grabbed Sourcecode.
// This function runs on UI Thread, so you can update UI elements here
}
}
}
You can also post data with the function PostData. In method doInBackground, add this:
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("key", "value")
.appendQueryParameter("key2", "value2");
Source = NetworkOps.PostData(getApplicationContext(), url, builder);

How to print the entire JSON output?

Please have a look at the following code
package com.example.jsontest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText editText;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.edit_text);
//Call The JSon
try {
JSONObject jObject = new JSONObject(getJson());
int code = jObject.getInt("code");
editText.append("Code: "+code+"\n");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String getJson()
{
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://bigml.io/andromeda/source/5277b1bd035d074e940056e0?username=xxx;api_key=xxxxxxxxxxxxxxx");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
}
In here, what I need to do is, print the "entire" result I retrieved. I wish to print the entire thing, I don't need to get separate values. How can I do this? Here is the link to the BigML retrieve documentation.
Just use JSONObject.toString() ?
You should never connect to network on main thread. Best and the most simple option is to use AsyncTask<...>.
something like this:
private class DownloadProductsTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
try {
return new PublicDataDBManager().retriveJsonData(mCode, mUserMail);
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(String result){
buildData(result);// here you update mathod in your main thread
}
}
Here is simple example: http://androide-examples.blogspot.com/2013/11/android-retrieve-json-data-from-url.html
So I ran your code, and it crashed. I also see that you are bypassing security and doing network operations in onCreate, in the main thread. This isn't a good idea in Android. Network operations should go in a background thread.
I refactored it very quickly to use a thread and it worked. Here is the code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.edit_text);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
new Thread(new Runnable() {
#Override
public void run() {
JSONObject jObject;
try {
jObject = new JSONObject(getJson());
// I am logging the raw value that was returned here
Log.i("JSON Body", jObject.toString());
int code = jObject.getInt("code");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
If you want to update the main thread (MainActivity) within the thread, create a Handler and pass a reference to that into the thread, and use that for updates.

Android app doesn't want do HttpClient request

I'm trying to launch first app that handles Http requests. The following code is from a tutorial book and it doesn't work:
package com.example.httpgetdemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BufferedReader in = null;
System.out.println("Before");
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://google.com/");
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String page = sb.toString();
System.out.println(page);
} catch (Exception e) {
e.printStackTrace();
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
What do I mean by saying it doesn't work - I run in it on a phone and LogCat shows the first System.out.println but not the second one, there is error saying:
E/(1755): Can't open file for reading
I read some threads over here about making it in asynchronous way, but if so, then the app would crash and, what-more, it's a book example so it should work, shouldn't it? The aim phone runs the ICS
What's wrong?
Thanks

how do i load remote text from a text file into android textview?

I have gone through all the examples and I can not seem to get this to work.
This is my current code:
package hello.android;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloAndroidActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.textView1);
try {
// Create a URL for the desired page
URL url = new URL("http://xlradioaustin.com/song/CurrentSong.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
// str is one line of text; readLine() strips the newline character(s)
}
in.close();
tv.setText(str);
} catch (MalformedURLException e) {
tv.setText("mal");
} catch (IOException e) {
tv.setText("io");
}
}
}
Assuming your Android device is online and you've granted your app the INTERNET permission, try this:
try {
// Create a URL for the desired page
URL url = new URL("http://xlradioaustin.com/song/CurrentSong.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
StringBuilder sb = new StringBuilder(100);
while ((str = in.readLine()) != null) {
sb.append(str);
// str is one line of text; readLine() strips the newline character(s)
}
in.close();
tv.setText(sb.toString());
} catch (MalformedURLException e) {
tv.setText("mal");
} catch (IOException e) {
tv.setText("io");
}
Let me know if that works: you are currently looping until str is null, then using that null value.
A follow up on the answer, it worked after adding
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}

Categories

Resources