📌  相关文章
📜  如何在Android中使用Volley更新API中的数据?

📅  最后修改于: 2021-05-13 16:20:40             🧑  作者: Mango

先决条件

  • 使用Volley Library在Android中进行JSON解析
  • 如何在Android中使用Volley将数据发布到API?

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

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

我们将构建一个简单的应用程序,在其中将显示一个简单的表单,并使用该表单来更新数据并将其传递给API以更新该数据。我们将使用PUT请求和排球库将我们的数据更新为API。下面提供了一个示例视频,以使您对我们在本文中将要做的事情有个大概的了解。注意,我们将使用Java语言实现该项目。

分步实施

步骤1:创建一个新项目

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

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

以下是Volley的依赖关系,我们将使用它们来从API获取数据。要添加此依赖关系,请导航至应用程序> Gradle脚本> build.gradle(app),然后在“依赖关系”部分添加以下依赖关系。

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

步骤3:在AndroidManifest.xml文件中向Internet添加权限

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

XML


XML



      
    
    
  
    
    
  
    
    


Java
import android.os.Bundle;
import android.text.TextUtils;
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 com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
  
import org.json.JSONException;
import org.json.JSONObject;
  
import java.util.HashMap;
import java.util.Map;
  
public class MainActivity extends AppCompatActivity {
  
    // 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 name, String job) {
          
        // making our progress bar visible.
        loadingPB.setVisibility(View.VISIBLE);
          
        // url for updating our data
        // in below url 2 is the identity at which 
        // we will be updating our data.
        String url = "https://reqres.in/api/users/2";
          
        // creating a new variable for our request queue
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
          
        // making a string request to update our data and 
        // passing method as PUT. to update our data.
        StringRequest request = new StringRequest(Request.Method.PUT, url, new Response.Listener() {
            @Override
            public void onResponse(String response) {
                  
                // hiding our progress bar.
                loadingPB.setVisibility(View.GONE);
                  
                // inside on response method we are
                // setting our edit text to empty.
                jobEdt.setText("");
                userNameEdt.setText("");
                  
                // on below line we are displaying a toast message as data updated.
                Toast.makeText(MainActivity.this, "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.
                    JSONObject jsonObject = new JSONObject(response);
                      
                    // creating a string for our output.
                    String output = jsonObject.getString("name") + "\n" + jsonObject.getString("job") + "\n" + jsonObject.getString("updatedAt");
                      
                    // on below line we are setting 
                    // our string to our text view.
                    responseTV.setText(output);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // displaying toast message on response failure.
                Toast.makeText(MainActivity.this, "Fail to update data..", Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map getParams() {
                 
                // below line we are creating a map for storing
                // our values in key and value pair.
                Map params = new HashMap();
                  
                // on below line we are passing our key
                // and value pair to our parameters.
                params.put("name", name);
                params.put("job", job);
                  
                // at last we are 
                // returning our params.
                return params;
            }
        };
        // below line is to make 
        // a json object request.
        queue.add(request);
    }
}


步骤4:使用activity_main.xml文件

导航到应用程序> res>布局> activity_main.xml,然后将以下代码添加到该文件中。以下是activity_main.xml文件的代码

XML格式




      
    
    
  
    
    
  
    
    

步骤5:使用MainActivity。 Java文件

转到MainActivity。 Java文件并参考以下代码。下面是MainActivity的代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。

Java

import android.os.Bundle;
import android.text.TextUtils;
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 com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
  
import org.json.JSONException;
import org.json.JSONObject;
  
import java.util.HashMap;
import java.util.Map;
  
public class MainActivity extends AppCompatActivity {
  
    // 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 name, String job) {
          
        // making our progress bar visible.
        loadingPB.setVisibility(View.VISIBLE);
          
        // url for updating our data
        // in below url 2 is the identity at which 
        // we will be updating our data.
        String url = "https://reqres.in/api/users/2";
          
        // creating a new variable for our request queue
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
          
        // making a string request to update our data and 
        // passing method as PUT. to update our data.
        StringRequest request = new StringRequest(Request.Method.PUT, url, new Response.Listener() {
            @Override
            public void onResponse(String response) {
                  
                // hiding our progress bar.
                loadingPB.setVisibility(View.GONE);
                  
                // inside on response method we are
                // setting our edit text to empty.
                jobEdt.setText("");
                userNameEdt.setText("");
                  
                // on below line we are displaying a toast message as data updated.
                Toast.makeText(MainActivity.this, "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.
                    JSONObject jsonObject = new JSONObject(response);
                      
                    // creating a string for our output.
                    String output = jsonObject.getString("name") + "\n" + jsonObject.getString("job") + "\n" + jsonObject.getString("updatedAt");
                      
                    // on below line we are setting 
                    // our string to our text view.
                    responseTV.setText(output);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // displaying toast message on response failure.
                Toast.makeText(MainActivity.this, "Fail to update data..", Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map getParams() {
                 
                // below line we are creating a map for storing
                // our values in key and value pair.
                Map params = new HashMap();
                  
                // on below line we are passing our key
                // and value pair to our parameters.
                params.put("name", name);
                params.put("job", job);
                  
                // at last we are 
                // returning our params.
                return params;
            }
        };
        // below line is to make 
        // a json object request.
        queue.add(request);
    }
}

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

输出: