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

时间:2015-02-23 20:50:26

标签: android sql api model-view-controller textview

我正在创建一个需要从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
}

1 个答案:

答案 0 :(得分:0)

AsyncTask方法doInBackground()在与UI的单独线程上运行。您不应该通过此方法进行任何更新UI的调用。 覆盖AsyncTask中的onPostExecute(),并在此处调用任何更新UI的调用 看一下AsyncTask documentation中的示例。

例如,在您的情况下:

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