0

次のコードでは、Null Pointer Exception エラーが発生します。しかし、View を使用しないと、ボタンを非表示にせずに適切な出力が得られます (無効にするだけです)。私の xml ファイルは次のとおりです。

 <Button
    android:id="@+id/button1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/start_track"
    android:onClick="start"
    android:textAppearance="?android:attr/textAppearanceLarge" />

<Button
    android:id="@+id/button2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/stop_track"
    android:onClick="stop" 

    android:textAppearance="?android:attr/textAppearanceLarge"/>

私のアクティビティコードは次のとおりです。

public void start(View v1)
{

    schedular = Executors.newSingleThreadScheduledExecutor();

    Toast.makeText(WelcomeActivity.this, "Tracking Started", Toast.LENGTH_SHORT).show();
    updateLocation();

    findViewById(R.id.button1).setEnabled(false);
    findViewById(R.id.button2).setEnabled(true);

    findViewById(R.id.button1).setVisibility(View.INVISIBLE);
    findViewById(R.id.button2).setVisibility(View.VISIBLE);


}

public void stop(View v2)
{

    Toast.makeText(WelcomeActivity.this, "Tracking Stopped", Toast.LENGTH_SHORT).show();
    schedular.shutdown();

    findViewById(R.id.button1).setEnabled(true);
    findViewById(R.id.button2).setEnabled(false);   

    findViewById(R.id.button1).setVisibility(View.VISIBLE);
    findViewById(R.id.button2).setVisibility(View.INVISIBLE);
}

親切に私を助けてください。無効にするコード行を削除してこのコードを試しましたが、それでも Null Pointer Exception エラーが発生します。

4

1 に答える 1

0

1 つのボタンを使用して、クリック時にテキストを変更することもできます。

<Button
    android:id="@+id/button1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/start_track"
    android:onClick="doSth"
    android:textAppearance="?android:attr/textAppearanceLarge" />

private boolean clicked = false;

public void doSth(View v1)
{
    if(clicked) {

        Toast.makeText(WelcomeActivity.this, "Tracking Stopped", Toast.LENGTH_SHORT).show();
        schedular.shutdown();

        findViewById(R.id.button1).setText("Start tracking");

        clicked = false;
    } else {

        schedular = Executors.newSingleThreadScheduledExecutor();

        Toast.makeText(WelcomeActivity.this, "Tracking Started",  Toast.LENGTH_SHORT).show();
        updateLocation();

        findViewById(R.id.button1).setText("Stop tracking");

    }
}
于 2013-09-17T13:48:24.993 に答える