gpt4 book ai didi

java - 变量在函数外丢失了它的值?

转载 作者:行者123 更新时间:2023-11-29 19:02:17 24 4
gpt4 key购买 nike

我创建一个名为“value_array”的变量然后将数组列表的值放入其中变成那样:value_array = collection.get(0);然后我尝试通过 Toast 函数显示结果结果是:Value_1=1然后我退出了入队功能当我尝试使用 Toast 功能时结果是:Value_1=0怎么解决调用同一个变量,在函数外面才不会丢值,看看我的代码:

package com.example.cca.retrofit;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import retrofit.Call;
import retrofit.Retrofit;
//https://github.com/metachris/retrofit2-samples
//https://www.youtube.com/watch?v=uAXn7VntQvw

public class MainActivity extends AppCompatActivity {

//HttpApiSimple asd;
private Call<List<Users>> getUsersCall;
private Call<HttpApi.HttpBinResponse>call;
// private List<int[]> collection;
private List<Integer>collection;
private HttpApi api;
public int value_array;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// asd = new HttpApiSimple();
testInstance();
}

private void testInstance(){

api = HttpApi.getInstance();
value_array = 0;
api.addHeader("Authorization","MyT23");
/// Get iteme from index number33333+69

getUsersCall = api.getService().getAllChatRooms();
getUsersCall.enqueue(new retrofit.Callback<List<Users>>(){
@Override
public void onResponse(retrofit.Response<List<Users>> response, Retrofit retrofit){
collection = new ArrayList<>();

for(int i=0; i<response.body().size(); i++){

collection.add(Integer.parseInt(response.body().get(i).id));
}

value_array = collection.get(1);
// Add pramater from another table ;
// Toast.makeText(MainActivity.this,"Value_1=" + value_array ,Toast.LENGTH_LONG).show();

call = api.getService().postWithJson(new HttpApi.LoginData(13,"Rauool",value_array));
call.enqueue(new retrofit.Callback<HttpApi.HttpBinResponse>(){
@Override
public void onResponse(retrofit.Response<HttpApi.HttpBinResponse> response, retrofit.Retrofit retrofit){
// Toast.makeText(MainActivity.this, "" + response.body().message.toString(), Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Throwable t) {
// Toast.makeText(MainActivity.this, "" + t.toString(), Toast.LENGTH_LONG).show();
}
});
}

@Override
public void onFailure(Throwable t){
// Toast.makeText(MainActivity.this," " + t.toString() ,Toast.LENGTH_LONG).show();
}});
}

}

最佳答案

它不是“丢失”的。您看不到初始值(或默认为 0)的原因是您进行了异步调用以获取 value_array 的值。当调用挂起时,您的代码仍然会执行,并且会在收到结果之前继续执行 Toast

您的情况不需要修复。简单地删除

Toast.makeText(MainActivity.this,"Value_2 = " + value_array,Toast.LENGTH_LONG)

因为它在那里没有任何值(value)。您有两个回调方法 onResponseonFailure。收到结果后,您可以在那里做任何您想做的事情。

关于java - 变量在函数外丢失了它的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48565416/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com