Android 开发杂记(不定时持续更新)

本文详细介绍了如何解决Git中游离态结点的问题,包括如何从特定commit创建分支,以及如何处理Android中PopupWindow的遮罩效果。同时,深入探讨了使用Swagger Codegen在Android项目中生成Retrofit代码的过程,并分享了遇到的常见问题及其解决方案。

简要目录

  • 解决git游离态结点
  • 解决Android popupwindow弹出遮罩问题
  • Android 使用swaggercodegen流程及踩坑

拯救游离的head(HEAD detached at head)

  • 以本次提交的commit id 创建一个分支
git branch newbranch 7d8733939 

复制代码
  • 切换到自己的工作分支
git checkout dev
复制代码
  • 把刚刚临时创建的newbranch 合并到自己的工作分支当中
git merge newbranch

复制代码
  • 然后push到服务器万事大吉(不需要的add commit了)
git push
复制代码

关于popupwinodw 所在Activity无遮罩的解决方案

思路: 获取到当前Activity的window,通过设置window.LayoutParams的alph改变其透明度,达到背景遮罩的效果

WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.alpha = 0.4f;
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
getWindow().setAttributes(lp);
复制代码

当然当popupwindow 消失的时候你要让他的透明度恢复正常1

Android 客户端集成swgger codegen生成的代码(Retrofit)

过程
  • 下载swagger-codegen.jar
  • 准备好json或者YAM文件,他是codegen用来生成的参考
  • 配置config.gso,是生成过程的一些配置

config.json

{
  "library": "retrofit2",
  "useRxJava2": "false",
  "developerName": "红孩儿",
  "developerEmail": "",
  "developerOrganization": "alibaba",
  "invokerPackage": "com.alibaba.warehousing.network",
  "modelPackage": "com.alibaba.warehousing.entrygen",
  "apiPackage": "com.alibaba.warehousing.network.data.api",
  "artifactId": "swagger-petstore-retrofit2"
}

复制代码
  • cmd命令行使用命令
java -jar swagger-codegen.jar generate -i json.json -o client -l java -c config.json -DdateLibrary=legacy
复制代码
踩坑
  • 在AS中向项目中集成时候出现冲突
Program type already present: org.apache.oltu.oauth2.common.OAuth$HttpMethod
复制代码

解决冲突

configurations.all {exclude group: 'org.apache.oltu.oauth2', module: 'org.apache.oltu.oauth2.common'}
复制代码
  • 关于Date问题 可能自动生成的代码中的Date跟我们想要的不一样,可以在Gson反序列化的时候,转换成我们想要的格式。
  gson = new GsonBuilder()
                    .setDateFormat("yyyy-MM-dd HH:mm:ss")
                    .registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
                        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            try {
                                return sdf.parse(json.getAsJsonPrimitive().getAsString());
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            return null;
                        }
                    })
                    .create();
复制代码
  • 自动生成的Retrofit实体类转换时自定义

来个栗子说明:服务端返回的接口是这样的

 {"result":null,"success":true,"error":null}
复制代码

当success为true的时候,result里面就有值了,而且是不确定的值可能为某种类型的实体,也可能是Array。

自动生成的代码的接口是这样的:

  @GET("api/services/app/User/Get")
  Call<User> apiServicesAppRackGetGet(
          @Query("id") Integer id
  );
复制代码

实际返回的是这样的

 {"result":{"username":"李不凡","age”:21},"success":true,"error":null}
复制代码

明白这个问题了吧:我接口API里期望的是User,返回的是被Result包装过的User了,直接反序列化会出现问题

解决方式,Retrofit.Builder adapterBuilder添加converterfactory,自己写一个转换器,把json转换成我们期望的形式

public class CustomizeGsonConverterFactory extends Converter.Factory {
    public static CustomizeGsonConverterFactory create() {
        return create(new Gson());
    }

    public static CustomizeGsonConverterFactory create(Gson gson) {
        return new CustomizeGsonConverterFactory(gson);
    }

    private final Gson gson;

    private CustomizeGsonConverterFactory(Gson gson) {
        if (gson == null) {
            throw new NullPointerException("gson == null");
        }
        this.gson = gson;
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
                                                            Retrofit retrofit) {
        TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        return new CustomizeGsonResponseBodyConverter<>(gson, adapter);
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        return new CustomizeGsonRequestBodyConverter<>(gson, adapter);
    }

}
复制代码
public class CustomizeGsonRequestBodyConverter<T> implements Converter<T, RequestBody> {

    private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
    private static final Charset UTF_8 = Charset.forName("UTF-8");

    private final Gson gson;
    private final TypeAdapter<T> adapter;

    CustomizeGsonRequestBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public RequestBody convert(T value) throws IOException {
        Buffer buffer = new Buffer();
        Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
        JsonWriter jsonWriter = gson.newJsonWriter(writer);
        adapter.write(jsonWriter, value);
        jsonWriter.close();
        return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
    }
}
复制代码
public class CustomizeGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {

    private final Gson gson;
    private final TypeAdapter<T> adapter;

    CustomizeGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String response = value.string();
        NetResponse baseResponse = gson.fromJson(response, NetResponse.class);
        if (baseResponse.success) {
            try {
                return adapter.fromJson(gson.toJson(baseResponse.result));
            } finally {
                value.close();
            }
        } else {
            throw new ApiException(gson.toJson(baseResponse.error));
        }

    }
}

复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值