I want to make a query to Firestore database to get a url stored. Then with that url I want to show the .txt that cointains the url.
My problem is that the code executes automatically and doesn’t wait to end the query.
I want to:
-
Store the url in a variable.
-
With that variable take the .txt and read line by line in a texview.
I can do both, but separately, when I try to do it together I have the problem, I need to wait the result and then continue executing the code. How can I do it?
My code is:
String idioma, modo, cuento, url_cuento;
FirebaseFirestore db = FirebaseFirestore.getInstance();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reproductor_cuento);
//Hacemos llamada a clase para mostrar la pantalla completa
PantallaCompleta pantallaCompleta = new PantallaCompleta();
View decorView = getWindow().getDecorView();
pantallaCompleta.pantallaCompleta(decorView);
//Recogemos los parametros que se pasan por activities
Bundle extra = this.getIntent().getExtras();
idioma = extra.getString("idioma");
modo = extra.getString("modo");
cuento = extra.getString("cuento");
url_cuento = consultaTxtCuento(cuento, idioma);
new GetData().execute();
}
public String consultaTxtCuento(String cuento, String idioma){
final String[] urlTxt = new String[1];
DocumentReference docRef = db.collection("cuentos").document(cuento);
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
urlTxt[0] = document.get("txt_" + idioma).toString();
System.out.println("Se obtiene como URL -> " + urlTxt[0]);
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
return urlTxt[0];
}
class GetData extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
String result = "";
try {
URL url = new URL(url_cuento);
urlConnection = (HttpURLConnection) url.openConnection();
int code = urlConnection.getResponseCode();
if(code==200){
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
if (in != null) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
}
in.close();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return result;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
What can I do to execute waiting the results? Thanks
Carlos Serrano is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.