InputStream does not work if used multiple times
I'm having some problems with an InputStream. I'm writing a little Android application and part of it has to fetch HTML code from a website. Generally, it works fine, but sometimes (usually the second time it's called, but it may also take a few tries to reproduce this) it will just skip the InputStream (I noticed this since it takes a few seconds while debugging, but every time it fails it will just immediately skip to the next line). Any ideas what could be causing this and how to fix it?
private class fetchdata extends AsyncTask<Void, Void, Void> {
public Activity activity;
public fetchdata(Activity a)
{
activity = a;
}
protected Void doInBackground(Void...voids)
{
String[] page = new String[16384]; //Number is just for testing, don't worry
try {
page = executeHttpGet();
} catch (Exception e) {
page[0] = "Error";
}
displayFetchedData(page);
return null;
}
public String[] executeHt开发者_如何学CtpGet() throws Exception {
URL u;
InputStream is = null;
DataInputStream dis = null;
String s;
int i = 0;
int hostselection;
boolean skip;
String[] page = new String[16384];
String[] serverurls = new String[2];
addSecurityException();
SharedPreferences dataprefs = getSharedPreferences("serverdata", Context.MODE_PRIVATE);
hostselection = dataprefs.getInt("selectedhost", 0);
SharedPreferences preferences;
preferences = PreferenceManager.getDefaultSharedPreferences(activity);
serverurls[0] = preferences.getString("server01", "");
serverurls[1] = preferences.getString("server02", "");
for (int j = 0; j < 2; j++)
{
skip = false;
if (j == 0)
{
if (hostselection == 0 || hostselection == 1)
{
Authenticator.setDefault(new MyAuthenticator(activity, false));
}
else
{
skip = true;
}
}
if (j == 1)
{
if (hostselection == 0 || hostselection == 2)
{
Authenticator.setDefault(new MyAuthenticator(activity, true));
}
else
{
skip = true;
}
}
if (skip == false)
{
try {
u = new URL(serverurls[j]);
is = u.openStream(); //LINE IN QUESTION
dis = new DataInputStream(new BufferedInputStream(is));
while ((s = dis.readLine()) != null)
{
if (s.length() > 18)
{
page[i] = s;
i++;
}
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
is.close();
}
}
return page;
}
Create a BufferedInputStream
out of the input stream you get, then Call mark()
method with the input stream length as parameter. Call reset()
when you need to reuse the stream next time.
Unrelated, but you aren't closing the DataInputStream.
Tell us more about the skipping. Is an exception raised? Is it possible that when you are running it outside of debug mode it is somehow referencing stale class files? The only thing I can imagine is that somehow your debug and normal classes are somehow different.
精彩评论