簡體   English   中英

將Rest API集成到Android應用程序中

[英]Integrate Rest API Into Android Application

我正在創建一個需要從Web API獲取數據的Android應用程序。 我在localhost上運行帶有SQL Server數據庫的MVC Web API應用程序。 我想在我的應用程序中檢索數據並輸出到TextViews。 我是API調用的新手,我不確定我是否正確使用它。 源代碼如下

fragment2_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#D70B0D"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="5dp"
        android:text="@string/textView1"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#FFFFFF"
        android:textStyle="bold"/>

    <TextView
        android:id="@+id/txtId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/txtId"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#FFFFFF"
        android:layout_margin="23dp"/>

    <TextView
        android:id="@+id/txtName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/txtName"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#FFFFFF"
        android:layout_margin="23dp"/>

    <TextView
        android:id="@+id/txtBirth"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/txtBirth"
        android:textAppearance="?android:attr/textAppearanceMedium" 
        android:textColor="#FFFFFF"
        android:layout_margin="23dp"/>

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="5dp"
        android:text="@string/textView5"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#FFFFFF"
        android:textStyle="bold" />

     <TextView
        android:id="@+id/txtMedHis"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/txtMedHis"
        android:textAppearance="?android:attr/textAppearanceMedium" 
        android:textColor="#FFFFFF"
        android:layout_margin="23dp"/>

     <TextView
        android:id="@+id/txtMed"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/txtMed"
        android:textAppearance="?android:attr/textAppearanceMedium" 
        android:textColor="#FFFFFF"
        android:layout_margin="23dp"/>

     <TextView
        android:id="@+id/txtAler"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/txtAler"
        android:textAppearance="?android:attr/textAppearanceMedium" 
        android:textColor="#FFFFFF"
        android:layout_margin="23dp"/>

</LinearLayout>

Fragment2.java

package ie.itsligo.medication;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class Fragment2 extends Fragment {

    public final static String apiURL = "http://localhost:63607/api/person/1";

    TextView txtId;
    TextView txtName;
    TextView txtBirth;
    TextView txtMedHis;
    TextView txtMed;
    TextView txtAler;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment2_layout, container, false);

        String urlString = apiURL;

        new CallAPI().execute(urlString);

        txtId = (TextView) container.findViewById(R.id.txtId);
        txtName = (TextView) container.findViewById(R.id.txtName);

        return view;
    }

    private class CallAPI extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... params) {

            String urlString=params[0]; // URL to call
            String resultToDisplay = "";
            InputStream in = null;

            // HTTP Get
            try {

                URL url = new URL(urlString);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                in = new BufferedInputStream(urlConnection.getInputStream());

                StringBuilder sb = new StringBuilder();

                String line = "";

                 BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                        while ((line=reader.readLine())!=null){
                            sb.append(line);
                        }
                        reader.close();
                String result = sb.toString();

                JSONObject jsonResult = new JSONObject(result);
                int id = jsonResult.getInt("ID");
                String name = jsonResult.getString("FullName");

                txtId.setText(id);
                txtName.setText(name);

            } catch (Exception e) {

                System.out.println(e.getMessage());
                return e.getMessage();

            }

            return resultToDisplay;
        }

    } // end CallAPI
}

AsyncTask方法doInBackground()在與UI的單獨線程上運行。 您不應該通過此方法進行任何更新UI的調用。 覆蓋AsyncTask中的onPostExecute(),並在此處調用任何更新UI的調用。
看一下AsyncTask文檔中的示例。

例如,在您的情況下:

private class CallAPI extends AsyncTask<String, String, String[]> {

        @Override
        protected String doInBackground(String... params) {
            String[] result = new String[2];
            ...
            result[0] = id;
            result[1] = name;
            return result;
        }

        @Override
        protected void onPostExecute(String[] result) {
            // Make any updates to your UI in here
            txtId.setText(result[0]);
            txtName.setText(result[1]);
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM