所以我和一个朋友一直在开发基本的Android应用程序。我们已经屏蔽了逻辑并进行了伪编码,但是在更新我们的对象之一时遇到了一些麻烦。 (顺便说一句,我们仍然都是新手,因此,如果我的术语不正确,我深表歉意,欢迎进行更正。)据我了解,btcCurrent应该在dataGet方法中更新。我认为此值更改将持续存在,但是当我设置textView时,btcCurrent.last_price显然为null,而不是它设置为的值。在Android Studio中进行的调试显示,该值在dataGet中时已正确设置,但不会在该值外持久存在。我不明白我在做什么错。
MainActivity.java
package com.twodudesdev.bitcoinalert;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;
import cz.msebera.android.httpclient.Header;
public class MainActivity extends AppCompatActivity {
Context context = this;
TextView textView;
BitCoinInfo btcCurrent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AsyncHttpClient client = new AsyncHttpClient();
textView = this.findViewById(R.id.textDisplayPrice);
dataGet(client);
textView.setText(btcCurrent.last_price);
}
private void dataGet(AsyncHttpClient client) {
client.get("https://api.bitfinex.com/v1/ticker/btcusd", new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, String response) {
String toastText = "Successfully downloaded JSON File";
Toast successfulJsonToast = Toast.makeText(context, toastText, Toast.LENGTH_SHORT);
successfulJsonToast.show();
Gson btcGson = new GsonBuilder().create();
btcCurrent = btcGson.fromJson(response, BitCoinInfo.class);
}
@Override
public void onFailure(int statusCode, Header[] headers, String response, Throwable throwable) {
String toastText = "Cannot load JSON File: " + throwable;
Toast failedJsonToast = Toast.makeText(context, toastText, Toast.LENGTH_SHORT);
failedJsonToast.show();
}
});
}
}
BitCoinInfo.java
package com.twodudesdev.bitcoinalert;
public class BitCoinInfo {
public int id;
public String mid;
public String bid;
public String ask;
public String last_price;
public String timestamp;
}
最佳答案
dataGet(client);
textView.setText(btcCurrent.last_price);
您正在尝试在进行异步http调用后立即更新textview文本,因此btcCurrent.last_price当时为null。将此行
textView.setText(btcCurrent.last_price);
移至onSuccess
方法。