I am experimenting with firebase and want to read a textfile from the bucket. I can copy the file to local disk, which works fine. Now I want to read the textfile and copy the contents to an arraylist. This time I get the NetworkOnMainThread although I start a new thread to do the work. At least I think I am.I read about using Asynchtask, but would like to know WHY this is not working as expected. The code to get the InputstreamfromURL worked fine in the past.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download);
downloadtext = (TextView) findViewById(R.id.downloadtext);
text = new ArrayList<>();
listViewText = (ListView) findViewById(R.id.listViewtext);
listViewText.setAdapter(new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, text));
Thread thread= new Thread(){
public void run() {
storage = FirebaseStorage.getInstance();
storageRef = storage.getReferenceFromUrl("gs://fir-test-68815.appspot.com");
filename = "testfile.txt";
StorageReference file = storageRef.child(filename);
file.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
Log.d(MainActivity.TAG, "URL =" + uri.toString());
try {
InputStream is = getInputStreamFromURL(uri);
text = getText(is);
textReady.post(new Runnable() {
@Override
public void run() {
((ArrayAdapter)listViewText.getAdapter()).notifyDataSetChanged();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private ArrayList<String> getText(InputStream is) throws IOException {
ArrayList<String> text = new ArrayList<>();
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
text.add(line);
}
return text;
}
private InputStream getInputStreamFromURL(Uri urlToGet) throws IOException {
InputStream is = null;
URL downloadURL = new URL(urlToGet.toString());
HttpURLConnection conn = (HttpURLConnection) downloadURL.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
// next two lines produce the error
int response = conn.getResponseCode();
is = conn.getInputStream();
return is;
}
};
thread.start();
textReady = new Handler();
}