Computer >> Máy Tính >  >> Xử lý sự cố >> Android

Cách bao gồm một trình tải API trong ứng dụng Android của bạn

Nếu bạn là nhà phát triển ứng dụng, đôi khi bạn muốn bao gồm một API web để tìm nạp dữ liệu nhằm cung cấp cho người dùng của mình. Việc này không quá khó và có thể thực hiện bằng XML hoặc JSON. Vì vậy, trong hướng dẫn này, chúng tôi sẽ chỉ cho bạn cách tạo một trình tìm nạp dữ liệu API web đơn giản vào ứng dụng Android của bạn.

Đối với hướng dẫn này, chúng tôi sẽ sử dụng JSON thay vì XML.

Viết mã trong JSON

Trước tiên, hãy tạo một tệp XML dạng xem danh sách mới, với mã sau:

      Tiếp theo tạo một tệp XML mới và đây là nơi bạn sẽ liệt kê các phần tử bạn muốn hiển thị (ImageView, TextView, v.v.)         

Để tìm nạp dữ liệu từ API, chúng ta cần phải đi đến hoạt động chính và chúng ta cần sử dụng AsyncTask vì không thể tìm nạp API trên chuỗi chính. AsyncTask chỉ đơn giản là một luồng xử lý nền, đồng thời hiển thị kết quả trong giao diện người dùng. Việc sử dụng chuỗi chính cho các quy trình mạng thường sẽ làm ứng dụng của bạn gặp sự cố. Nếu điều đó nghe có vẻ hơi khó hiểu, hãy xem một số hướng dẫn API chuyên sâu trên RapidAPI.

 class DownloadFilesTask mở rộng AsyncTask  {hộp thoại ProgressDialog riêng cuối cùng =new ProgressDialog (MainActivity.this); @ Overrideprotected void onPreExecute () {super.onPreExecute (); this.dialog.setMessage ("Đăng nhập ... "); this.dialog.show ();} @ Overrideprotected String doInBackground (Void ... params) {ServiceHandler sh =new ServiceHandler (); String jsonStr =sh.makeServiceCall (" https://jsonplaceholder.typicode .com / album / ", ServiceHandler.GET); Log.d (" res1 ", jsonStr); return jsonStr;} @ Overrideprotected void onPostExecute (Chuỗi phản hồi) {super.onPostExecute (phản hồi); Log.d (" res2 " , response); speech.dismiss (); if (response! =null) {try {JSONArray arr =new JSONArray (response); DataModel mDatModel =new DataModel (); for (int i =0; i  id_array =new ArrayList  (); ArrayList  notification_array =new ArrayList  (); Nút b1; ListView l; private cuối cùng static String SERVICE_URI ="https://jsonplaceholder.typicode.com/albums/"; private static final String TAG_QUESTIONS ="Question"; private static final String USER_ID ="userId"; private static final String ID ="id"; private static final String TITLE ="title"; JSONArray question =null; protected void onSaveInstanceState (Gói outState) {super.onSaveInstanceState (outState);} protected void onRestoreInstanceState (Bundle saveInstanceState) {super.onRestoreInstanceState (saveInstanceState);} @ Overrideprotected void onCreate (Bundle đã lưuInstanceState) {super.onCreate (đã lưu) ty_main); l =(ListView) findViewById (R.id.list); new DownloadFilesTask (). execute (); l.setOnItemClickListener (new AdapterView.OnItemClickListener () {@ Overridepublic void onItemClick (AdapterView  parent, View view, int position, long id) {String abc =id_array.get (position); Toast.makeText (getBaseContext (), id_array.get (position), Toast.LENGTH_LONG) .show (); Intent n =new Intent (MainActivity.this, Titleshow.class); n.putExtra ("id", id_array.get (position)); startActivity (n);}});} @ Overridepublic void onItemClick (AdapterView  parent, View view, int position, long id) {} ​​

Bạn sẽ tìm thấy câu trả lời trong hoạt động chính của mình

 ServiceHandler sh =new ServiceHandler (); String jsonStr =sh.makeServiceCall ("https://jsonplaceholder.typicode.com/albums/", ServiceHandler.GET); đây không phải là lớp xử lý dịch vụ để yêu cầu và nhận trả lời từ api web, vì vậy chúng tôi sẽ thực hiện tất cả việc này từ web api.ServiceHandler.javaclass ServiceHandler {static String response =null; public final static int GET =1; public final static int POST =2; public ServiceHandler () {} / ** * Thực hiện lệnh gọi dịch vụ ** @url - url để thực hiện yêu cầu * @method - phương thức yêu cầu http * / public String makeServiceCall (String url, int method) {return this.makeServiceCall (url, method, null);} / *** Thực hiện lệnh gọi dịch vụ ** @url - url để thực hiện yêu cầu * @method - http request method * @params - http request params * / public String makeServiceCall (String url, int method, List  params) {try {// http clientDefaultHttpClient httpClient =new DefaultHttpClient (); HttpEntity httpEntity =null; HttpResponse httpResponse =null; // Kiểm tra phương thức yêu cầu http typeif (phương thức ==POST) {HttpPost httpPost =new HttpPost (url); // thêm post paramsif (params! =Null) {httpPost.setEntity (new UrlEncodedFormEntity (params));} httpResponse =httpClient.execute (httpPost);} else if (method ==GET) {// thêm các tham số vào urlif (params! =null) {String paramString =URLEncodedUtils.format (params, "utf-8"); url + ="?" + paramString;} HttpGet httpGet =new HttpGet (url); httpResponse =httpClient.execute (httpGet);} httpEntity =httpResponse.getEntity (); response =EntityUtils.toString (httpEntception);} catch (Unsupported) ();} catch (ClientProtocolException e) {e.printStackTrace ();} catch (IOException e) {e.printStackTrace ();} trả về phản hồi;}} 

Tiếp theo trong asyncTask của bạn, bạn sẽ tìm thấy một lớp Bộ điều hợp, lớp này sẽ đặt phương thức bộ điều hợp, nhưng để làm được điều này, chúng tôi cần tạo một bộ điều hợp tùy chỉnh.

 public class AAdapter mở rộng BaseAdapter {private Activity activity; // private ArrayList > data; private static ArrayList title; private static LayoutInflater Inflater =null; public AAdapter (Activity a, ArrayList b) {activity =a; this.title =b; Inflater =(LayoutInflater) activity.getSystemService (Context.LAYOUT_INFLATER_SERVICE);} public int getCount () {return title.size ();} public Object getItem (int position) {return position;} public long getItemId (int position) {return position;} public View getView (int position, View convertView, ViewGroup parent) {View vi =convertView; if (convertView ==null) vi =Inflater.inflate (R.layout.abcd, null); TextView title2 =(TextView) vi.findViewById (R.id.txt_ttlsm_row); // titleString song =title.get (position) .toString (); title2.setText (song); TextView title22 =(TextView) vi.findViewById (R.id.txt_ttlcontact_row2); // messageString song2 =title.get (position) .toString (); title22.setText (song2); return vi;}} 

Chúng ta cần nhớ rằng lớp bộ điều hợp được coi là lớp trừu tượng trong Android, vì vậy chúng ta cần triển khai tất cả các phương thức. Trong đoạn mã bên dưới, phương thức getview rất quan trọng, vì chúng tôi sẽ thêm nhiều mã vào đó để hiển thị tệp XML thứ hai.

 Inflater =(LayoutInflater) activity.getSystemService (Context.LAYOUT_INFLATER_SERVICE); 

Và chúng tôi cũng sẽ cần một lớp Bộ điều hợp cho Tải hình ảnh để trình tìm nạp API có thể tải hình ảnh từ internet.

 public class MyAdapter mở rộng BaseAdapter {ImageLoader imageLoader; private Context ctx; ArrayList  list; public MyAdapter (Context ctx, ArrayList  mDataList) {list =mDataList; this.ctx =ctx;} public int getCount ( ) {return list.size ();} public Object getItem (int position) {return position;} public long getItemId (int position) {return position;} public View getView (int position, View convertView, ViewGroup parent) {// View vi =convertView; ViewHolder viewHolder; if (convertView ==null) {LayoutInflater vi =(LayoutInflater) ctx.getSystemService (Context.LAYOUT_INFLATER_SERVICE); convertView =vi.inflate (R.layout.abcde, null); viewHolder =new ViewHolder (); viewHolder.imageView =(ImageView) convertView.findViewById (R.id.image); viewHolder.textView =(TextView) convertView.findViewById (R.id.txt_ttlsm_row); convertView.setTag (viewHolder);} else {viewHolder =(ViewHolder) convertView.getTag ();} Dữ liệu AlbumData =list.get (vị trí); String a =data.getThumbnailUrl (); if (data! =Null) { viewHolder.textView.setText (data.getTitle ()); String url =a; Glide.with (ctx) .load (url) .centerCrop (). placeholder (R.drawable.abhi) .crossFade (). into (viewHolder .imageView); / * Picasso.with (ctx) .load ("https://preview.keenthemes.com/conquer/assets/plugins/jcrop/demos/demo_files/image2.jpg") .into (viewHolder.imageView); * // * ImageLoader imageLoader =ImageLoader.getInstance (); imageLoader.displayImage ("https://www.keenthemes.com/preview/conquer/assets/plugins/jcrop/demos/demo_files/image1.jpg", viewHolder. imageView); * /} return convertView;} public class ViewHolder {ImageView imageView; TextView textView;} 

Chúng tôi đã thêm một nhận xét mã thực sự chỉ là một gợi ý cho trình tải hình ảnh Picasso, đây là một trình tải xuống hình ảnh mã nguồn mở và thư viện bộ nhớ đệm mạnh mẽ dành cho Android và giữ một dấu ấn nhẹ trong ứng dụng của bạn. Tuy nhiên, bạn cũng có thể sử dụng trình tải hình ảnh Glide để tùy chỉnh nhiều hơn, vì nó cung cấp hỗ trợ GIF và quản lý bộ nhớ tốt hơn.

 public class ViewHolder {ImageView imageView; TextView textView;} 

Những gì lớp người giữ chế độ xem làm là tạo một phiên bản tĩnh của ViewHolder, sau đó đính kèm nó vào mục chế độ xem trong lần tải đầu tiên. Sau đó, nó sẽ được truy xuất từ ​​thẻ xem trong các cuộc gọi trong tương lai.

Phương thức getView () được gọi rất nhiều chẳng hạn như khi có nhiều phần tử trong ListView. Vì vậy, chúng tôi sẽ triển khai một lớp mô hình dữ liệu cho phương thức set và get, điều này sẽ giúp bạn lấy phần tử của danh sách mảng và chỉ làm cho cuộc sống của bạn dễ dàng hơn trong tương lai.

 public class AlbumData {int albumId; int id; String title; String url; String thumbnailUrl; public int getAlbumId () {return albumId;} public void setAlbumId (int albumId) {this.albumId =albumId;} public int getId () {return id;} public void setId (int id) {this.id =id;} public String getTitle () {return title;} public void setTitle (String title) {this.title =title;} public String getUrl () {return url;} public void setUrl (String url) {this.url =url;} public String getThumbnailUrl () {return thumbnailUrl;} public void setThumbnailUrl (String thumbnailUrl) {this.thumbnailUrl =thumbnailUrl;}}  

Đó là mọi thứ bạn cần lúc này. Bạn có thể kiểm tra đầu ra của trình tìm nạp API này trong trình giả lập ứng dụng như BlueStacks.