You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Java:如何在方法内部更新对象?

Troubleshooting Null btcCurrent.last_price in Your Android App

Hey there, fellow Android newbie! Let’s figure out why your btcCurrent.last_price is showing up as null when you try to set it to your TextView—this is a super common pitfall for folks just starting out, so you’re not alone.

Most Likely Causes & Fixes

1. You’re Running Into Async Timing Issues

Chances are your dataGet() method is handling a network request (since you’re fetching BTC prices), and network calls in Android are almost always asynchronous. That means when you call dataGet() and immediately try to set your TextView, the request hasn’t finished yet—so btcCurrent hasn’t been updated at all, leaving last_price as null.

Fix: Move your TextView update code inside the callback that runs after the data is successfully fetched. For example, if you’re using AsyncTask (great for beginners) or a library like Retrofit, update the UI only once you’ve got the data:

// 先在类里声明并初始化btcCurrent(关键!不要让它一直是null)
private BtcData btcCurrent;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    // 初始化对象,避免空指针
    btcCurrent = new BtcData();
    
    // 启动数据获取
    dataGet();
}

private void dataGet() {
    // 模拟异步网络请求(实际项目用OkHttp/Retrofit会更规范)
    new AsyncTask<Void, Void, String>() {
        @Override
        protected String doInBackground(Void... voids) {
            // 这里写实际的网络请求逻辑,获取BTC的last_price
            return getBtcPriceFromApi();
        }

        @Override
        protected void onPostExecute(String fetchedPrice) {
            // 数据拿到了!更新btcCurrent的属性
            btcCurrent.last_price = fetchedPrice;
            
            // 现在安全地更新TextView(onPostExecute在主线程,符合Android规则)
            TextView priceTextView = findViewById(R.id.btc_price_tv);
            priceTextView.setText(btcCurrent.last_price);
        }
    }.execute();
}

2. You’re Reassigning btcCurrent Instead of Updating Its Properties

If inside dataGet() you’re doing something like btcCurrent = new BtcData() and then setting last_price on this new object, you’re breaking the reference to the original btcCurrent variable you declared elsewhere. The original variable will still point to a null or empty object, hence last_price is null when you try to use it.

Fix: Make sure you initialize btcCurrent once (like in onCreate()) and only update its properties in dataGet(), not create a new object:

// 错误写法:重新赋值了新对象,原来的引用失效
private void dataGet() {
    // ❌ 不要这么做!
    btcCurrent = new BtcData();
    btcCurrent.last_price = fetchedPrice;
}

// 正确写法:更新已有对象的属性
private void dataGet() {
    // ✅ 用已经初始化好的btcCurrent
    btcCurrent.last_price = fetchedPrice;
}

3. You’re Trying to Update UI From a Background Thread

Android won’t let you update UI elements (like TextView) from a non-main thread. If dataGet() runs on a background thread and you try to set the TextView directly there, you might get an exception—or if you somehow bypass that, the data might not sync properly, leading to null values.

Fix: Always update UI from the main thread. As shown in the AsyncTask example above, onPostExecute() runs on the main thread. If you’re using other async methods, use runOnUiThread() to wrap your UI update code:

// 在后台线程里获取到数据后,切换到主线程更新UI
runOnUiThread(new Runnable() {
    @Override
    public void run() {
        priceTextView.setText(btcCurrent.last_price);
    }
});

Quick Checks to Rule Out Basics

  • Did you initialize btcCurrent before using it? If it’s never been set to new BtcData(), it’ll be null no matter what.
  • Double-check that your dataGet() method is actually successfully fetching the last_price value—add some log statements (like Log.d("BTC_PRICE", "Fetched price: " + fetchedPrice)) to confirm the data is coming through.

Hope this helps you get your BTC price showing up properly—happy coding!

内容的提问来源于stack exchange,提问作者Generilisk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:52:52