BufferedReader and InputStreamReader from URL - android

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.

Related

Reading a DropBox Text File

I have an android app that loads images and text files into Dropbox. I've figured out the authentication and upload process.
Now, using the same authenticated session, I want to read one of the uploaded text files (to look for changes). I've found a download example, but that would mean writing it to local SD, then reading for there ... not efficient at all (in part because of the additional android permission required).
I've examined Dropbox's v2 documentation and there do seem to be a bunch of read calls but I can't, for the life of me, figure out how to use them. The helpful Android-Dropbox examples also don't seem to tackle my specific problem. I couldn't find any v2 examples on stackoverflow either.
Surely, somebody can point me to a simple example that provides a nice InputStream.
You can use the Dropbox Java SDK download method to get file contents directly. There's an example of using that in the example app here. That example writes directly to a FileOutputStream.
It sounds like you just want an InputStream though, which would look like this:
DbxClientV2 client = new DbxClientV2(config, ACCESS_TOKEN);
String remotePath = "/test.txt"; // the path to the file you want to download
InputStream fileInputStream = null;
try {
fileInputStream = client.files().download(remotePath).getInputStream();
// use `fileInputStream` as desired
} catch (DbxException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
After much tooling around, here's something that works
String my_link = null;
URL my_url = null;
URLConnection conn = null;
BufferedReader reader = null;
try {
my_link = my_DbxClient.files().getTemporaryLink("/" + my_File).getLink();
my_url = new URL (my_link);
conn = my_url.openConnection();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} catch (DbxException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Getting text from textfile from server into textview not working

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.

How to load a csv file into android for read/write

I am building an app which needs to read and edit items from a .csv file.
I can place the .csv in the assets folder but would rather the ability to search for it in the external storage as it will change regularly.
A friend has given me this code for placing it in the assets folder, but I am relatively new to android and this code doesn't make sense to me and I cant get it to work.
public ArrayList<String> Job = new ArrayList<String>();
try {
is = res.getAssets().open("Job.csv");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null)
Job.add(line);
} catch (IOException ex) {
// handle exception
} finally {
try {
is.close();
} catch (IOException e) {
// handle exception
}
}

How to deal with version issues in android 1.6 to 2.x

I built a JSON consumer in android for 1.6 (thought it was good practice to build on the oldest version for max support). I was able to successfully retrieve the json under 1.5-1.6. However I just threw the app on my droid (2.x) and now I receive "org.json.jsonexception: expected literal value at character ....". Why the difference in versions? How can I deal with this?
If you can't get it working with that library, try GSON which is great
http://code.google.com/p/google-gson/
I had a method to convert the InputStream to a string representation of the JSON. I needed to adjust the substring from (intial, length()-1) to (initial, length()-2) to get it to work in both 1.5 and 2.x. Thanks for the help.
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader returns null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
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();
}
}
// API is defective and does not return correct json response.
// Reformat string response to confirm to expected json response
// return sb.toString();
return "{\"Results\":" + sb.substring(11, sb.length()-2) + "}\n" ;
}
I had the same error message. In my case, it turned out that the JSON lib was confused because the JSON returned had the quotes (") escaped. This apparently confused it about the length of the string, and caused the exception.

why doenst this code work? in order to get a response from the server in android

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?

Categories

Resources