簡體   English   中英

Android Wear附加到textView崩潰的應用程序

[英]Android Wear append to textView crashes app

因此,當嘗試在我的應用程序上檢索傳感器列表時,我遇到了一個奇怪的問題。

打印到日志工作正常。

當我嘗試追加到textView時,它崩潰了。

這是我嘗試添加的地方:

protected void onCreate(Bundle b) {
    super.onCreate(b);
    setContentView(R.layout.activity_main);

    sensorTextView = (TextView) findViewById(R.id.sensorList);

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    initialiseAccelerometer();

    sensorManager=(SensorManager) getSystemService(SENSOR_SERVICE);
    List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
    for (Sensor sensor : sensors) {
        Log.d("Sensors", "" + sensor.getName());
        sensorTextView.append(sensor.getName());
    }

    sensorManager.registerListener(
                               this,
                               sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                               SensorManager.SENSOR_DELAY_NORMAL);
    mGestureDetector = new GestureDetectorCompat(this, new LongPressListener());
}

以及隨后的錯誤:

java.lang.RuntimeException: Unable to start activity     
ComponentInfo{com.example.XXXXXX.XXXXXXXXXXX.MainActivity}: 
java.lang.NullPointerException: 
Attempt to invoke virtual method 
'void android.widget.TextView.append(java.lang.CharSequence)' on a null object reference

以及具有正確ID的XML文件:

android:id="@+id/sensorList"

誰能指出我的正確方向或就我做錯了事向我提出建議?

activity_main.xml中:

<android.support.wearable.view.WatchViewStub
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/watch_view_stub"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:rectLayout="@layout/rect_activity_main"
app:roundLayout="@layout/round_activity_main"
tools:context=".MainActivity"
tools:deviceIds="wear"></android.support.wearable.view.WatchViewStub>

謝謝,埃米特

文檔的此部分說明了WatchViewStub一些怪癖。 特別要注意以下幾點:

在WatchViewStub檢測到屏幕形狀之前,您為方形或圓形屏幕指定的布局不會膨脹,因此您的應用程序無法立即訪問其視圖。 要訪問這些視圖,請在活動中設置一個偵聽器,以在特定形狀的布局膨脹后得到通知

您可能試圖過早設置TextView引用,這就是為什么在嘗試添加文本時它為null的原因。 如果改為使用下面的示例代碼(同樣來自文檔)中的OnLayoutInflatedListener來等待,直到適當的圓形/方形布局被OnLayoutInflatedListener為止,您應該發現兩種屏幕類型的引用均已正確初始化:

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

    WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
    stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
        @Override public void onLayoutInflated(WatchViewStub stub) {
            // Now you can access your views
            TextView tv = (TextView) stub.findViewById(R.id.text);
            ...
        }
    });
}

[請注意,我的一位同事指出,當前存在一個錯誤,要求您以特定的順序定義方形布局xml屬性和圓形布局xml屬性,這樣才能正常工作-我不記得要臨時使用首先,如果遇到問題,請單挑]。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM