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
Related
Okay so I'm trying to make an app that is able to retrieve data from a web server and then show it on a textView and constantly update it if the data changes from the web server. And what I got so far after many rounds of trying is this as shown
public class HttpTest extends AppCompatActivity {
TextView text = (TextView) this.findViewById(R.id.textView3);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_http_test);
HttpURLConnection urlConnection = null;
try {
URL url = new URL("http://IPGOESHERE/");
HttpURLConnection urLConnection = (HttpURLConnection) url.openConnection();
InputStream in = urLConnection.getInputStream();
BufferedReader data = new BufferedReader(new InputStreamReader(in));
StringBuilder total = new StringBuilder();
String line;
while ((line = data.readLine()) != null) {
total.append(line).append('\n');
}
String result = total.toString();
text.setText(result);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
I don't think what i have written allows for constant update, but I at least want to be able to show some kind of data on a textView and make sure it doesn't crash first. So if someone could point out what I'm doing wrong it will be much appreciated.
The app crash because you are making HTTP request on main thread. Use an AsyncTask instead
you need to this kind of work on a different thread. try using an AsyncTask.
you create a class that extends AsyncTask, than make the url connection in the doInBackground method (a method that gets called on a worker thread). you can then update the textview in the onPostExecute method which is called on the ui thread. good luck :)
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.
I want to read a text file from a URL, parse, and then set an arraylist and then add it to my adapter. However whenever I try launching the app I'm finding my infos arraylist is not populating with data. I want to know how do I get the application to read data from a URL and then display it. I do have the persmission for INTERNET in the maniifest.
CardAdapter ca = new CardAdapter(createList(0));
recList.setAdapter(ca);
ArrayList<CardInfo> infos = new ArrayList<CardInfo>();
try {
URL url = new URL("https://dl.dropboxusercontent.com/u/56230108/events.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
String line = "";
while ((line = br.readLine()) != null) {
Log.e("value", line);
String[] a = line.split("\\$EV\\$");
CardInfo info = new CardInfo();
info.title = a[0];
info.desc = a[1];
info.date = a[2];
info.time = a[3];
info.contact = a[4];
infos.add(info);
}
br.close();
}
catch(Exception e)
{
}
if(infos.size() > 0)
{
ca.add(infos.get(0), 0);
}
It looks like you are only ever adding a single item to your adapter. Try this for loop instead of the if statement you have, at the bottom of your code:
for(CardInfo info: infos)
{
ca.add(info, 0);
}
you forgot use URLConnection to connect to link.
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.
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();