尝试获取我的回复状态

时间:2016-04-26 19:47:18

标签: android retrofit retrofit2

我试图获取我的回复状态,如果确实如此,则启动新活动,否则 - 建立警报对话框。当我的数据正确时,一切都很好,Activity正在启动。但是当它不正确时,我的应用程序因NPE而崩溃,因为值或response.body() == null。但是当数据不正确时,Postman说我有一些数据status == failed。但这种状态并不适合我。我试图检查是否response.body() == null,启动警报对话框,但是当数据不正确时,没有任何反应。我做错了什么?

我的片段:

public class FeedFragment extends Fragment {
    EditText username;
    EditText password;
    Button btnLogin;

    public List<SignInResult> signInResult;
    String username_value,password_value;
    public static final String ROOT_URL = "https://api.vid.me/";

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_feed, container, false);
        username = (EditText) rootView.findViewById(R.id.user_name_field);
        password = (EditText) rootView.findViewById(R.id.password_field);
        btnLogin = (Button) rootView.findViewById(R.id.button_login);
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Authorize();
            }
        });
        return rootView;
    }

    public void Authorize() {
        Retrofit retrofitAdapter = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(ROOT_URL)
                .build();
        final VideoApi videoApi = retrofitAdapter.create(VideoApi.class);

         username_value = username.getText().toString();
         password_value = password.getText().toString();
String basicauth = "Basic "+ Base64.encodeToString(String.format("%s:%s",username_value,password_value).getBytes(),Base64.NO_WRAP);
        Call<SignInResult> call = videoApi.insertUser(username_value,password_value);
        call.enqueue(new Callback<SignInResult>() {


            @Override
            public void onResponse(Call<SignInResult> call, Response<SignInResult> response) {
                if(response.body()==null){ buildDialog(getActivity());}else {
                    Boolean i = response.body().getStatus();
                    if (i == true) {
                        Intent user_activity_intent = new Intent(getActivity(), User_videos.class);
                        startActivity(user_activity_intent);
                    }
                }




            }

            @Override
            public void onFailure(Call<SignInResult> call, Throwable t) {

            }
        });
}
    public AlertDialog.Builder buildDialog(Context c) {

        AlertDialog.Builder builder = new AlertDialog.Builder(c);
        builder.setTitle("Invalid password ");
        builder.setMessage("The password you entered was not valid");
        builder.setIcon(R.drawable.ic_block_black_18dp);
        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                dialog.dismiss();
            }
        });

        return builder;
    }
}

我的回复模型:

public class SignInResult {

    @SerializedName("status")
    private Boolean status;
    @SerializedName("auth")
    private Auth auth;
    @SerializedName("user")
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Boolean getStatus() {
        return status;
    }

    public void setStatus(Boolean status) {
        this.status = status;
    }

    public Auth getAuth() {
        return auth;
    }

    public void setAuth(Auth auth) {
        this.auth = auth;
    }

    public static class User {
        @SerializedName("user_id")
        private String userId;
        @SerializedName("username")

        private String username;
        @SerializedName("full_url")
        private String fullUrl;
        @SerializedName("avatar")
        private String avatar;
        @SerializedName("avatar_url")
        private String avatarUrl;
        @SerializedName("cover")
        private String cover;
        @SerializedName("cover_url")
        private String coverUrl;
        @SerializedName("displayname")
        private String displayname;
        @SerializedName("follower_count")
        private Integer followerCount;
        @SerializedName("likes_count")
        private String likesCount;
        @SerializedName("video_count")
        private Integer videoCount;
        @SerializedName("video_views")
        private String videoViews;
        @SerializedName("videos_scores")
        private Integer videosScores;
        @SerializedName("comments_scores")
        private Integer commentsScores;
        @SerializedName("bio")
        private String bio;

        public String getBio() {
            return bio;
        }

        public void setBio(String bio) {
            this.bio = bio;
        }

        public String getUserId() {
            return userId;
        }

        public void setUserId(String userId) {
            this.userId = userId;
        }

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getFullUrl() {
            return fullUrl;
        }

        public void setFullUrl(String fullUrl) {
            this.fullUrl = fullUrl;
        }

        public String getAvatar() {
            return avatar;
        }

        public void setAvatar(String avatar) {
            this.avatar = avatar;
        }

        public String getAvatarUrl() {
            return avatarUrl;
        }

        public void setAvatarUrl(String avatarUrl) {
            this.avatarUrl = avatarUrl;
        }

        public String getCover() {
            return cover;
        }

        public void setCover(String cover) {
            this.cover = cover;
        }

        public String getCoverUrl() {
            return coverUrl;
        }

        public void setCoverUrl(String coverUrl) {
            this.coverUrl = coverUrl;
        }

        public String getDisplayname() {
            return displayname;
        }

        public void setDisplayname(String displayname) {
            this.displayname = displayname;
        }

        public Integer getFollowerCount() {
            return followerCount;
        }

        public void setFollowerCount(Integer followerCount) {
            this.followerCount = followerCount;
        }

        public String getLikesCount() {
            return likesCount;
        }

        public void setLikesCount(String likesCount) {
            this.likesCount = likesCount;
        }

        public Integer getVideoCount() {
            return videoCount;
        }

        public void setVideoCount(Integer videoCount) {
            this.videoCount = videoCount;
        }

        public String getVideoViews() {
            return videoViews;
        }

        public void setVideoViews(String videoViews) {
            this.videoViews = videoViews;
        }

        public Integer getVideosScores() {
            return videosScores;
        }

        public void setVideosScores(Integer videosScores) {
            this.videosScores = videosScores;
        }

        public Integer getCommentsScores() {
            return commentsScores;
        }

        public void setCommentsScores(Integer commentsScores) {
            this.commentsScores = commentsScores;
        }
    }

    public static class Auth {

        @SerializedName("token")
        private String token;
        @SerializedName("expires")
        private String expires;
        @SerializedName("user_id")
        private String userId;

        public String getToken() {
            return token;
        }

        public void setToken(String token) {
            this.token = token;
        }

        public String getExpires() {
            return expires;
        }

        public void setExpires(String expires) {
            this.expires = expires;
        }

        public String getUserId() {
            return userId;
        }

        public void setUserId(String userId) {
            this.userId = userId;
        }
    }
}

邮差结果好的时候:

{
    "status": true,
    "auth": {
        "token": "64e63fb0269c4adf8479d15669de7534",
        "expires": "2017-04-26 19:31:21",
        "user_id": "11272862"
    },
    "user": {
        "user_id": "11272862",
        "username": "prozrostyslav",
        "full_url": "https://vid.me/prozrostyslav",
        "avatar": null,
        "avatar_url": "https://d2ha22j8ys3e0o.cloudfront.net/images/default-avatars/13.png?602-2-2-4-9",
        "cover": null,
        "cover_url": "https://d2ha22j8ys3e0o.cloudfront.net/images/default-covers/03.jpg?602-2-2-4-9",
        "displayname": null,
        "follower_count": 0,
        "likes_count": "0",
        "video_count": 0,
        "video_views": "0",
        "videos_scores": 0,
        "comments_scores": 0,
        "bio": null
    }
}

邮差失败时的结果:

{
    "status": false,
    "code": "invalid_password",
    "error": "The password you entered was not valid."
}

1 个答案:

答案 0 :(得分:0)

每当有HTTP响应时,无论是否成功,都会调用

onResponse。查看Callback的类引用,response.isSuccessful()指示是否应该查看response.body()或response.errorBody()。在您的代码段中,即使response.isSuccessful()为false,您也可以访问body(),从而导致NPE。请尝试以下方法:

flush()