gpt4 book ai didi

java - Android-由于 java.lang.NullPointerException 无法显示收到的位置值

转载 作者:行者123 更新时间:2023-12-01 17:50:51 30 4
gpt4 key购买 nike

我正在尝试创建一个布局,在 TextView 中显示收到的位置更新,但我不断收到此错误,我做错了什么?

我们将不胜感激,提前致谢!

错误如下:

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.defro.app, PID: 7731 java.lang.NullPointerException: Attempt to invoke virtual >method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null >object reference at com.example.defro.app.MainActivity$1.onLocationChanged(MainActivity.java:29)`

第 29 行是:

txtLoc.setText(String.valueOf(iaLocation.getLongitude() + ", " + iaLocation.getLatitude()));

Main_Activity:

public class MainActivity extends AppCompatActivity {

IALocationManager mLocationManager;
IALocationListener mLocationListener = new IALocationListener() {
@Override
public void onLocationChanged(IALocation iaLocation) {
TextView txtLoc = (TextView) findViewById(R.id.textView);
txtLoc.setText(String.valueOf(iaLocation.getLongitude() + ", " + iaLocation.getLatitude()));

}

@Override
public void onStatusChanged(String s, int i, Bundle bundle) {

}

};
private final int CODE_PERMISSIONS = 1;

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

mLocationManager = IALocationManager.create(this);


String[] neededPermissions = {
Manifest.permission.CHANGE_WIFI_STATE,
Manifest.permission.ACCESS_WIFI_STATE,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN



};
ActivityCompat.requestPermissions(this, neededPermissions, CODE_PERMISSIONS);


}
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);

//Handle if any of the permissions are denied, in grantResults
}


protected void onResume() {
super.onResume();
mLocationManager.requestLocationUpdates(IALocationRequest.create(), mLocationListener);

}

protected void onPause() {
mLocationManager.removeLocationUpdates(mLocationListener);
super.onPause();
}

protected void onDestroy() {

mLocationManager.destroy();
super.onDestroy();
}

}

content_main.xml:

<TextView
android:layout_width="wrap_content"
android:layout_height="23dp"
android:text="Lat, Long"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.051"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.032" />

最佳答案

将此行写入 onCreate 方法

TextView txtLoc = (TextView) findViewById(R.id.textView);

给TextView添加id

android:id="@+id/textView"

关于java - Android-由于 java.lang.NullPointerException 无法显示收到的位置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50338021/

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