简体   繁体   中英

Integrate Rest API Into Android Application

I am creating an Android application that will need to get data from a Web API. I am running a MVC Web API application on localhost with a SQL Server Database. I want to retrieve the data and output to TextViews in my application. I am new to API calls and im not sure if am I doing it correctly. Source code below

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
}

The AsyncTask method doInBackground() runs on a separate thread to the UI. You should not make any calls to update the UI from this method. Override onPostExecute() in your AsyncTask, and put any calls to update the UI in here.
Take a look at the example in the AsyncTask documentation .

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]);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM