在Android中使用改造Android

2023-09-12 06:53:00 作者:独坐君王位

我有一个Android应用程序,有3项活动:

I have an android app that has 3 activities :

系统登录活动 系统任务acivity,其中涉及用户的所有任务(使用数组适配器填充)显示 系统task_details活动​​导致从单击列表中的任务

我都需要消耗的REST API。该研究我迄今所做的指示,我用改造。我查了一下如何使用它,并发现:

I have to consume REST Apis. The research I have done so far directs me to use Retrofit. I checked how to use it and found out that :

在主要活动将基本URL(矿是登录活动) 我需要创建一个API类,并定义使用说明我的功能。 使用活动中的类休息适配器,并定义回调。

要是我的应用程序是一个活动的应用程序,我会碾碎一切都在我的MainActivity.java,但我不知道如何以及在哪里把所有的code从1,2,3中使用的步骤我3 activities.Could请你告诉如何利用改造我的应用程序帮助。非常感谢。

Had my app been a single activity app, I would have crunched everything in my MainActivity.java but I don't know how and where to put all the code from steps 1,2,3 for use in my 3 activities.Could you please help by telling how to use Retrofit in my app. Thanks a lot.

具体而言,我需要网络调用: 1.登录用户 2.获取用户的所有任务。 而对于这两个我将使用一个给定的REST API。

Specifically, I need network calls to : 1. Login the user 2. Get all the tasks of the user. And for both I would be using a given REST api.

推荐答案

使用改造是相当简单明了。

Using Retrofit is quite simple and straightforward.

首先,你需要添加到改造项目,作为例如用摇篮构建系统正。

First of all you need to add retrofit to your project, as example with Gradle build sytem.

compile 'com.squareup.retrofit:retrofit:1.7.1' |

另一种方式,你可以下载.jar和它放在你的libs文件夹。

another way you can download .jar and place it to your libs folder.

然后,你需要定义将要使用的改造,使API调用到您的REST端点接口。例如,对于用户:

Then you need to define interfaces that will be used by Retrofit to make API calls to your REST endpoints. For example for users:

public interface YourUsersApi {

   //You can use rx.java for sophisticated composition of requests 
   @GET("/users/{user}")
   public Observable<SomeUserModel> fetchUser(@Path("user") String user);

   //or you can just get your model if you use json api
   @GET("/users/{user}")
   public SomeUserModel fetchUser(@Path("user") String user);

   //or if there are some special cases you can process your response manually 
   @GET("/users/{user}")
   public Response fetchUser(@Path("user") String user);

}

确定。现在,您已经定义了API接口的,你可以尝试使用它。

Ok. Now you have defined your API interface an you can try to use it.

要开始,你需要创建一个实例的的 RestAdapter 的并设置基地的API后端的URL。它也很简单:

To start you need to create an instance of RestAdapter and set base url of your API back-end. It's also quite simple:

RestAdapter restAdapter = new RestAdapter.Builder()
   .setEndpoint("https://yourserveraddress.com")
    .build();

YourUsersApi yourUsersApi = restAdapter.create(YourUsersApi.class);

下面将改造从接口读取你的信息,并在引擎盖下它会创建的的 RestHandler 的根据元信息的提供,实际上将执行HTTP请求。

Here Retrofit will read your information from interface and under the hood it will create RestHandler according to meta-info your provided which actually will perform HTTP requests.

然后引擎盖下,一旦收到响应,如果JSON API的数据将被改造为使用GSON库模型,所以你应该知道的是事实,这是present在GSON的限制实际上是有在改造。

Then under the hood, once response is received, in case of json api your data will be transformed to your model using Gson library so you should be aware of that fact that limitations that are present in Gson are actually there in Retrofit.

要你的回应数据扩展/序列化器的/ deserialisation覆盖过程中你的模型,你可能想提供自定义的序列化器/ deserialisers改造。

To extend/override process of serialisers/deserialisation your response data to your models you might want to provide your custom serialisers/deserialisers to retrofit.

在这里,你需要实现转换器接口,并实现2种方法的的 fromBody()的和的 toBody()的。

Here you need to implement Converter interface and implement 2 methods fromBody() and toBody().

下面是例子:

public class SomeCustomRetrofitConverter implements Converter {

    private GsonBuilder gb;

    public SomeCustomRetrofitConverter() {
        gb = new GsonBuilder();

        //register your cursom custom type serialisers/deserialisers if needed
        gb.registerTypeAdapter(SomeCutsomType.class, new SomeCutsomTypeDeserializer());
    }

    public static final String ENCODING = "UTF-8";

    @Override
    public Object fromBody(TypedInput body, Type type) throws ConversionException {
        String charset = "UTF-8";
        if (body.mimeType() != null) {
            charset = MimeUtil.parseCharset(body.mimeType());
        }
        InputStreamReader isr = null;
        try {
           isr = new InputStreamReader(body.in(), charset);
           Gson gson = gb.create();
           return gson.fromJson(isr, type);
        } catch (IOException e) {
            throw new ConversionException(e);
        } catch (JsonParseException e) {
            throw new ConversionException(e);
        } finally {
            if (isr != null) {
                   try {
                      isr.close();
                   } catch (IOException ignored) {
                }
            }
        }
    }

    @Override
    public TypedOutput toBody(Object object) {
        try {
            Gson gson = gb.create();
            return new JsonTypedOutput(gson.toJson(object).getBytes(ENCODING), ENCODING);
        } catch (UnsupportedEncodingException e) {
            throw new AssertionError(e);
        }
     }

    private static class JsonTypedOutput implements TypedOutput {
        private final byte[] jsonBytes;
        private final String mimeType;

        JsonTypedOutput(byte[] jsonBytes, String encode) {
            this.jsonBytes = jsonBytes;
            this.mimeType = "application/json; charset=" + encode;
        }

        @Override
        public String fileName() {
            return null;
        }

       @Override
       public String mimeType() {
           return mimeType;
       }

       @Override
       public long length() {
          return jsonBytes.length;
       }

       @Override
       public void writeTo(OutputStream out) throws IOException {
           out.write(jsonBytes);
       }
    }
 }

现在,您需要启用自定义适配器,如果需要使用的的 setConverter()了的建设RestAdapter

And now you need to enable your custom adapters, if it was needed by using setConverter() on building RestAdapter

确定。现在你知道如何从服务器上获取数据到你的Andr​​oid应用程序。但是,你需要以某种方式管理您的数据和调用在正确的地方REST调用。 在那里,我会建议使用Android服务或AsyncTask的或装载机或rx.java将查询以不阻止你的UI在后台线程数据。

Ok. Now you are aware how you can get your data from server to your Android application. But you need somehow mange your data and invoke REST call in right place. There I would suggest to use android Service or AsyncTask or loader or rx.java that would query your data on background thread in order to not block your UI.

所以,现在你可以找到最合适的地方叫

So now you can find the most appropriate place to call

SomeUserModel yourUser = yourUsersApi.fetchUser("someUsers")

要获取远程的数据。