Android: actualice los datos en la API usando Volley con Jetpack Compose

Las API se utilizan en las aplicaciones de Android para acceder a los datos de los servidores. Podemos realizar varias operaciones CRUD utilizando estas API dentro de nuestra base de datos, como agregar nuevos datos, actualizar datos y leer y actualizar datos. En este artículo, veremos cómo actualizar datos en API usando Volley en Android con Jetpack Compose

Implementación paso a paso

Paso 1: crea un nuevo proyecto en Android Studio

Para crear un nuevo proyecto en Android Studio, consulte Cómo crear/iniciar un nuevo proyecto en Android Studio . Al elegir la plantilla, seleccione Actividad de composición vacía . Si no encuentra esta plantilla, intente actualizar Android Studio a la última versión. Demostramos la aplicación en Kotlin, así que asegúrese de seleccionar Kotlin como idioma principal al crear un nuevo proyecto.

Paso 2: Agregar dependencia en build.gradle

Navegue a build.gradle y agregue la dependencia a continuación en la sección de dependencias. 

// below line is used for volley library
implementation ‘com.android.volley:volley:1.1.1’

Después de agregar la dependencia, simplemente sincronice su proyecto para instalarlo. 

Paso 3: agregar permisos a Internet en el archivo AndroidManifest.xml

Vaya a la aplicación > AndroidManifest.xml y agréguele el siguiente código. 

XML

<uses-permission android:name="android.permission.INTERNET"/>

Paso 4: trabajar con el archivo MainActivity.kt

Vaya al archivo MainActivity.kt y consulte el siguiente código. A continuación se muestra el código del archivo MainActivity.kt . Se agregan comentarios dentro del código para comprender el código con más detalle.

Kotlin

package com.example.newcanaryproject
 
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.*
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.*
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.VolleyError
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.example.newcanaryproject.ui.theme.*
import org.json.JSONException
import org.json.JSONObject
import java.util.*
 
class MainActivity : ComponentActivity() {
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            NewCanaryProjectTheme {
                // on below line we are specifying background color for our application
                Surface(
                    // on below line we are specifying modifier and color for our app
                    modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background
                ) {
                    // on below line we are specifying theme as scaffold.
                    Scaffold(
 
                        // in scaffold we are specifying top bar.
                        topBar = {
 
                            // inside top bar we are specifying background color.
                            TopAppBar(backgroundColor = greenColor,
 
                                // along with that we are specifying title for our top bar.
                                title = {
 
                                    // in the top bar we are specifying tile as a text
                                    Text(
 
                                        // on below line we are specifying text
                                        // to display in top app bar.
                                        text = "Volley PUT Request in Android",
 
                                        // on below line we are specifying
                                        // modifier to fill max width.
                                        modifier = Modifier.fillMaxWidth(),
 
                                        // on below line we are
                                        // specifying text alignment.
                                        textAlign = TextAlign.Center,
 
                                        // on below line we are
                                        // specifying color for our text.
                                        color = Color.White
                                    )
                                })
                        }) {
                        // on below line we are calling pop
                        // window dialog method to display ui.
                        updateDataUsingVolley()
                    }
                }
            }
        }
    }
}
 
@Composable
fun updateDataUsingVolley() {
    // on below line we are creating a
    // variable for our context
    val ctx = LocalContext.current
 
    // on below line we are creating variables
    // for user name, job and response.
    val userName = remember {
        mutableStateOf(TextFieldValue())
    }
    val job = remember {
        mutableStateOf(TextFieldValue())
    }
    val response = remember {
        mutableStateOf("")
    }
 
    // on the below line we are creating a column.
    Column(
        // on below line we are adding a modifier to it
        // and setting max size, max height and max width
        modifier = Modifier
            .fillMaxSize()
            .fillMaxHeight()
            .fillMaxWidth(),
 
        // on below line we are adding vertical
        // arrangement and horizontal alignment.
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
 
        // on below line we are creating a text
        Text(
            // on below line we are specifying text as
            // Session Management in Android.
            text = "Volley PUT Request in Android",
 
            // on below line we are specifying text color.
            color = greenColor,
 
            fontSize = 20.sp,
 
            // on below line we are specifying font family
            fontFamily = FontFamily.Default,
 
            // on below line we are adding font weight
            // and alignment for our text
            fontWeight = FontWeight.Bold, textAlign = TextAlign.Center
        )
 
        // on below line we are adding spacer
        Spacer(modifier = Modifier.height(5.dp))
 
        // on below line we are creating
        // a text field for our email.
        TextField(
            // on below line we are specifying
            // value for our email text field.
            value = userName.value,
 
            // on below line we are adding on
            // value change for text field.
            onValueChange = { userName.value = it },
 
            // on below line we are adding place holder
            // as text as "Enter your email"
            placeholder = { Text(text = "Enter your name") },
 
            // on below line we are adding modifier to it
            // and adding padding to it and filling max width
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth(),
 
            // on below line we are adding text style
            // specifying color and font size to it.
            textStyle = TextStyle(color = Color.Black, fontSize = 15.sp),
             
              // on below line we are adding
              // single line to it.
            singleLine = true,
 
            )
 
        // on below line we are adding spacer
        Spacer(modifier = Modifier.height(5.dp))
 
        // on below line we are creating
        // a text field for our email.
        TextField(
            // on below line we are specifying
            // value for our email text field.
            value = job.value,
 
            // on below line we are adding on
            // value change for text field.
            onValueChange = { job.value = it },
 
            // on below line we are adding place holder
            // as text as "Enter your email"
            placeholder = { Text(text = "Enter your job") },
 
            // on below line we are adding modifier to it
            // and adding padding to it and filling max width
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth(),
 
            // on below line we are adding text style
            // specifying color and font size to it.
            textStyle = TextStyle(color = Color.Black, fontSize = 15.sp),
             
              // on below line we are adding
              // single line to it.
            singleLine = true,
        )
 
        // on below line we are adding spacer
        Spacer(modifier = Modifier.height(10.dp))
 
        // on below line we are creating a button
        Button(
            onClick = {
                // on below line we are calling make
                // payment method to update data.
                updateData(
                    userName.value.text, job.value.text, ctx, response
                )
            },
            // on below line we are adding modifier to our button.
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            // on below line we are adding text for our button
            Text(text = "Update Data", modifier = Modifier.padding(8.dp))
        }
 
        // on below line we are adding a spacer.
        Spacer(modifier = Modifier.height(20.dp))
 
        // on below line we are creating a
        // text for displaying a response.
        Text(
            text = response.value,
            color = Color.Black,
            fontSize = 20.sp,
            fontWeight = FontWeight.Bold, modifier = Modifier
                .padding(10.dp)
                .fillMaxWidth(),
            textAlign = TextAlign.Center
        )
    }
}
 
 
private fun updateData(
    userName: String,
    job: String,
    ctx: Context,
    res: MutableState<String>
) {
    // on below line we are creating a variable for url.
    val url = "https://reqres.in/api/users/2"
 
    // creating a new variable for our request queue
    val queue = Volley.newRequestQueue(ctx)
 
    // making a string request to update our data and
    // passing method as PUT. to update our data.
    val request: StringRequest =
        object : StringRequest(Request.Method.PUT, url, object : Response.Listener<String?> {
            override fun onResponse(response: String?) {
 
                // on below line we are displaying a toast message as data updated.
                Toast.makeText(ctx, "Data Updated..", Toast.LENGTH_SHORT).show()
                try {
                    // on below line we are extracting data from our json object
                    // and passing our response to our json object.
                    val jsonObject = JSONObject(response)
 
                    // creating a string for our output.
                    val result =
                        "User Name : " + jsonObject.getString("name") + "\n" + "Job : " + jsonObject.getString(
                            "job"
                        ) + "\n" + "Updated At : " + jsonObject.getString("updatedAt")
 
                    // on below line we are setting
                    // our string to our text view.
                    res.value = result
                } catch (e: JSONException) {
                    e.printStackTrace()
                }
            }
        }, object : Response.ErrorListener {
            override fun onErrorResponse(error: VolleyError?) {
                // displaying toast message on response failure.
                Log.e("tag", "error is " + error!!.message)
                Toast.makeText(ctx, "Fail to update data..", Toast.LENGTH_SHORT)
                    .show()
            }
        }) {
            override fun getParams(): Map<String, String>? {
 
                // below line we are creating a map for storing
                // our values in key and value pair.
                val params: MutableMap<String, String> = HashMap()
 
                // on below line we are passing our key
                // and value pair to our parameters.
                params["name"] = userName
                params["job"] = job
 
                // at last we are
                // returning our params.
                return params
            }
        }
    // below line is to make
    // a json object request.
    queue.add(request)
}

Ahora ejecute su aplicación para ver el resultado. 

Producción:

Publicación traducida automáticamente

Artículo escrito por chaitanyamunje y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *