Android Java:如何更新方法中的对象?

时间:2018-04-26 18:31:51

标签: java android

所以我和朋友一直在研究基本的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;
}

1 个答案:

答案 0 :(得分:2)

    dataGet(client);
    textView.setText(btcCurrent.last_price);

您正在尝试在进行异步http调用后立即更新textview文本,因此btcCurrent.last_price在此时为null。将此行textView.setText(btcCurrent.last_price);移至onSuccess方法。