空指针异常,改造?

编程入门 行业动态 更新时间:2024-10-25 14:34:02
本文介绍了空指针异常,改造?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试从 URL 获取 id 但获取空指针异常

I am trying to get an id from URL but getting the null pointer exception

java.lang.NullPointerException:尝试从空对象引用上的字段java.lang.String com.hex.encode.ID_Model$User.id"读取在 com.hex.encode.Home$3.onResponse(Home.java:99)

java.lang.NullPointerException: Attempt to read from field 'java.lang.String com.hex.encode.ID_Model$User.id' on a null object reference at com.hex.encode.Home$3.onResponse(Home.java:99)

这是我用来获取 ID 的代码:

and this is the code I am using to get the id:

private void GetID() { Call<ID_Model> idcall = fetchdata.getIdService().getID(user_search); idcall.enqueue(new Callback<ID_Model>() { @Override public void onResponse(@NonNull Call<ID_Model> call,@NonNull Response<ID_Model> response) { assert response.body() != null; String fetched_id =response.body().getUser().getId;//this is where the exception is poping GetData(fetched_id); } @Override public void onFailure(@NonNull Call<ID_Model> call, @NonNull Throwable t) { //something// } }); }

以下是 fetchdata 类:

and below is the fetchdata class:

class fetchdata { private static UserFetchData userdatafetch = null; private static UserIDFetch fetchService = null; static UserIDFetch getIdService() { if (fetchService == null) { String id_url = "url_and_it's_working"; Retrofit fetch_id = new Retrofit.Builder() .baseUrl(id_url) .addConverterFactory(GsonConverterFactory.create()) .build(); fetchService = fetch_id.create(UserIDFetch.class); } return fetchService; } public interface UserIDFetch{ @GET("{user_input}"+"/") Call<ID_Model> getID(@Path("user_input") String s); } }

编辑

这是 Id_Model :

Here is the Id_Model :

public class ID_Model { @SerializedName("user") @Expose public User user; public User getUser() { return user; } public class User { @SerializedName("id") @Expose public String id; public String getId() { return id; } public void setId(String id) { this.id = id; } } }

编辑这是来自 API 服务器的响应:justpaste.it/4gk8r

Edit Here is the response from the API Server : justpaste.it/4gk8r

推荐答案

您需要使用 response.isSucessful() 检查响应是否成功.这也取决于服务器端,当 API 成功命中服务器时,他们发送 200 然后我们需要检查 API 响应是否success 或 failure 基于响应.

You need to check response is successful with response.isSucessful(). And it also depends on server side they send the 200 when API successfully hit on server and then we need to check the API response is it success or failure on the basis of the response.

在你的情况下,我认为 API 调用是成功的 200 并返回一些响应但 response.body().getUser()是 null.所以你必须检查API的响应.

In your case, I think API call is success with 200 and return some response but response.body().getUser() is null. So you have to check the response of API.

更多推荐

空指针异常,改造?

本文发布于:2023-08-02 17:53:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1279886.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指针   异常

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!