I'm trying to show the status of something. This is done by saving the status in a textfile (Either online or offline) called status.txt
I then use this code:
try {
// Create a URL for the desired page
URL url = new URL("mywebsite.net/subfolder/status.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
onlineStatus.setVisibility(View.VISIBLE);
onlineStatus.setText(str);
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
}
};
Nothing seems to happen, the app does not crash.
Any help would be appreciated.
Try this
URL url = new URL("http://mywebsite.net/subfolder/status.txt");
Also as good practice never completely ignore the thrown exceptions. Print the stacktrace at the very least. This is very helpful in the long term.
In your case maybe set the text to some generic error message.
Even after this, don't set the text in the while loop if you want to set the whole content in the text view.
Related
I'm a new student working on an android application. The application is almost done and works fine.
The app uses a property list to generate it's content. At this moment it uses a .plist file located in the assets folder. Ideally I want this .plist file to be retrieved from an URL. However i'm stuck on this part for a few days now.
Could you please advise me in how to realise retrieving and using the file from an URL. Any advice is welcome!
In my code we see how I currently read the .plist file. I don't think the parsing of the response is required info for my question:
public class PListHelper {
/**
* PlayList reader from assets
*
* #return string of p-list file
*/
public static String readPlayListFromAssets(Context context) {
StringBuffer sb = new StringBuffer();
BufferedReader br=null;
try {
br = new BufferedReader(new InputStreamReader(context.getAssets().open("restaurant.plist")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException ex) {
ex.printStackTrace();
}
}
Log.i("Main", "input: "+sb.toString());
return sb.toString();
}
Have a look at URLConnection
Also, in the future, avoid using .plist as it something specific to ios and osx. By using another format (like json) you won't have to implement your own parsing.
while(isRunning == true) {
if (SSocket != null) {
try {
Socket socket = SSocket.accept();
PrintStream PStream = new PrintStream(socket.getOutputStream());
BufferedReader BReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String info = null;
while ((info = BReader.readLine()) != null) {
System.out.println("now got " + info);
if (info.equals("")) {
break;
}
}
String content = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Main></Main>";
PStream.println("HTTP/1.0 200 OK");
PStream.println("Content-Type: text/xml");
PStream.println("Content-Length: " + content.length());
PStream.println("");
PStream.println(content);
PStream.close();
BReader.close();
socket.close();
Thread.sleep(10);
} catch (Exception e) {
}
}
}
This code makes the server display a xml, but when I go to another page (e.g. http://10.0.0.101:39878/otherpage.html), the content is the same. How do I do to change the contents of each page and enter a 404 when it does not exist?
You have to parse the client's request to find out which page is being requested, and then send the appropriate content. The code you showed is not doing any parsing at all. In fact, it is not even reading the client's full request to begin with, only the first line of it, which is not enough. You need to read RFC 2616, which defines the HTTP protocol. And then consider NOT implementing an HTTP server manually, but use a pre-made library instead. See How to create a HTTP server in Android? for some suggestions.
I got a bit of a Problem with my App, i use a .txt File for getting the right URL's to Display my Pictures that the App should show. Everything works fine. But if i change the Content of the Remote .txt File the App keeps loading the same Pictures again. Here is the code for getting the Pics from remote.
private ArrayList<String> getPictures(){
fileList.clear();
try {
URL url = new URL("http://server.com/test.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(
url.openStream()));
String str;
while ((str = in.readLine()) != null) {
fileList.add(str);
}
in.close();
} catch (MalformedURLException te) {
finish();
} catch (IOException tt) {
finish();
}
return fileList;
}
So i don't have a clue why it isn't getting the new content for i clear the ArrayList each time the method is called!
I hope someone has a Solution for this Problem, it's pretty anoying.
/edit: forgot to post the Method containing the Adapter, so here it is:
private String getAnImageUrl() {
getPictures();
ArrayAdapter<String> arrAdapt = new ArrayAdapter<String>(this, R.layout.main, fileList);
arrAdapt.setNotifyOnChange(true);
i++;
if (i >= arrAdapt.getCount()) {
i = 0;
}
return test = arrAdapt.getItem(i).toString();
}
Yeah, I experienced this with my own app downloading some JSON. The easiest way to fix it is to add a random parameter to your URL request like so:
String urlString = "http://server.com/test.txt?" + System.currentTimeMillis();
URL url = new URL(urlString);
Which will add the current system time to your url as a parameter, which will bypass any cached version of the page
I'm trying to figure out why special characters in a JSON feed (that looks completely fine when viewed in a browser) will break when used in my Android code. Characters with accent marks, ellipsis characters, curly quote characters and so on are replaced by other characters--perhaps translating it from UTF-8 down to ASCII? I'm not sure. I'm using a GET request to pull JSON data from a server, parsing it, storing it in a database, then using Html.fromHtml() and placing the contents in a TextView.
After much experimentation, I narrowed down possibilities until I discovered the problem is with the Ignition HTTP libraries (https://github.com/kaeppler/ignition). Specifically, with ignitedHttpResponse.getResponseBodyAsString()
Although that's a handy shortcut, that one line results in the broken characters. Instead, I now use:
InputStream contentStream = ignitedHttpResponse.getResponseBody();
String content = Util.inputStreamToString(contentStream);
public static String inputStreamToString(InputStream is) throws IOException {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
// Return full string
return total.toString();
}
Edit: Adding more detail
Here is a minimum test case to reproduce the issue.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
activity = this;
instance = this;
String url = SaveConstants.URL;
IgnitedHttpRequest request = new IgnitedHttp(activity).get(url);
InputStream contentStream = null;
try {
IgnitedHttpResponse response = request.send();
String badContent = response.getResponseBodyAsString();
int start = badContent.indexOf("is Texas");
Log.e(TAG, "bad content: " + badContent.substring(start, start + 10));
contentStream = response.getResponseBody();
String goodContent = Util.inputStreamToString(contentStream);
start = goodContent.indexOf("is Texas");
Log.e(TAG, "good content: " + goodContent.substring(start, start + 10));
} catch (IOException ioe) {
Log.e(TAG, "error", ioe);
}
}
In the log:
bad content: is Texasâ good content: is Texas’
Update: either I'm crazy, or the problem only occurs in the clients' production feed, not their development feed, although the contents look identical when viewed in a browser--showing "Texas’". So perhaps there's some wonky server configuration required to cause this issue... but still, the fix for this issue when it occurs is as I outlined. I do not recommend using response.getResponseBodyAsString();
try {
HttpResponse response = new DefaultHttpClient().execute(
new HttpGet(requestString));
InputStream is = response.getEntity().getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((line=br.readLine()) != null){
long temp = Long.parseLong(line);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Also check for valid response. Why would anyone cast web response to Long ?
Use StringBuilder or simple String for fetching response.
eg.
.
.
StringBuilder reponseBuilder=new StringBuilder("");
while ((line=br.readLine()) != null){
//long temp = Long.parseLong(line);
reponseBuilder.append(line);
}
.
.
And then use it as per scenario may be converting it to a String using:
reponseBuilder.toString();
and if still your facing same issue then,
Yup, This is truly regarding invalid permission stuff.
Add below code,
<uses-permission android:name="android.permission.INTERNET">
as child of your manifest file. And this will work as magic.
You haven't told us what error you are getting, but my guess would be that this line is giving you problems:
long temp = Long.parseLong(line)
Are you trying to parse HTTP reply as series of lines where each line contains a long?