我正在试用firebase,并希望从桶中读取一个文本文件。我可以将文件复制到本地磁盘,这样可以正常工作。现在,我想读取文本文件并将内容复制到数组中。这一次我得到了NetworkOnMainThread,尽管我启动了一个新线程来完成这项工作。至少我认为我是,我读过关于使用Asynchtask的文章,但是想知道为什么它不能像预期的那样工作。过去,获取InputstreamfromURL的代码运行良好。
@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();
}发布于 2016-10-16 11:08:51
Firebase事件回调是默认情况下,在主UI线程上调用。在OnSuccessListener中也会发生这种情况。
还有使用Firebase下载文件的其他方法。但是,如果仍然希望使用getDownloadUrl(),则需要在getDownloadUrl()回调触发后在单独的线程(例如使用AsyncTask)上实现下载。
https://stackoverflow.com/questions/40069327
复制相似问题