gpt4 book ai didi

android - 创建 GoogleApiClient 实例时出现 NullPointerException

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:51:50 26 4
gpt4 key购买 nike

我已经开始为 Android Wear 创建 Watch Face。我已经实现了几乎所有的东西,现在我想在脸上展示手机电池。根据我研究后的理解,这只能通过消息或数据层 API 来实现。所以我开始在他的领域工作,但一开始我就遇到了问题。我无法连接到 Google Api 客户端。

我在“磨损”下有两个类 - 一个是 watch (服务)的通用类,另一个是我创建的:

public class BatteryActivity extends Activity {

GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks( new ConnectionCallbacks() {
@Override
public void onConnected(Bundle connectionHint) {
Log.i( "", "onConnected: " + connectionHint);
// Now you can use the Data Layer API
}
@Override
public void onConnectionSuspended(int cause) {
Log.i( "", "onConnectionSuspended: " + cause);
}
})
.addOnConnectionFailedListener( new OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.i( "", "onConnectionFailed: " + result);
}
})
// Request access only to the Wearable API
.addApi(Wearable.API)
.build();
}

当我简单地像这样实例化它时:BatteryActivity batteryActivity = new BatteryActivity();我收到此错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Looper android.content.Context.getMainLooper()' on a null object reference

如果我实例化了,我不明白 mGoogleApiClient 为何为空。请注意 - 这完全基于此处的谷歌文档 - https://developer.android.com/training/wearables/data-layer/messages.html

最佳答案

我想您应该在 onCreate 方法上构建 GoogleApiClient。你的代码应该是这样的:

public class BatteryActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);

GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks( new ConnectionCallbacks() {
@Override
public void onConnected(Bundle connectionHint) {
Log.i( "", "onConnected: " + connectionHint);
// Now you can use the Data Layer API
}
@Override
public void onConnectionSuspended(int cause) {
Log.i( "", "onConnectionSuspended: " + cause);
}
})
.addOnConnectionFailedListener( new OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.i( "", "onConnectionFailed: " + result);
}
})
// Request access only to the Wearable API
.addApi(Wearable.API)
.build();
}
}

关于android - 创建 GoogleApiClient 实例时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29481292/

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