परिचय
Volley एंड्रॉइड के लिए एक लोकप्रिय नेटवर्किंग लाइब्रेरी है जो HTTP अनुरोधों को सरल बनाती है। यह लेख एक साधारण GET अनुरोध के साथ StringRequest का उपयोग करना दिखाता है।
चरण-दर-चरण कार्यान्वयन
चरण 1: build.gradle में निर्भरता जोड़ें
dependencies {
implementation 'com.android.volley:volley:1.1.0'
// अन्य निर्भरताएं...
}चरण 2: लेआउट (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="30sp" />
</LinearLayout>चरण 3: MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView textView;
RequestQueue queue;
String URL = "https://www.mocky.io/v2/597c41390f0000d002f4dbd1";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.GET, URL,
response -> {
textView.setText(response);
Toast.makeText(this, response, Toast.LENGTH_LONG).show();
},
error -> Log.d("error", error.toString())
);
queue.add(request);
}
}चरण 4: AndroidManifest.xml में इंटरनेट अनुमति
<uses-permission android:name="android.permission.INTERNET" />
व्याख्या
RequestQueueअनुरोधों को प्रबंधित करता है।StringRequestGET अनुरोध बनाता है और प्रतिक्रिया को स्ट्रिंग के रूप में पार्स करता है।- सफलता पर `onResponse`, त्रुटि पर `onErrorResponse` कॉल होता है।
- यूआई थ्रेड पर प्रतिक्रिया स्वचालित रूप से वितरित की जाती है।
यह उदाहरण एक मॉक API से JSON प्रतिक्रिया प्राप्त करता है और इसे TextView में दिखाता है।