在android Retrofit

时间:2018-02-05 11:02:36

标签: java android android-studio jwt retrofit2

我想用他们的令牌注册用户,我想在android中使用retrofit注册用户,但我一直收到这个错误:

ERROR::: Attempt to invoke virtual method 'void com.signup.User.setUsername(java.lang.String)' on a null object reference

这是我的代码:

    public class Session {
    Context context;
    private SharedPreferences prefs;

    public Session(Context cntx) {
        // TODO Auto-generated constructor stub
        this.context = cntx;
        prefs = PreferenceManager.getDefaultSharedPreferences(context);
    }

    public void setJwtToken(String token) {
        prefs.edit().putString("JwtToken", token).commit();
    }

    public String getJwtToken() {
        String token = prefs.getString("JwtToken", "");
        if (token == null || token.isEmpty()) {
            token = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjIxNzc0NTI3OTksImlhdCI6MTUxNjAyMjk5OSwiaXNzIjoiQmFzb2JhYXMgTmVwYWwiLCJuYmYiOjE1MTYwMjI5OTksImp0aSI6Ikd1ZXN0VG9rZW4iLCJzdWIiOjB9.QikmNgBYmqch5HREGFEpUs4Xk3x-zFfDg5mhYJO7jM8";
        }
        return token;
    }

}

    public interface ApiInterface {

    @POST("/api/users/signup")
    Call<ResponseBody> signMeUp(@Header("Authorization") String token ,@Body User user);



}

    public class MainActivity extends AppCompatActivity {

    private EditText et_name, et_address, et_phone, et_username, et_email, et_password, et_confipassword;
    private Button register;
    private User user;
    private SharedPreferences prefs;
    private ApiInterface apiInterface;
    private Session session;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        et_name = findViewById(R.id.edit_text_name);
        et_address = findViewById(R.id.edit_text_address);
        et_phone = findViewById(R.id.edit_text_phonenumber);
        et_username = findViewById(R.id.edit_text_username);
        et_email = findViewById(R.id.edit_text_email);
        et_password = findViewById(R.id.edit_text_password);
        et_confipassword = findViewById(R.id.edit_text_confirm_password);


        register = findViewById(R.id.signupButton);
        register.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
               Login();

            }

        });
    }


    private void Login() {


        user.setUsername(et_name.getText().toString());
        user.setAddress(et_address.getText().toString());
        user.setPhone(et_phone.getText().toString());
        user.setName(et_name.getText().toString());
        user.setEmail(et_email.getText().toString());
        user.setPassword(et_password.getText().toString());
        user.setPasswordConfirmation(et_confipassword.getText().toString());

        signupUser(user);
    }
    private void signupUser(final User user) {
        // Set up progressbar before call
        apiInterface = ApiClient.getClient().create(ApiInterface.class);

        Call<ResponseBody> call1 = apiInterface.signMeUp(session.getJwtToken(),user);

        final Gson gson = new Gson();
        final String json = gson.toJson(user);
        call1.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.code() == 201) {
                    try {
                        JSONObject jsonObject = new JSONObject(response.body().string());
                        //Starting main activity after user sees dialog
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else if (response.code() == 500) {
                    try {
                        JSONObject jsonObject = new JSONObject(response.errorBody().string());
                        Log.e("SignupFragment", jsonObject.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else
                    Log.e("SignupFragment", response.raw().toString());
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });
    }


    }


    public class User {

    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("email")
    @Expose
    private String email;
    @SerializedName("password")
    @Expose
    private String password;
    @SerializedName("password_confirmation")
    @Expose
    private String passwordConfirmation;
    @SerializedName("image")
    @Expose
    private String image;
    @SerializedName("phone")
    @Expose
    private String phone;
    @SerializedName("address")
    @Expose
    private String address;
    @SerializedName("username")
    @Expose
    private String username;
    @SerializedName("pan_no")
    @Expose
    private String panNo;
    @SerializedName("birthday")
    @Expose
    private String birthday;

    public String getName() {
        return name;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPasswordConfirmation() {
        return passwordConfirmation;
    }

    public void setPasswordConfirmation(String passwordConfirmation) {
        this.passwordConfirmation = passwordConfirmation;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getUsername() {
        return username;
    }

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

    public String getPanNo() {
        return panNo;
    }

    public void setPanNo(String panNo) {
        this.panNo = panNo;
    }

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }


}

    public class ApiClient {

    public static final String BASE_URL = "https://myapp.herokuapp.com/";
    private static Retrofit retrofit = null;

    public static Retrofit getClient() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }

        return retrofit;
    }
    ApiInterface apiInterface=retrofit.create(ApiInterface.class);
}

我想通过我的应用注册用户,但我一直收到错误。并且,如果我从接口中删除auth标题,我会收到一条消息,询问令牌,当我提供令牌时,它会给我一个空对象引用错误!!

3 个答案:

答案 0 :(得分:0)

您应该在访问变量之前实例化变量:User user = new User();

更新:在void Login()

中执行此操作

答案 1 :(得分:0)

在onCreate方法中创建一个User实例,或在那里声明它的

答案 2 :(得分:0)

试试这个

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        user = new User();
        session = new Session(this);
}