简体   繁体   English

将Rest API集成到Android应用程序中

[英]Integrate Rest API Into Android Application

I am creating an Android application that will need to get data from a Web API. 我正在创建一个需要从Web API获取数据的Android应用程序。 I am running a MVC Web API application on localhost with a SQL Server Database. 我在localhost上运行带有SQL Server数据库的MVC Web API应用程序。 I want to retrieve the data and output to TextViews in my application. 我想在我的应用程序中检索数据并输出到TextViews。 I am new to API calls and im not sure if am I doing it correctly. 我是API调用的新手,我不确定我是否正确使用它。 Source code below 源代码如下

fragment2_layout.xml 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 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
}

The AsyncTask method doInBackground() runs on a separate thread to the UI. AsyncTask方法doInBackground()在与UI的单独线程上运行。 You should not make any calls to update the UI from this method. 您不应该通过此方法进行任何更新UI的调用。 Override onPostExecute() in your AsyncTask, and put any calls to update the UI in here. 覆盖AsyncTask中的onPostExecute(),并在此处调用任何更新UI的调用。
Take a look at the example in the AsyncTask documentation . 看一下AsyncTask文档中的示例。

For example, in your case: 例如,在您的情况下:

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