Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

Llamada GET en Android Studio con Java

Tiempo de lectura: 2 minutos

Para crear una lista de elementos obtenidos de una llamada GET y mostrarlos, hay que seguir los siguientes pasos como muestro en el ejemplo.

Primero creamos un archivo XML para definir la vista con la lista. Para poder mostrar una lista, vamos a usar el elemento “ListView”.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="match_parent"/> </RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

A continuación inicializamos el ListView y el Adapter e inicializamos

Inicializamos GetDataTask que extiende de AsyncTask para realizar una solicitud GET en segundo plano doInBackground que crea una conexión con la URL lee los datos de esa conexión y los almacenamos en una lista como ejemplo lo llamamos data.

Cuando la tarea en segundo plano está completa, llamamos a onPostExecute y recibimos los datos JSON.

Finalmente, agregamos al Adapter del ListView- Y para actualizar la vista usamos adapter.notifyDataSetChanged().

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
public class MainActivity extends AppCompatActivity {
private ListView listView;
private ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
// Método para realizar la solicitud GET
new GetDataTask().execute();
listView.setAdapter(adapter);
}
private class GetDataTask extends AsyncTask<Void, Void, List<String>> {
@Override
protected List<String> doInBackground(Void... voids) {
// URL del endpoint correspondiente en tu servidor
String apiUrl = "url_api";
List<String> data = new ArrayList<>();
try {
URL url = new URL(apiUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
data.add(line); // Agregar los datos obtenidos
}
bufferedReader.close();
urlConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
@Override
protected void onPostExecute(List<String> result) {
super.onPostExecute(result);
List<String> centerNames = new ArrayList<>();
try {
for (String jsonData : result) {
JSONArray jsonArray = new JSONArray(jsonData);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String centerName = jsonObject.getString("name");
centerNames.add(centerName);
}
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("JSON_PARSE_ERROR", "Error parsing JSON: " + e.getMessage());
// Log.e("JSON_PARSE_ERROR", "JSON Data: " + jsonData);
}
adapter.addAll(centerNames);
adapter.notifyDataSetChanged();
}
}
}
public class MainActivity extends AppCompatActivity { private ListView listView; private ArrayAdapter<String> adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = findViewById(R.id.listView); adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1); // Método para realizar la solicitud GET new GetDataTask().execute(); listView.setAdapter(adapter); } private class GetDataTask extends AsyncTask<Void, Void, List<String>> { @Override protected List<String> doInBackground(Void... voids) { // URL del endpoint correspondiente en tu servidor String apiUrl = "url_api"; List<String> data = new ArrayList<>(); try { URL url = new URL(apiUrl); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(urlConnection.getInputStream())); String line; while ((line = bufferedReader.readLine()) != null) { data.add(line); // Agregar los datos obtenidos } bufferedReader.close(); urlConnection.disconnect(); } catch (IOException e) { e.printStackTrace(); } return data; } @Override protected void onPostExecute(List<String> result) { super.onPostExecute(result); List<String> centerNames = new ArrayList<>(); try { for (String jsonData : result) { JSONArray jsonArray = new JSONArray(jsonData); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); String centerName = jsonObject.getString("name"); centerNames.add(centerName); } } } catch (JSONException e) { e.printStackTrace(); Log.e("JSON_PARSE_ERROR", "Error parsing JSON: " + e.getMessage()); // Log.e("JSON_PARSE_ERROR", "JSON Data: " + jsonData); } adapter.addAll(centerNames); adapter.notifyDataSetChanged(); } } }
public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private ArrayAdapter<String> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = findViewById(R.id.listView);
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);

        // Método para realizar la solicitud GET
        new GetDataTask().execute();

        listView.setAdapter(adapter);
    }

    private class GetDataTask extends AsyncTask<Void, Void, List<String>> {

        @Override
        protected List<String> doInBackground(Void... voids) {
            // URL del endpoint correspondiente en tu servidor
            String apiUrl = "url_api";

            List<String> data = new ArrayList<>();

            try {
                URL url = new URL(apiUrl);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");

                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(urlConnection.getInputStream()));
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    data.add(line); // Agregar los datos obtenidos
                }

                bufferedReader.close();
                urlConnection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return data;
        }


        @Override
        protected void onPostExecute(List<String> result) {
            super.onPostExecute(result);
            List<String> centerNames = new ArrayList<>();

            try {
                for (String jsonData : result) {
                    JSONArray jsonArray = new JSONArray(jsonData);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        String centerName = jsonObject.getString("name");
                        centerNames.add(centerName);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Log.e("JSON_PARSE_ERROR", "Error parsing JSON: " + e.getMessage());
                // Log.e("JSON_PARSE_ERROR", "JSON Data: " + jsonData);
            }

            adapter.addAll(centerNames);
            adapter.notifyDataSetChanged();
        }
    }

}

Por último muestro el resultado de la lista en vista móvil.

Espero que les sirva de ayuda! Que tengan un feliz día.

1

Deja un comentario