在我的XML文档中,我只有一个基本的textview,其ID为username。当我删除username.setText()时,程序运行正常。
这是我的代码:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
private ImageButton homeButton;
int totalTickets = 0;
public TextView showValue;
private MySqliteOpenHelper mySqliteOpenHelper;
private SQLiteDatabase mDatabase;
public String googleDisplayName;
private TextView username;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_menu);
navigationView.setNavigationItemSelectedListener(this);
showValue = (TextView) findViewById(R.id.ticketCounter);
username = (TextView) findViewById(R.id.username);
username.setText("Test");
不太确定问题是否与我的XML代码有关。我正在获得NPE,但我不确定如何解决该问题。我的textview(用户名)具有文本,因此不为null。也许我误会了一些东西,但我对android还是很陌生。
XML代码:
<RelativeLayout 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:layout_width="match_parent"
android:layout_height="176dp"
android:background="#414040"
android:gravity="bottom"
android:orientation="vertical"
android:theme="@style/ThemeOverlay.AppCompat.Dark"
tools:layout_editor_absoluteY="25dp">
<TextView
android:id="@+id/version_Number"
android:layout_width="178dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:text="@string/nav_header"
android:textSize="8sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="@+id/username"
app:layout_constraintTop_toBottomOf="@+id/username" />
<TextView
android:id="@+id/username"
android:layout_width="wrap_content"
android:layout_height="26dp"
android:layout_above="@+id/version_Number"
android:layout_alignParentStart="true"
android:text="user"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="@+id/version_Number"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/navButton" />