کتابخانه volley بهترین کتابخانه برای ارتباط با سرور در اندروید می باشد . در این پست از آموزش ارتباط با سرور در اندروید به معرفی کتابخانه volley می پردازیم ، برای درک بهتر مطلب سعی شده طی مثالی ساده نحوه استفاده کتابخانه volley آموزش داده شود. برای پیاده سازی این پروژه نیاز به داده هایی از نوع JSON می باشد تا از طریق یک لینک وب قابل خواندن باشد و برای خواندن این داده ها ما از کتابخانه volley استفاده خواهیم کرد:
ارتباط با سرور در اندروید :
کتابخانه volley چیست؟
کتابخانه volley کتابخانه ای است که اپلیکیشن ها از آن برای برقراری ارتباط با سرور در اندروید استفاده می کنند . از مزایای این کتابخانه سرعت و سهولت در مرتبط کردن اپلیکیشن در یک شبکه داخلی یا اینترنت است.
دلایل استفاده از کتابخانه volley برای ارتباط با سرور در اندروید ؟
Volley فرآیند ارتباط با سرور در اندروید را آسان می کند :
- مدیریت درخواست ها ی ارتباط با سرور در اندروید به راحتی قابل انجام است
- مدیریت شبکه به صورت کارآمد و بهینه
- قابلیت سفارشی سازی با توجه به نیاز های اپلیکیشن
آموزش کتابخانه volley
برای استفاده از کتابخانه volley در اندروید ما نیاز به یک مسیر وب که شامل داده های JSON باشد داریم . مسیر زیر یک خروجی JSON را در اختیار شما قرار می دهد:
https://acdev.ir/wp-content/project/json/CarApp.json
از URL بالا می توانید در پروژه خود استفاده کنید . در این ساختار JSON ، اطلاعات خودرو ها شامل نام خودرو و مسیر قرار گیری تصویر را قرار داده ایم که از آن برای نمایش در اپلیکیشن اندروید استفاده می شود. هدف ما در این مثال خواندن اطلاعات بالا در اپلیکیشن و نمایش انها در List View است.
ایجاد پروژه جدید در اندروید استدیو
- در ایتدا یک پروژه اندروید با نام CarApp ایجاد می کنیم ، نام پروژه اهمیتی ندارد اما حتما یک اکتیوتی از نوع Empty Activity به پروژه اضافه کنید.
- بعد از اینکه پروژه ایجاد شد به فایل AndroidManifest رفته و مجوز دسترسی به شبکه را در این فایل اعلام کنید.
مجوز دسترسی به اینترنت
فایل AndroidManifest.xml باز کرده و مجوز دسترسی به اینترنت را مطابق کد زیر در آن وارد کنید.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.azarniva.carapp"> <!-- افزودن مجوز اینترنت --> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
افوزدن کتابخانه volley
در این قسمت نحوه اضافه کردن کتابخانه volley به یک پروژه اندروید را شرح می دهیم
- ابتدا فایل build.gradle را در app level باز کنید .
- حال در این فایل کد زیر را که کتابخانه را به پروژه معرفی می کند اضافه کنید:
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) //افزودن کتابخانه Volley compile 'com.android.volley:volley:1.0.0' testCompile 'junit:junit:4.12' }
ایجاد کلاس Data Model :
برای ذخیره اطلاعات خوانده شده در یک شئی ما نیاز به ایجاد یک کلاس ساده داریم به همین جهت کلاس جاوا با نام Car ایجاد کرده و کدهای زیر را در آن تایپ کنید :
package com.example.azarniva.carapp; /** * Created by azarniva on 14/10/2017. */ public class Car { String name, imageUrl; public Car(String name, String imageUrl) { this.name = name; this.imageUrl = imageUrl; } public String getName() { return name; } public String getImageUrl() { return imageUrl; } }
- هدف از ایجاد کلاس بالا خواندن اطلاعات از ساختار JSon و ریختن آنها در اشیائی از این کلاس است .
- در این کلاس یک سازنده برای مقدار دهی اولیه اطلاعات و متدهای getters برای خواندن این مقادیر است.
ایجاد ListView
- هماگونه که قبلا عنوان شد داده های خوانده شده از JSon را در ListView نمایش خواهیم داد و در این قسمت قصد داریم یک ListView سفارشی ایجاد کنیم
- ابتدا فایل activity_main.xml را باز کرده و یک ListView و یک Progress Bar را به آن اضافه کنید ، Progress Bar برای نمایش لود شدن اطلاعات هنگام خواندن اطلاعات از JSon کاربرد دارد
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.azarniva.carapp.MainActivity"> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="match_parent" /> <ProgressBar android:visibility="gone" android:id="@+id/progressBar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" /> </RelativeLayout>
در قسمت بعد نحوه ایجاد یک لایوت برای آیتم های List View را نمایش خواهیم داد:
ایجاد لایوت سفارشی برای آیتم های List View
در داخل پوشه لایوت (res->layout) یک فایل لایوت با نام list_items.xml ایجاد کنید .
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textViewName" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="@android:style/TextAppearance.DeviceDefault.Large" /> <TextView android:id="@+id/textViewImageUrl" android:layout_width="match_parent" android:layout_height="wrap_content" android:autoLink="web" android:textColor="#08308e" /> </LinearLayout>
همانطور که می بینید ۲ تا Text Views برای نمایش اطلاعات استخراج شده از داده های JSon در این لایوت اضافه شده اند.
ایجاد Adapter سفارشی
- زمانیکه که نیاز به ایجاد List View سفارشی دارید باید یک Array Adapter سفارشی شده برای آن ایجاد کنید .
- برای این منظور یک کلاس جدید با نام ListViewAdapter.java ایجاد کرده و کدهای زیر را در آن وارد کنید :
package com.example.azarniva.carapp; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.List; /** * Created by azarniva on 14/10/2017. */ public class ListViewAdapter extends ArrayAdapter<Car>{ //لیت خودروهایی که نمایش داده خواهد شد private List<Car> CarList; //the context object private Context mCtx; //here we are getting the herolist and context //so while creating the object of this adapter class we need to give herolist and context public ListViewAdapter(List<Car> CarList, Context mCtx) { super(mCtx, R.layout.list_items, CarList); this.CarList = CarList; this.mCtx = mCtx; } //this method will return the list item @Override public View getView(int position, View convertView, ViewGroup parent) { //getting the layoutinflater LayoutInflater inflater = LayoutInflater.from(mCtx); //creating a view with our xml layout View listViewItem = inflater.inflate(R.layout.list_items, null, true); //getting text views TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName); TextView textViewImageUrl = (TextView) listViewItem.findViewById(R.id.textViewImageUrl); //Getting the car for the specified position Car hero = CarList.get(position); //setting car values to textviews textViewName.setText(hero.getName()); textViewImageUrl.setText(hero.getImageUrl()); //returning the listitem return listViewItem; } }
و در آخرین قسمت این آموزش داده های JSon را استخراج کرده و آنها را در Listview نمایش می دهیم
استخراج و خواندن Json با استفاده از کتابخانه volley
حال به سراغ فایل MainActivity.java رفته و کدهای زیر را د رآن کپی کنید :
package com.example.azarniva.carapp; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.ListView; import android.widget.ProgressBar; 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.StringRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class MainActivity extends Activity { //the URL having the json data private static final String JSON_URL = "https://acdev.ir/wp-content/project/json/CarApp.json"; //listview object ListView listView; //the car list where we will store all the hero objects after parsing json List<Car> carList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //initializing listview and car list listView = (ListView) findViewById(R.id.listView); carList = new ArrayList<>(); //this method will fetch and parse the data loadCarList(); } private void loadCarList() { //getting the progressbar final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar); //making the progressbar visible progressBar.setVisibility(View.VISIBLE); //creating a string request to send request to the url StringRequest stringRequest = new StringRequest(Request.Method.GET, JSON_URL, new Response.Listener<String>() { @Override public void onResponse(String response) { //hiding the progressbar after completion progressBar.setVisibility(View.INVISIBLE); try { //getting the whole json object from the response JSONObject obj = new JSONObject(response); //we have the array named car inside the object //so here we are getting that json array JSONArray carArray = obj.getJSONArray("Cars"); //now looping through all the elements of the json array for (int i = 0; i < carArray.length(); i++) { //getting the json object of the particular index inside the array JSONObject carObject = carArray.getJSONObject(i); //creating a car object and giving them the values from json object Car car = new Car(carObject.getString("name"), carObject.getString("imageurl")); //adding the car to carlist carList.add(car); } //creating custom adapter object ListViewAdapter adapter = new ListViewAdapter(carList, getApplicationContext()); //adding the adapter to listview listView.setAdapter(adapter); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //displaying the error in toast if occurrs Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); } }); //creating a request queue RequestQueue requestQueue = Volley.newRequestQueue(this); //adding the string request to request queue requestQueue.add(stringRequest); } }
در انتهای App را اجرا ء کرده و نتیجه نهایی را بررسی کنید.
من محمد آذرنیوا، نویسنده و مدرس دوره های برنامه نویسی ، طراحی وب و تحلیل گر پایگاه داده هستم و قصد دارم در این وبسایت مطالب کاربردی در این زمینه را با شما به اشتراک بگذارم …