我创建一个名为“value_array”的变量然后它将arraylist的值放入其中 变成那样: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 :(得分:2)
它不会“丢失”。您没有看到初始值(或默认值为0)的原因是您进行异步调用以获取value_array
的值。当呼叫处于待处理状态时,您的代码仍会执行,并在收到结果之前继续生成Toast
。
您的案例无需修复。只需删除
Toast.makeText(MainActivity.this,"Value_2 = " + value_array,Toast.LENGTH_LONG)
因为它没有任何价值。您有两种回调方法onResponse
和onFailure
。在那里,你可以随着结果收到你想做的任何事情。