[英]Null Pointer Exception textview
setText(java.lang.CharSquence)中的空對象引用中存在空指針異常,idk為什么? textview電視正在另一個活動中,也許這就是重點嗎?
Intent intent = new Intent(this, DisplayResultActivit.class);
EditText edittext = findViewById(R.id.liczba);
EditText edittext2 = findViewById(R.id.liczba2);
int wpis2 = Integer.valueOf(edittext2.getText().toString());
int wpis = Integer.valueOf(edittext.getText().toString());
int suma = wpis + wpis2;
TextView tv = findViewById(R.id.result);
tv.setText(String.valueOf(suma));
startActivity(intent);
的確,如果嘗試從findViewById中找到對象(如果未找到),則將獲得NullPointerException。
我假設,您嘗試在嘗試重定向到的“活動”視圖上填充TextField? 在這種情況下,您可以向該意圖添加其他對象,該對象將從第二個活動中讀出。
在第一個活動上嘗試:
intent.putExtra("myText", String.valueOf(suma));
startActivity(intent);
在第二個活動onCreate上嘗試:
Intent incomingIntent = getIntent();
if (incomingIntent.hasExtra("myText")) {
TextView tv = findViewById(R.id.result);
tv.setText(incomingIntent.getStringExtra("myText");
}
空對象引用上的setText(java.lang.CharSquence)中的Null Pointer Exception
TextView tv = findViewById(R.id.result);
tv.setText(String.valueOf(suma));
作為例外,上面的代碼表明在您的rootview樹中找不到電視。 因此,您必須在此活動的contentView(布局xml文件)中添加TextView id為“ result”。
您無法直接訪問其他活動的textView,您必須在啟動活動時傳遞意圖,然后在創建活動時按ID查找TextView,然后從上一個活動傳遞getIntent並將其設置為文本視圖。
首先,當您創建意圖時傳遞活動值
EditText edittext = findViewById(R.id.liczba);
EditText edittext2 = findViewById(R.id.liczba2);
int wpis2 = Integer.valueOf(edittext2.getText().toString());
int wpis = Integer.valueOf(edittext.getText().toString());
int suma = wpis + wpis2;
Intent intent = new Intent(this, DisplayResultActivit.class);
intent.putExtra("suma", suma);
startActivity(intent);
然后在DisplayResultActivit中
Intent intent= getIntent();
TextView tv = findViewById(R.id.result);
if (getIntent().getExtras() != null) {
int suma = getIntent().getIntExtra("suma",0);
tv.setText(String.valueOf(suma));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.