📜  如何在 Android 中使用 Retrofit 更新 API 中的数据?

📅  最后修改于: 2022-05-13 01:54:59.383000             🧑  作者: Mango

如何在 Android 中使用 Retrofit 更新 API 中的数据?

我们已经看到在 API 的帮助下从 API 读取数据以及将数据发布到我们的数据库。在本文中,我们将看看更新 API 中的数据。我们将使用 Retrofit 库来更新我们 API 中的数据。

我们将在本文中构建什么?

我们将构建一个简单的应用程序,在该应用程序中我们将显示一个简单的表单,并使用该表单更新我们的数据并将其传递给我们的 API 以更新该数据。我们将使用 PUT 请求和 Retrofit 库来更新我们的数据到 API。下面给出了一个示例视频,以了解我们将在本文中做什么。请注意,我们将使用Java语言来实现这个项目。

分步实施

第 1 步:创建一个新项目

要在 Android Studio 中创建新项目,请参阅如何在 Android Studio 中创建/启动新项目。请注意,选择Java作为编程语言。

第 2 步:在 build.gradle 文件中添加以下依赖项



下面是我们将用来从 API 获取数据的 Volley 的依赖项。要添加此依赖项,请导航到app > Gradle Scripts > build.gradle(app)并在依赖项部分添加以下依赖项。

// below dependancy for using retrofit.
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'

添加此依赖项后,同步您的项目,现在转向 AndroidManifest.xml 部分。

第 3 步:在 AndroidManifest.xml 文件中添加互联网权限

导航到应用程序 > AndroidManifest.xml并将以下代码添加到其中。

XML



XML


  
    
    
  
    
    
  
    
    


Java
package com.gtappdevelopers.gfg;
  
public class DataModal {
    // string variables for name and job.
    private String name;
    private String job;
  
    public DataModal(String name, String job) {
        this.name = name;
        this.job = job;
    }
  
    // creating getter and setter methods. 
    public String getName() {
        return name;
    }
  
    public void setName(String name) {
        this.name = name;
    }
  
    public String getJob() {
        return job;
    }
  
    public void setJob(String job) {
        this.job = job;
    }
}


Java
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);
}


Java
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 = "https://reqres.in/";
      
    // 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()) && TextUtils.isEmpty(jobEdt.getText().toString())) {
                      
                    // displaying a toast message if the edit text is empty.
                    Toast.makeText(MainActivity.this, "Please enter your data..", Toast.LENGTH_SHORT).show();
                    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());
            }
        });
    }
}


步骤 4:使用 activity_main.xml 文件

导航到app > res > layout > activity_main.xml并将以下代码添加到该文件中。下面是activity_main.xml文件的代码。

XML





  
    
    
  
    
    
  
    
    

第 5 步:创建一个模态类来存储我们的数据

导航到应用程序 > Java > 您应用程序的包名称 > 右键单击它 > 新建 > Java类并将其命名为DataModal并将以下代码添加到其中。代码中添加了注释,以便更详细地了解。

Java

package com.gtappdevelopers.gfg;
  
public class DataModal {
    // string variables for name and job.
    private String name;
    private String job;
  
    public DataModal(String name, String job) {
        this.name = name;
        this.job = job;
    }
  
    // creating getter and setter methods. 
    public String getName() {
        return name;
    }
  
    public void setName(String name) {
        this.name = name;
    }
  
    public String getJob() {
        return job;
    }
  
    public void setJob(String job) {
        this.job = job;
    }
}

第 6 步:为我们的 API 调用创建一个接口类

导航到应用程序 > Java > 您应用程序的包名称 > 右键单击它 > 新建 > Java类,将其选择为RetrofitAPI并将以下代码添加到其中。代码中添加了注释,以便更详细地了解。

Java

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);
}

第 7 步:使用 MainActivity。 Java文件

导航到应用程序 > Java > 您应用程序的包名称 > MainActivity。 Java文件并将以下代码添加到其中。代码中添加了注释,以便更详细地了解。

Java

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 = "https://reqres.in/";
      
    // 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()) && TextUtils.isEmpty(jobEdt.getText().toString())) {
                      
                    // displaying a toast message if the edit text is empty.
                    Toast.makeText(MainActivity.this, "Please enter your data..", Toast.LENGTH_SHORT).show();
                    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());
            }
        });
    }
}

现在运行您的应用程序并查看应用程序的输出。

输出: