[英]Why are my TextViews null?
我想如果用戶輸入一個無效數字,則兩個TextView
應該更改其文本。
我抬頭檢查是否有多個具有相同ID的TextView
,結果是我的TextView
的每個ID都是唯一的。
每次我輸入無效數字來強行輸入錯誤時,我的應用就會崩潰。 如果我在調試中啟動應用程序並標記了我的兩個“問題代碼”。 結果是兩個TextView
都為null
。
我不知道為什么會這樣,因為ID是唯一的,而且我不會更改當前的布局。
我的Java代碼:
public void checkingInput(View view) {
TextView eKnowledge = (TextView) findViewById(R.id.enterKnowledge);
try{
int inputNumber = Integer.parseInt(eKnowledge.getText().toString());
_knowledge = KnowledgeLevel.fromUserInput(inputNumber);
test();
hideKeyboard(view);
} catch(NumberFormatException e){
errorKnowledge();
hideKeyboard(view);
}
}
@SuppressLint("SetTextI18n")
public void test() {
setContentView(R.layout.test);
TextView test = (TextView) findViewById(R.id.textView_nur_einmal_benutzt_hoff_ich);
switch(_knowledge) {
case NOOB:
test.setText("ENUM = NOOB");
break;
case BEGINNER:
test.setText("ENUM = BEGINNER");
break;
case ADVANCED:
test.setText("ENUM = ADV");
break;
case PRO:
test.setText("ENUM = PRO");
break;
case GRANDMASTER:
test.setText("ENUM = GM");
break;
case ERROR:
errorKnowledge();
break;
case FAIL:
test.setText("FEHLER!");
break;
}
}
@SuppressLint("SetTextI18n")
public void errorKnowledge(){
TextView hKnowledge = (TextView) findViewById(R.id.testWissenstandHeader);
TextView tKnowledge = (TextView) findViewById(R.id.testWissenstandText);
/* da ist der fehler ... einmal mit dem debugger durch zeigt es doch direkt: hKnowledge und tKnowledge sind null, daher die NullPointerException */
hKnowledge.getResources().getString(R.string.FehlerGefunden);
hKnowledge.getResources().getColor(android.R.color.holo_red_dark);
tKnowledge.getResources().getString(R.string.FehlerText1);
tKnowledge.getResources().getColor(android.R.color.holo_red_light);
}
private enum KnowledgeLevel {
FAIL, ERROR, NOOB, BEGINNER, ADVANCED, PRO, GRANDMASTER;
static KnowledgeLevel fromUserInput(final int input)
{
if (input >= 11 || input <= -1) {
return ERROR;
}
else if (input == 10) {
return GRANDMASTER;
}
else if (input >= 7) {
return PRO;
}
else if (input >= 4) {
return ADVANCED;
}
else if (input >= 1 ) {
return BEGINNER;
}
else if (input == 0) {
return NOOB;
}
return FAIL;
}
}
而我的XML:
<TextView
android:id="@+id/testWissenstandHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_marginTop="8dp"
android:text="Bla"
android:textAlignment="center"
android:textColor="#511613"
android:textSize="32sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="@+id/kastenKnowledge"
app:layout_constraintLeft_toLeftOf="@+id/kastenKnowledge"
app:layout_constraintRight_toRightOf="@+id/kastenKnowledge"
app:layout_constraintTop_toTopOf="@+id/kastenKnowledge"/>
<TextView
android:id="@+id/testWissenstandText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text='BlaBla'
android:textAlignment="center"
android:textColor="#E0E0E0"
android:textSize="20sp"
app:layout_constraintHorizontal_bias="0.512"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@+id/testWissenstandHeader"/>
我研究了一下,在stackoverflow.com上發現的唯一解決方案是我需要使用setContentView();
但是我有兩個問題:
1.如果不更改布局,為什么要使用它?
2.我嘗試過,但我的應用程序沒有崩潰,但我的文本沒有更改。 ( setContentView();
在使用setText();"
之前使用setText();"
)
這是我的整個錯誤報告(無調試問題):
08-10 00:14:53.580 2774-2774/com.example.alexander.hashtagnevereverbuggy E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.alexander.hashtagnevereverbuggy, PID: 2774
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.widget.TextView.getResources()' on a null object reference
at com.example.alexander.hashtagnevereverbuggy.MainActivity.errorKnowledge(MainActivity.java:112)
at com.example.alexander.hashtagnevereverbuggy.MainActivity.test(MainActivity.java:97)
at com.example.alexander.hashtagnevereverbuggy.MainActivity.checkingInput(MainActivity.java:68)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
編輯:
package com.example.alexander.hashtagnevereverbuggy;
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.HashMap;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import java.util.Map;
@SuppressWarnings("deprecation")
public class MainActivity extends AppCompatActivity implements Heroes {
private KnowledgeLevel _knowledge = KnowledgeLevel.NOOB;
private static FragmentManager _fragmentManager;
private enum WerteTextFelder {
TITLE,TYP, DAMAGE, LADUNG, KUGELN, NACHLADEDAUER, HEILUNG, HEADSHOT, WIRKUNGSDAUER, EXTRAEFFEKT, BESONDERHEIT
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, getString(R.string.AppID));
_fragmentManager = getFragmentManager();
Button testButtonAnfang = (Button) findViewById(R.id.AnfangsButton);
testButtonAnfang.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
setContentView(R.layout.testwissenstand);
}
});
}
@Override
public void onBackPressed() {
if(getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
}
super.onBackPressed();
}
public void checkingInput(View view) {
TextView eKnowledge = (TextView) findViewById(R.id.enterKnowledge);
try{
int inputNumber = Integer.parseInt(eKnowledge.getText().toString());
_knowledge = KnowledgeLevel.fromUserInput(inputNumber);
test();
hideKeyboard(view);
} catch(NumberFormatException e){
errorKnowledge();
hideKeyboard(view);
}
}
@SuppressLint("SetTextI18n")
public void test() {
setContentView(R.layout.test);
TextView test = (TextView) findViewById(R.id.textView_nur_einmal_benutzt_hoff_ich);
switch(_knowledge) {
case NOOB:
test.setText("ENUM = NOOB");
break;
case BEGINNER:
test.setText("ENUM = BEGINNER");
break;
case ADVANCED:
test.setText("ENUM = ADV");
break;
case PRO:
test.setText("ENUM = PRO");
break;
case GRANDMASTER:
test.setText("ENUM = GM");
break;
case ERROR:
errorKnowledge();
break;
case FAIL:
test.setText("FEHLER!");
break;
}
}
@SuppressLint("SetTextI18n")
public void errorKnowledge(){
TextView hKnowledge = (TextView) findViewById(R.id.testWissenstandHeader);
TextView tKnowledge = (TextView) findViewById(R.id.testWissenstandText);
/* da ist der fehler ... einmal mit dem debugger durch zeigt es doch direkt: hKnowledge und tKnowledge sind null, daher die NullPointerException */
hKnowledge.getResources().getString(R.string.FehlerGefunden);
hKnowledge.getResources().getColor(android.R.color.holo_red_dark);
tKnowledge.getResources().getString(R.string.FehlerText1);
tKnowledge.getResources().getColor(android.R.color.holo_red_light);
}
private enum KnowledgeLevel {
FAIL, ERROR, NOOB, BEGINNER, ADVANCED, PRO, GRANDMASTER;
static KnowledgeLevel fromUserInput(final int input)
{
if (input >= 11 || input <= -1) {
return ERROR;
}
else if (input == 10) {
return GRANDMASTER;
}
else if (input >= 7) {
return PRO;
}
else if (input >= 4) {
return ADVANCED;
}
else if (input >= 1 ) {
return BEGINNER;
}
else if (input == 0) {
return NOOB;
}
return FAIL;
}
}
public static void addTransaction(Fragment fragment, String tag){
if (_fragmentManager != null) {
FragmentTransaction fragmentTransaction = _fragmentManager.beginTransaction();
fragmentTransaction.add(fragment, tag);
fragmentTransaction.addToBackStack(tag);
fragmentTransaction.commit();
}
}
private void hideKeyboard(View view){
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
private class geileListener implements View.OnClickListener{
private Hero hero;
private geileListener (Hero hero) {
this.hero = hero;
}
@Override
public void onClick(View view) {
setContentView(hero.getHeroLayout());
}
}
private void advertisment() {
/*Notwendig um advertisment im showlock darzustellen*/
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}
public void showPreview (Hero hero) {
setContentView(hero.getPreviewLayout());
ImageButton button = (ImageButton) findViewById(R.id.imageButton_Preview);
button.setImageResource(hero.getPreviewImage());
button.setOnClickListener(new geileListener(hero));
advertisment();
}
private Map<WerteTextFelder, TextView> getWerteTextFelder() {
setContentView(R.layout.werte);
Map<WerteTextFelder, TextView> map = new HashMap<>();
TextView Titel = (TextView) findViewById(R.id.textView_Überschrift);
TextView Typ = (TextView) findViewById(R.id.textView_Werte_0);
TextView Damage = (TextView) findViewById(R.id.textView_Wert_1);
TextView Ladung = (TextView) findViewById(R.id.textView_Wert_2);
TextView Kugeln = (TextView) findViewById(R.id.textView_Wert_3);
TextView Nachladedauer = (TextView) findViewById(R.id.textView_Wert_4);
TextView Heilung = (TextView) findViewById(R.id.textView_Wert_5);
TextView Headshot = (TextView) findViewById(R.id.textView_Wert_6);
TextView Wirkungsdauer = (TextView) findViewById(R.id.textView_Wert_7);
TextView ExtraEffekt = (TextView) findViewById(R.id.textView_Wert_8);
TextView wert9 = (TextView) findViewById(R.id.textView_Wert_9);
map.put(WerteTextFelder.TITLE, Titel);
map.put(WerteTextFelder.TYP, Typ);
map.put(WerteTextFelder.DAMAGE, Damage);
map.put(WerteTextFelder.LADUNG, Ladung);
map.put(WerteTextFelder.KUGELN, Kugeln);
map.put(WerteTextFelder.NACHLADEDAUER, Nachladedauer);
map.put(WerteTextFelder.HEILUNG, Heilung);
map.put(WerteTextFelder.HEADSHOT, Headshot);
map.put(WerteTextFelder.WIRKUNGSDAUER, Wirkungsdauer);
map.put(WerteTextFelder.EXTRAEFFEKT, ExtraEffekt);
map.put(WerteTextFelder.BESONDERHEIT, wert9);
return map;
}
其他所有內容(4k代碼行)都非常重要
在onCreate()
,必須調用setContentView(R.layout.whateveryourxml)
。 之后,但仍然可以追溯到onCreate,可以調用errorKnowledge()
。 這應確保兩個TextView都不為null。
[編輯:我想弄清楚, 你必須的onCreate期間調用setContentView方法,或者你TextViews將解析為空。 假設您已完成操作(如您發布的代碼中所示),請繼續閱讀!]
這些代碼行對我來說似乎不正確。 他們看起來好像不會做任何事情:
hKnowledge.getResources().getString(R.string.FehlerGefunden);
hKnowledge.getResources().getColor(android.R.color.holo_red_dark);
tKnowledge.getResources().getString(R.string.FehlerText1);
tKnowledge.getResources().getColor(android.R.color.holo_red_light);
您沒有看到任何效果的原因是這些是返回某些值的get語句,但是實際上您沒有使用這些值做任何事情。
我覺得您實際上想說的是:
hKnowledge.setText(R.string.FehlerGefunden);
hKnowledge.setTextColor(android.R.color.holo_red_dark);
tKnowledge.setText(R.string.FehlerText1);
tKnowledge.setTextColor(android.R.color.holo_red_dark);
我還建議您花一些時間在onCreate方法中以完成所有findView的工作,這樣您就不必一遍又一遍地做。 (它也更清晰一些,為您節省了很多樣板java。)
您可以將各種TextView元素(等)定義為該類的私有成員,因此-例如,僅針對我們已經在討論的2個TextView:
private TextView hKnowledge;
private TextView tKnowledge;
...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hKnowledge = (TextView) findViewById(R.id.testWissenstandHeader);
tKnowledge = (TextView) findViewById(R.id.testWissenstandText);
...
}
完成此操作后,您可以從類中的其他任何地方引用兩個TextView,就像它們的成員一樣:hKnowledge和tKnowledge;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.