我们已经看到从 API 读取数据以及在 API 的帮助下将数据发布到我们的数据库。在本文中我们将了解如何在 API 中更新数据。我们将使用 Retrofit 库来更新 API 中的数据。
我们将在本文中构建什么
我们将构建一个简单的应用程序我们将在其中显示一个简单的表单并且使用该表单我们将更新我们的数据并将其传递给我们的 API 以更新该数据。我们将使用 PUT 请求和 Retrofit 库将我们的数据更新到 API。下面给出了一个示例视频以了解我们将在本文中做什么。请注意我们将使用Java语言来实现这个项目。
分步实施
第 1 步创建一个新项目
要在 Android Studio 中创建新项目请参阅如何在 Android Studio 中创建/启动新项目。请注意选择Java作为编程语言。
第 2 步在 build.gradle 文件中添加以下依赖项
下面是 Volley 的依赖项我们将使用它从 API 获取数据。要添加此依赖项请导航到app > Gradle Scripts > build.gradle(app)并在依赖项部分添加以下依赖项。
// below dependency for using retrofit.implementation com.squareup.retrofit2:retrofit:2.9.0implementation com.squareup.retrofit2:converter-gson:2.5.0
添加此依赖项后同步您的项目现在转到 AndroidManifest.xml 部分。
第 3 步在 AndroidManifest.xml 文件中添加互联网权限
导航到应用程序 > AndroidManifest.xml并将以下代码添加到其中。
XML
第 4 步使用 activity_main.xml 文件
导航到app > res > layout > activity_main.xml并将以下代码添加到该文件。下面是activity_main.xml文件的代码。
package com.gtappdevelopers.gfg; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.PUT; public interface RetrofitAPI { // as we are making a put request to update a data // so we are annotating it with put // and along with that we are passing a parameter as users PUT("api/users/2") // on below line we are creating a method to put our data. Call updateData(Body DataModal dataModal); }
package com.gtappdevelopers.gfg; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class MainActivity extends AppCompatActivity { String url "Reqres - A hosted REST-API ready to respond to your AJAX requests"; // creating our variables for our views such // as text view, button and progress // bar and response text view. private EditText userNameEdt, jobEdt; private Button updateBtn; private ProgressBar loadingPB; private TextView responseTV; Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our views with their ids. userNameEdt findViewById(R.id.idEdtUserName); jobEdt findViewById(R.id.idEdtJob); updateBtn findViewById(R.id.idBtnUpdate); loadingPB findViewById(R.id.idPBLoading); responseTV findViewById(R.id.idTVResponse); // adding on click listener for our button. updateBtn.setOnClickListener(new View.OnClickListener() { Override public void onClick(View v) { // checking if the edit text is empty or not. if (TextUtils.isEmpty(userNameEdt.getText().toString()) return; } // calling a method to update data in our API. callPUTDataMethod(userNameEdt.getText().toString(), jobEdt.getText().toString()); } }); } private void callPUTDataMethod(String userName, String job) { // below line is for displaying our progress bar. loadingPB.setVisibility(View.VISIBLE); // on below line we are creating a retrofit // builder and passing our base url Retrofit retrofit new Retrofit.Builder() .baseUrl(url) // as we are sending data in json format so // we have to add Gson converter factory .addConverterFactory(GsonConverterFactory.create()) // at last we are building our retrofit builder. .build(); // below the line is to create an instance for our retrofit api class. RetrofitAPI retrofitAPI retrofit.create(RetrofitAPI.class); // passing data from our text fields to our modal class. DataModal modal new DataModal(userName, job); // calling a method to create an update and passing our modal class. Call call retrofitAPI.updateData(modal); // on below line we are executing our method. call.enqueue(new Callback() { Override public void onResponse(Call call, Response response) { // this method is called when we get response from our api. Toast.makeText(MainActivity.this, "Data updated to API", Toast.LENGTH_SHORT).show(); // below line is for hiding our progress bar. loadingPB.setVisibility(View.GONE); // on below line we are setting empty // text to our both edit text. jobEdt.setText(""); userNameEdt.setText(""); // we are getting a response from our body and // passing it to our modal class. DataModal responseFromAPI response.body(); // on below line we are getting our data from modal class // and adding it to our string. String responseString "Response Code : " response.code() "\nName : " responseFromAPI.getName() "\n" "Job : " responseFromAPI.getJob(); // below line we are setting our string to our text view. responseTV.setText(responseString); } Override public void onFailure(Call call, Throwable t) { // setting text to our text view when // we get error response from API. responseTV.setText("Error found is : " t.getMessage()); } }); } }