Android 将改装响应传递给其他活动

Android 将改装响应传递给其他活动,android,retrofit2,Android,Retrofit2,我正在接收一个json服务器响应,并将其分配给一个int。我正在使用putExtra(也尝试了共享首选项)将这个int传递给下一个活动。当我加载下一个活动时,int不会第一次显示在屏幕上。我必须按下后退按钮,然后再次加载活动,以显示int值。我无法理解为什么第一次值传递不正确,以及为什么在第二次重新加载时它成功传递。我完全被这件事弄糊涂了,我想它要么通过要么不失败,第一次失败,每次都会通过重新加载 第一个活动执行插入并捕获行id,将行id传递给第二个活动,该活动用于使用传递的行id执行更新 有关

我正在接收一个json服务器响应,并将其分配给一个int。我正在使用putExtra(也尝试了共享首选项)将这个int传递给下一个活动。当我加载下一个活动时,int不会第一次显示在屏幕上。我必须按下后退按钮,然后再次加载活动,以显示int值。我无法理解为什么第一次值传递不正确,以及为什么在第二次重新加载时它成功传递。我完全被这件事弄糊涂了,我想它要么通过要么不失败,第一次失败,每次都会通过重新加载

第一个活动执行插入并捕获行id,将行id传递给第二个活动,该活动用于使用传递的行id执行更新

有关上下文,请参见代码段

改装电话的第一项活动:

case R.id.nextBtnMoodPage:
            if (hasSelected) {

                moodPreferences();
                backgroundSelector();

                Call<ReadCbtId> call = RetrofitClient
                        .getInstance()
                        .getApi()
                        .insertLog(userId, therapistId, moodBefore, automaticThoughtString, distortions, challengeThoughtString, alternativeThoughtString, moodAfter, posted);

                call.enqueue(new Callback<ReadCbtId>() {
                    @Override
                    public void onResponse(Call<ReadCbtId> call, Response<ReadCbtId> response) {

                        cbtId = response.body().getCbtId();
                        Toast.makeText(getContext(),String.valueOf(cbtId), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFailure(Call<ReadCbtId> call, Throwable t) {
                        Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });

                //editorWorkout.putInt("cbtId", cbtId);
                //editorWorkout.commit();
                Intent intent = new Intent(getActivity(), WorkoutAutomaticThoughtActivity.class);
                intent.putExtra("cbtId", cbtId);
                startActivity(intent);

            }
案例R.id.nextBtnMoodPage:
如果(当选){
moodPreferences();
背景选择器();
Call=Call客户端
.getInstance()
.getApi()
.insertLog(userId、therapistId、moodBefore、automaticThoughtString、扭曲、challengeThoughtString、alternativeThoughtString、moodAfter、post);
call.enqueue(新回调(){
@凌驾
公共void onResponse(调用、响应){
cbtId=response.body().getCbtId();
Toast.makeText(getContext(),String.valueOf(cbtId),Toast.LENGTH_SHORT.show();
}
@凌驾
失败时公共无效(调用调用,可丢弃的t){
Toast.makeText(getContext(),t.getMessage(),Toast.LENGTH_LONG).show();
}
});
//editorWorkout.putInt(“cbtId”,cbtId);
//commit();
Intent Intent=新的Intent(getActivity(),workUtautomaticthoughtActivity.class);
意向。额外支付(“cbtId”,cbtId);
星触觉(意向);
}
第二项活动:

 /**
 * Ints which are used to store numeric values related to the workout activity.
 */
private int userId, therapistId, cbtId;

private TextView title;

/**
 * @param savedInstanceState
 */
@SuppressLint("ResourceType")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_workout_automatic_thought);

    Bundle extras = getIntent().getExtras();
    cbtId = extras.getInt("cbtId");

    getSharedPreferences();
    moodPreferences();
    backgroundSelector();
    initialiseViews();
    setListeners();
}

/**
 * Method which gets the users shared preferences. loginPref stores the users ID and workoutPref stores the users mood
 * which they selected at the beginning of the Workout Activity.
 */
private void getSharedPreferences() {

    // Shared preferences track which mood the user selected
    loginPref = getSharedPreferences("loginPref", Context.MODE_PRIVATE);
    workoutPref = getSharedPreferences("workoutPref", Context.MODE_PRIVATE);

    // Users login preferences logged from the login activity.
    userId = loginPref.getInt("userId", 0);
    therapistId = loginPref.getInt("therapistId", 0);
   // cbtId = workoutPref.getInt("cbtId", 0);
}

/**
 *
 */
private void initialiseViews() {

    // Initialising editText form the xml file
    automaticThoughtET = findViewById(R.id.automaticThoughtInput);

    // Initialising the nextButton form the xml file
    nextButton = findViewById(R.id.DistortedNextBtn);

    title = findViewById(R.id.automaticThoughtTitle);
    title.setText("Test" + cbtId);

}


 private void setListeners() {
    // Setting an onClick listener to the nextButton
    nextButton.setOnClickListener(new View.OnClickListener() {

        /**
         * Method which opens a new activity when the next nextButton is clicked. This method also passed variables through
         * to the next activity as a string.
         * @param v
         */
        @Override
        public void onClick(View v) {

            if (!validateText()) {
                return;
            }

            Call<ResponseBody> call = RetrofitClient
                    .getInstance()
                    .getApi()
                    .updateAutomaticThought(cbtId, automaticThoughtString);

            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });
            //  Creating a new intent to move from the WorkoutAutomaticThoughtActivity to the WorkoutDistortedThoughtsActivity
            Intent intent = new Intent(WorkoutAutomaticThoughtActivity.this, WorkoutDistortedThoughtsActivity.class);

          /*  // Passing variables as Strings to the next activity
            automaticThoughtString = automaticThoughtET.getText().toString();
            intent.putExtra("AthoughtKey", automaticThoughtString);*/
            startActivity(intent);
            finish();
        }
    });
/**
*用于存储与训练活动相关的数值的整数。
*/
私人int用户ID、治疗师ID、cbtId;
私有文本视图标题;
/**
*@param savedInstanceState
*/
@SuppressLint(“资源类型”)
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u workout\u automatic\u think);
Bundle extras=getIntent().getExtras();
cbtId=额外的getInt(“cbtId”);
getSharedReferences();
moodPreferences();
背景选择器();
初始视图();
setListeners();
}
/**
*获取用户共享首选项的方法。loginPref存储用户ID,workoutPref存储用户情绪
*他们在训练活动开始时选择的。
*/
私有void getSharedReferences(){
//共享首选项跟踪用户选择的情绪
loginPref=getSharedReferences(“loginPref”,Context.MODE\u PRIVATE);
workoutPref=getSharedReferences(“workoutPref”,Context.MODE\u PRIVATE);
//从登录活动记录的用户登录首选项。
userId=loginPref.getInt(“userId”,0);
therapistId=loginPref.getInt(“therapistId”,0);
//cbtId=workoutPref.getInt(“cbtId”,0);
}
/**
*
*/
私有void initialiseViews(){
//初始化来自xml文件的editText
automaticthoughtt=findviewbyd(R.id.automaticThoughtInput);
//初始化xml文件中的下一个按钮
nextButton=findviewbyd(R.id.decurrentednextbtn);
title=findViewById(R.id.automaticThoughtTitle);
标题.setText(“测试”+cbtId);
}
私有void setListeners(){
//将onClick侦听器设置为nextButton
setOnClickListener(新视图.OnClickListener(){
/**
*方法,该方法在单击下一个下一个按钮时打开一个新活动。此方法还通过
*以字符串形式添加到下一个活动。
*@param v
*/
@凌驾
公共void onClick(视图v){
如果(!validateText()){
返回;
}
Call=Call客户端
.getInstance()
.getApi()
.UpdateAutomaticThink(cbtId,自动思维字符串);
call.enqueue(新回调(){
@凌驾
公共void onResponse(调用、响应){
}
@凌驾
失败时公共无效(调用调用,可丢弃的t){
}
});
//创建从WorkoutAutomatictHoughts活动移动到WorkoutTransformedHoughts活动的新意图
意向意向=新意向(WorkoutAutomaticThoughtActivity.this,WorkoutTransformedHoughtsActivity.class);
/*//将变量作为字符串传递给下一个活动
automaticThoughtString=automaticthoughtt.getText().toString();
intent.putExtra(“AthoughtKey”,automaticThoughtString)*/
星触觉(意向);
完成();
}
});

在得到结果之前,您正在调用下一个活动

Intent intent = new Intent(getActivity(), WorkoutAutomaticThoughtActivity.class);
intent.putExtra("cbtId", cbtId);
startActivity(intent);
此代码应该在

 @Override
 public void onResponse(Call<ReadCbtId> call, Response<ReadCbtId> response) {
    cbtId = response.body().getCbtId();
    Toast.makeText(getContext(),String.valueOf(cbtId), Toast.LENGTH_SHORT).show();
}

@覆盖
公共void onResponse(调用、响应){
cbtId=response.body().getCbtId();
Toast.makeText(getContext(),String.valueOf(cbtId),Toast.LENGTH_SHORT.show();
}
所以看起来是这样的:

@Override
public void onResponse(Call<ReadCbtId> call, Response<ReadCbtId> response) {
    Intent intent = new Intent(getActivity(), WorkoutAutomaticThoughtActivity.class);
    intent.putExtra("cbtId", response.body().getCbtId());

    Toast.makeText(getContext(),String.valueOf(response.body().getCbtId()), Toast.LENGTH_SHORT).show();

    startActivity(intent);

}
@覆盖
公共void onResponse(调用、响应){
Intent Intent=新的Intent(getActivity(),workUtautomaticthoughtActivity.class);
intent.putExtra(“cbtId”,response.body().getCbtId());
Toast.makeText(getContext()、String.valueOf(response.body().getCbtId())、Toast.LENGTH_SHORT.show();
开始