2016-04-26 9 views
0

Ich versuche, Status meiner Antwort zu erhalten, wenn es wahr ist, starten Sie neue Aktivität, sonst - Build-Alarm-Dialog. Wenn meine Daten korrekt sind, ist alles in Ordnung, die Aktivität beginnt. Aber wenn es falsch ist, stürzte meine App für NPE ab, weil Wert oder response.body() == null. Aber wenn Daten inkorrekt sind, sagte der Postbote, dass ich zum Beispiel einige Daten status == failed habe. Aber dieser Status geht nicht an mich. Ich versuche zu überprüfen, ob response.body() == null, Alarmdialog starten, aber wenn Daten falsch sind, ist nichts passiert. Was habe ich falsch gemacht?Versuchen Sie, den Status meiner Antwort zu erhalten

Mein Fragment:

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

Modell meiner Antwort:

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

Postman Ergebnis, wenn es in Ordnung ist:

{ 
    "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 
    } 
} 

Postman Ergebnis, wenn es fehlgeschlagen:

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

Antwort

0

onResponse wird immer dann aufgerufen, wenn eine HTTP-Antwort vorliegt, ob erfolgreich oder nicht. Betrachtet man die Klassenreferenz für Callback, zeigt response.isSuccessful() an, ob Sie die response.body() oder response.errorBody() betrachten sollten. In Ihrem Code-Snippet greifen Sie auf body() zu, auch wenn response.isSuccessful() false ist und daher eine NPE ergibt. Versuchen Sie Folgendes:.

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.isSuccessful()) { 
      // Do something with response.body() 
      SignInResult result = response.body(); 
      Intent user_activity_intent = new Intent(getActivity(), User_videos.class); 
      startActivity(user_activity_intent); 
     } else { 
      // Do something with response.errorBody().string() 
      try { 
       JSONObject errorPayload = new JSONObject(response.errorBody().string()); 
       if (errorPayload.getString("code").equals("invalid_password")) { 
        buildDialog(getActivity()); 
       } else { 
        // Do something else for other errors. 
       } 
      } catch (IOException|JSONException e1) { 
       // Continue 
      } 
     } 
    } 

    @Override 
    public void onFailure(Call<SignInResult> call, Throwable t) { 
     // Handle any network exception occurred talking to the server or 
     // when an unexpected exception occurred creating the 
     // request or processing the response. 
    } 
}); 
+0

Ich habe versucht, bauen in onFailure(), aber NPE caused.In Boolean i = response.body() getStatus(); –

+0

@prRost lassen Sie mich wissen, ob dies für Sie arbeitete – charleschenster

Verwandte Themen