如何从不同的方法传递变量对象

时间:2018-02-20 03:02:46

标签: android variables

我想从loadPhoneNumber方法调用verifySMS内的变量对象,但我得到如下错误,我该如何解决这个问题?

enter image description here

这是我的java代码:

public void loadPhoneNumber() {

    if (ContextCompat.checkSelfPermission(MainActivity.this,
            android.Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {

        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        String getSimNumber = telephonyManager.getLine1Number();
        Log.d("Success", "Phone number :" + getSimNumber);
        tvnope.setText(getSimNumber);
        requestOTP(getSimNumber);
        return;
    } else {
        requestStoragePermission();
    }
}

private void verifySMS(){
    Call<APIResponse> call=ServicesFactory.getService().getVerifySMS(getSimNumber,token);
    call.enqueue(new Callback<APIResponse>() {
        @Override
        public void onResponse(Call<APIResponse> call, Response<APIResponse> response) {
            if (response.isSuccessful()&&response.body().isSuccessful()){
                Intent intent = new Intent(MainActivity.this, MainPageActivity.class);
                startActivity(intent);
            }
        }

        @Override
        public void onFailure(Call<APIResponse> call, Throwable t) {
            Toast.makeText(MainActivity.this, "Token salah,silahkan input lagi", Toast.LENGTH_SHORT).show();
        }
    });
}

1 个答案:

答案 0 :(得分:1)

在班级中创建全局变量,并从任何方法分配/访问

public class YourClass
{
    //global variable
    String getSimNumber = "" ;


    public void loadPhoneNumber()
    {
         /*Initial Work*/ 
         //assign value into the global variable
         getSimNumber = telephonyManager.getLine1Number();
         /*Remaining Work*/ 
    }

    private void verifySMS()
    {
          //access the global variable
          Call<APIResponse>  call=ServicesFactory.getService().getVerifySMS(getSimNumber,token);
          /*Remaining Work*/
    }

}