0

I have created a common class to access all POJO classes. when i try to parse and acceess POJO variable i am getting null pointer exception. i really do not know where i was wrong . can anyone help me to resolve this issue?

CommonReponse.java

public class CommonResponse {

private Github github;

public Github getGithub() {
    return github;
}

public void setGithub(Github github) {
    this.github = github;
}}

GithubService.java

public interface GithubService {

@GET("users/{username}")
Call<CommonResponse> getGithubUserInfo(@Path("username") String username);}

Github.java // POJO

public class Github {

@SerializedName("name")

private String name;

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}}

GetUserInfo() // Method

   private void getUserInfo() {
    Retrofit retrofit = new Retrofit.Builder()
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl("https://api.github.com/")
            .build();

    GithubService githubService = retrofit.create(GithubService.class);
    Call<CommonResponse> call = githubService.getGithubUserInfo(mGitUserName);
    call.enqueue(new retrofit2.Callback<CommonResponse>() {
        @Override
        public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {

            System.out.println("Response:+"+response.body().getGithub().getName());

        }

        @Override
        public void onFailure(Call<CommonResponse> call, Throwable t) {
            System.out.println("Response error:+"+t.getMessage());

        }
    });}

log

02-19 15:38:53.926 32293-32293/com.ananth.rxandroidwithretrofit E/AndroidRuntime: FATAL EXCEPTION: main
                                                                              Process: com.ananth.rxandroidwithretrofit, PID: 32293
                                                                              java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.ananth.rxandroidwithretrofit.model.Github.getName()' on a null object reference
                                                                                  at com.ananth.rxandroidwithretrofit.ProfileActivity$7.onResponse(ProfileActivity.java:243)
                                                                                  at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
                                                                                  at android.os.Handler.handleCallback(Handler.java:751)
                                                                                  at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                  at android.os.Looper.loop(Looper.java:154)
                                                                                  at android.app.ActivityThread.main(ActivityThread.java:6682)
                                                                                  at java.lang.reflect.Method.invoke(Native Method)
                                                                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
Anantha Babu
  • 216
  • 2
  • 14

4 Answers4

0

The problem is that getGitHub returns null. The reason is that the github member of the CommonResponse instance was not initialized yet when you try to get its name. The solution is to modify getGitHub this way:

public Github getGithub() {
    if (github == null) {
        //Initialize github, so it will not be null
    }
    return github;
}
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • Thanks you. Its not getting force close now but i am still get null when i access variable in from pojo class – Anantha Babu Feb 19 '18 at 10:41
  • @AnanthaBabu I understand. How are you initializing the member in getGithub if it is null in your current version? – Lajos Arpad Feb 19 '18 at 10:44
  • public Github getGithub() { if (github == null) { //Initialize github, so it will not be null github=new Github(); } return github; } – Anantha Babu Feb 19 '18 at 10:51
  • @AnanthaBabu you are calling the default constructor of GitHub if it did not exist. You will need to set its name somehow, like either calling setName("thename") or implementing a constructor, which expects a String and passing the name to it. Subsequently, this constructor will need to initialize the name of the object to be equal to the parameter you received. – Lajos Arpad Feb 19 '18 at 10:56
0

Initialize your model

Github model; //In your Activity

private void getUserInfo() {
    Retrofit retrofit = new Retrofit.Builder()
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl("https://api.github.com/")
            .build();

    GithubService githubService = retrofit.create(GithubService.class);
    Call<CommonResponse> call = githubService.getGithubUserInfo(mGitUserName);
    call.enqueue(new retrofit2.Callback<CommonResponse>() {
        @Override
        public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {

            if(response!=null)
            {
            model = response.body(); //Parse your response here
            }

        }

        @Override
        public void onFailure(Call<CommonResponse> call, Throwable t) {
            System.out.println("Response error:+"+t.getMessage());

        }
    });}
Akshay Katariya
  • 1,464
  • 9
  • 20
0

Try this

private void getUserInfo() {
Retrofit retrofit = new Retrofit.Builder()
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        .addConverterFactory(GsonConverterFactory.create())
        .baseUrl("https://api.github.com/")
        .build();

GithubService githubService = retrofit.create(GithubService.class);
Call<Github> call = githubService.getGithubUserInfo(mGitUserName);
call.enqueue(new retrofit2.Callback<Github>() {
    @Override
    public void onResponse(Call<Github> call, Response<Github> response) {

        System.out.println("Response:+"+response.body().getName());

    }

    @Override
    public void onFailure(Call<Github> call, Throwable t) {
        System.out.println("Response error:+"+t.getMessage());

    }
});}

and

public interface GithubService {

@GET("users/{username}")
Call<Github> getGithubUserInfo(@Path("username") String username);}
Navneet Krishna
  • 5,009
  • 5
  • 25
  • 44
  • public Github getGithub() { if (github == null) { //Initialize github, so it will not be null github=new Github(); } return github; } – Anantha Babu Feb 19 '18 at 10:45
  • if this https://api.github.com/users/ananth10 is your response, then you will need only a single pojo class(Github), the outer class is not necessary – Navneet Krishna Feb 19 '18 at 10:46
  • Noo. I need a common response class. Please see this class [https://github.com/iammert/AndroidArchitecture/blob/master/app/src/main/java/iammert/com/androidarchitecture/data/remote/model/MoviesResponse.java]. i have just implemented same as it there. but i dont know why its not working – Anantha Babu Feb 19 '18 at 10:50
  • it depends on the response, in your case you are having a single json object, but in the given example there is an inner json object – Navneet Krishna Feb 19 '18 at 10:53
0

Change your POJO classes like that.Do not set getter and setter.

public class CommonResponse {
 @SerializedName("github")
 @Expose
 public Github github;
}


public class Github {
 @SerializedName("name")
 @Expose
 public String name;
}
Kemal Turk
  • 2,160
  • 1
  • 14
  • 15