如何在 Android 中使用 Volley 进行同步请求?
什么是 Android 中的同步请求
在 Android 应用中使用 Volley 进行同步请求对于希望从服务器检索数据并能够立即在其应用程序中使用它的开发者来说非常有用。这对于从远程服务器加载图像或数据等任务很有用。在本文中,我们将讨论如何在 Android 应用中使用 Volley 进行同步请求。
在 Android 中实现同步请求
我们将创建一个简单的应用程序,其中我们将简单地显示两个 TextView。在第一个 TextView 中,我们将显示应用程序的标题,在第二个 TextView 中,我们将显示 API 调用的响应。
步骤 1:在 Android Studio 中创建一个新项目
导航到 Android Studio,如下面的屏幕所示。在下面的屏幕中,单击“新建项目”以创建一个新的 Android Studio 项目。
单击“新建项目”后,您将看到下面的屏幕。
在此屏幕中,我们只需选择“空活动”并单击“下一步”。单击“下一步”后,您将看到下面的屏幕。
在此屏幕中,我们只需指定项目名称。然后包名将自动生成。
注意 - 确保将语言选择为 Java。指定所有详细信息后,单击“完成”以创建一个新的 Android Studio 项目。
创建项目后,我们将看到两个打开的文件,即 activity_main.xml 和 MainActivity.java 文件。
步骤 2:在 build.gradle 文件中添加依赖项以使用此库
导航到 Gradle Scripts > build.gradle 文件,并在 dependencies 部分添加以下依赖项。
implementation 'com.android.volley:volley:1.2.1'
在 dependencies 部分,我们将添加一个依赖项,该依赖项用于从 API 调用获取数据以将其加载到我们的应用程序中。
添加上述依赖项后,您将在 IDE 的右上角看到“立即同步”选项。只需单击它即可同步您的项目并在您的项目中安装此依赖项。
步骤 3:使用 activity_main.xml
导航到 activity_main.xml。如果此文件不可见,则要打开此文件。在左侧窗格中导航到 app > res > layout > activity_main.xml 以打开此文件。打开此文件后,将以下代码添加到其中。代码中添加了注释以详细了解。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<!-- on below line creating a text view for displaying a heading-->
<TextView
android:id="@+id/idTVHeading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@id/idTVMsg"
android:layout_margin="10dp"
android:padding="4dp"
android:text="Synchronous Request in Android App with Volley"
android:textAlignment="center"
android:textColor="@color/black"
android:textSize="20sp"
android:textStyle="bold" />
<!-- on below line creating a text view for displaying a message from API call-->
<TextView
android:id="@+id/idTVMsg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textAlignment="center"
android:textColor="@color/black"
android:textSize="18sp" />
</RelativeLayout>
说明 - 在上面的代码中,根元素是 Android 中的 RelativeLayout。此布局是一个视图组,用于相对于彼此对齐其中的所有元素。我们可以借助 ID 或位置在 RelativeLayout 中相对对齐所有元素。
在此 RelativeLayout 中,我们创建了两个 TextView。第一个 TextView 用于显示应用程序的标题。在第二个 TextView 中,我们将显示应用程序中 API 调用的响应。
步骤 4:在 AndroidManifest.xml 文件中添加互联网权限
由于我们正在使用 URL 从互联网获取数据,因此我们必须在我们的 Android 应用程序中添加互联网权限以访问互联网以加载此数据。因此,我们必须添加互联网权限。要添加互联网权限,请导航到 app > AndroidManifest.xml 文件,并在 application 标记上方添加以下权限。
<uses-permission android:name="android.permission.INTERNET"/>
步骤 7:使用 MainActivity.java
导航到 MainActivity.java。如果此文件不可见,则要打开此文件。在左侧窗格中导航到 app > java > 您的应用程序的包名 > MainActivity.java 以打开此文件。打开此文件后,将以下代码添加到其中。代码中添加了注释以详细了解。
package com.example.androidjavaapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
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.JsonObjectRequest;
import com.android.volley.toolbox.RequestFuture;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
// on below line creating a variables
private TextView msgTV;
String url = "https://www.jsonkeeper.com/b/N6XK";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// on below line initializing web view with id.
msgTV = findViewById(R.id.idTVMsg);
// on below line we are making a json object request and specifying the method name as get, url on which we are making request
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// in on response method we are setting response data to our text view.
try {
msgTV.setText(response.getString("message"));
} catch (JSONException e) {
// on below line handling error.
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// on below line displaying toast message for error.
Toast.makeText(MainActivity.this, "Error : " + error, Toast.LENGTH_SHORT).show();
}
});
// on below line adding request to volley request queue.
Volley.newRequestQueue(getApplicationContext()).add(jsonObjectRequest);
}
}
说明 - 在上面针对 MainActivity.java 文件的代码中。首先,我们为 TextView 创建一个变量,在其中显示文本消息。之后,我们为字符串创建一个变量,在其中添加一个 URL,通过该 URL 我们将获取 JSON 响应。
现在我们将看到 onCreate 方法。这是每个 Android 应用程序的默认方法。创建应用程序视图时会调用此方法。在此方法内部,我们设置内容视图,即名为 activity_main.xml 的布局文件,以从此文件中设置 UI。
指定视图后,我们使用我们在 activity_main.xml 文件中给出的唯一 ID 初始化 TextView。
初始化变量后,我们进行 JSON 对象请求。在此方法中,我们发出 GET 请求并传递要对其发出请求的 URL。在 onResponse 方法中,我们解析 JSON 响应并将其设置为 TextView。之后,我们还创建了一个错误侦听器方法。在其中,当接收到任何错误时,我们显示一个 Toast 消息。最后,我们将此 JSON 对象请求添加到队列以执行它。
添加上述代码后,现在我们只需单击顶栏中的绿色图标即可在移动设备上运行我们的应用程序。
注意 - 确保您已连接到您的真实设备或模拟器。
输出
结论
在上面的教程中,我们了解了如何使用 Volley 作为库在 Android 应用程序中进行同步请求。
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP