Skip to content
Related Articles

Related Articles

How to Post Data to API using Volley in Android using Jetpack Compose?

View Discussion
Improve Article
Save Article
  • Last Updated : 03 Aug, 2022
View Discussion
Improve Article
Save Article

APIs are used within Android Applications to interact with a database to perform various CRUD operations on data within the database such as adding new data, reading the existing data, and updating and deleting existing data. In this article, we will take a look at How to Post data to API in android using Volley in Jetpack Compose.

Note: If you are seeking Java code for Jetpack Compose, please note that Jetpack Compose is only available in Kotlin. It uses features such as coroutines, and the handling of @Composable annotations is handled by a Kotlin compiler. There is no method for Java to access these. Therefore, you cannot use Jetpack Compose if your project does not support Kotlin.

Step By Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. While choosing the template, select Empty Compose Activity. If you do not find this template, try upgrading the Android Studio to the latest version. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Add the below Dependency to your build.gradle File

Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section.  

implementation ‘com.android.volley:volley:1.1.1’

After adding this dependency sync your project and now move towards the AndroidManifest.xml part.  

Step 3: Adding Internet Permissions in the AndroidManifest.xml File

Navigate to the app > AndroidManifest.xml and add the below code to it.  

XML




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

Step 4: Adding a new color in the Color.kt file

Navigate to app > java > your app’s package name > ui.theme > Color.kt file and add the below code to it. 

Kotlin




import androidx.compose.ui.graphics.Color
 
val Purple200 = Color(0xFF0F9D58)
val Purple500 = Color(0xFF0F9D58)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
 
// in the below line, we are adding different colors.
val greenColor = Color(0xFF0F9D58)

Step 5: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code for further explanation.

Kotlin




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 {
                // in the below line, we are specifying background color for our application
                Surface(
                    // in the below line, we are specifying modifier and color for our app
                    modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background
                ) {
                    // in the 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(
 
                                        // in the below line, we are specifying text to display in top app bar.
                                        text = "Volley POST Request in Android",
 
                                        // in the below line, we are specifying modifier to fill max width.
                                        modifier = Modifier.fillMaxWidth(),
 
                                        // in the below line, we are specifying text alignment.
                                        textAlign = TextAlign.Center,
 
                                        // in the below line, we are specifying color for our text.
                                        color = Color.White
                                    )
                                })
                        }) {
                        // in the below line, we are calling pop window dialog method to display ui.
                        postDataUsingVolley()
                    }
                }
            }
        }
    }
}
 
@Composable
fun postDataUsingVolley() {
    // in the below line, we are creating a variable for our context
    val ctx = LocalContext.current
 
    // in the 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("")
    }
 
    // in the below line, we are creating a column.
    Column(
        // in the below line, we are adding a modifier to it
        // and setting max size, max height and max width
        modifier = Modifier
            .fillMaxSize()
            .fillMaxHeight()
            .fillMaxWidth(),
 
        // in the below line, we are adding vertical
        // arrangement and horizontal alignment.
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
 
        // in the below line, we are creating a text
        Text(
            // in the below line, we are specifying text as
            // Session Management in Android.
            text = "Volley POST Request in Android",
 
            // in the below line, we are specifying text color.
            color = greenColor,
 
            fontSize = 20.sp,
 
            // in the below line, we are specifying font family
            fontFamily = FontFamily.Default,
 
            // in the below line, we are adding font weight
            // and alignment for our text
            fontWeight = FontWeight.Bold, textAlign = TextAlign.Center
        )
 
        // in the below line, we are adding spacer
        Spacer(modifier = Modifier.height(5.dp))
 
        // in the below line, we are creating a text field for our email.
        TextField(
            // in the below line, we are specifying value for our email text field.
            value = userName.value,
 
            // in the below line, we are adding on value change for text field.
            onValueChange = { userName.value = it },
 
            // in the below line, we are adding place holder as text as "Enter your email"
            placeholder = { Text(text = "Enter your name") },
 
            // in the below line, we are adding modifier to it
            // and adding padding to it and filling max width
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth(),
 
            // in the below line, we are adding text style
            // specifying color and font size to it.
            textStyle = TextStyle(color = Color.Black, fontSize = 15.sp),
            // in the below line, we are adding single line to it.
            singleLine = true,
 
            )
 
        // in the below line, we are adding spacer
        Spacer(modifier = Modifier.height(5.dp))
 
        // in the below line, we are creating a text field for our email.
        TextField(
            // in the below line, we are specifying value for our email text field.
            value = job.value,
 
            // in the below line, we are adding on value change for text field.
            onValueChange = { job.value = it },
 
            // in the below line, we are adding place holder as text as "Enter your email"
            placeholder = { Text(text = "Enter your job") },
 
            // in the below line, we are adding modifier to it
            // and adding padding to it and filling max width
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth(),
 
            // in the below line, we are adding text style
            // specifying color and font size to it.
            textStyle = TextStyle(color = Color.Black, fontSize = 15.sp),
            // in the below line, we are adding single line to it.
            singleLine = true,
        )
 
        // in the below line, we are adding spacer
        Spacer(modifier = Modifier.height(10.dp))
 
        // in the below line, we are creating a button
        Button(
            onClick = {
                // in the below line, we are calling make payment method to update data.
                postData(
                    userName.value.text, job.value.text, ctx, response
                )
            },
            // in the below line, we are adding modifier to our button.
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            // in the below line, we are adding text for our button
            Text(text = "Post Data", modifier = Modifier.padding(8.dp))
        }
 
        // in the below line, we are adding a spacer.
        Spacer(modifier = Modifier.height(20.dp))
 
        // in the 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 postData(
    userName: String,
    job: String,
    ctx: Context,
    res: MutableState<String>
) {
    // in the below line, we are creating a variable for url.
    var url = "https://reqres.in/api/users"
 
    // 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.POST, url, object : Response.Listener<String?> {
            override fun onResponse(response: String?) {
 
                // in the below line, we are displaying a toast message as data updated.
                Toast.makeText(ctx, "Data Posted to API..", Toast.LENGTH_SHORT).show()
                try {
                    // in the 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"
                        )
                    // in the 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.
                Toast.makeText(ctx, "Fail to post data..", Toast.LENGTH_SHORT)
                    .show()
            }
        }) {
            override fun getParams(): Map<String, String>? {
 
                // in the below line, we are creating a map for storing
                // our values in key and value pair.
                val params: MutableMap<String, String> = HashMap()
 
                // in the 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)
}

Now run your application to see the output of it.

Output:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!