2017-08-10 65 views
0

我想要如果用戶輸入一個無效的數字,兩個TextView s應該改變他們的文本。
我擡起頭,檢查是否有一個以上的TextView帶有相同的ID,而且我的TextView中的每個ID都是唯一的。爲什麼我的TextViews爲空?

每當我輸入一個無效數字強制我的錯誤我的應用程序崩潰。如果我在調試中啓動應用程序並標記我的兩個「有問題的代碼」。結果是TextView s是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.爲什麼我應該使用,如果我不chnage我的佈局?
2.我試了一下,我的應用程序沒有崩潰,但我的文本沒有改變。 (setContentView();setText();"之前使用的,使用)

這裏是我的整個errorreport(沒有調試prozess):

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; 
} 

其他一切(abput的代碼4K行)的arent重要

+0

你能發佈全班嗎?我想知道何時調用errorKnowledge方法,以及是否已經在onCreate方法中運行了setContentView。 – instantiator

+0

來自您的日誌它說你在「onClick」有問題 – Salman500

+0

@instantiator我更新了我的代碼。你去 – user8442416

回答

0

在您的onCreate(),您必須致電setContentView(R.layout.whateveryourxml)。之後,但仍然可以追溯到您的onCreate,您可以撥打errorKnowledge()。這應該確保TextView都不爲null。

+0

我更新了我的問題,我認爲我不需要在我的'onCreate();'方法中做某事。 – user8442416

0

[編輯:只是澄清,你必須在onCreate期間調用setContentView方法,否則你的TextViews將解析爲null。假設你已經這麼做了 - 就像你發佈的代碼一樣 - 請繼續閱讀!]

這些代碼行對我來說似乎不太合適。他們不看,如果他們會做任何事情:

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); 

你看到沒有效果的原因是,這些都是得到返回一些值語句,但你實際上並不使用這些值來什麼都做

我覺得你真正想說的是:

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個TextViews我們已經談論:

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); 
    ... 
} 

已經做到了這一點,那麼你可以參考兩個TextViews從其他地方在您的就像他們的成員一樣:知識和知識;

+0

編輯問題:我的「開始」佈局是「activity_main」,並有一個按鈕將contentView更改爲「testwissenstand」。那麼爲什麼我需要在我的'onCreate'方法中做到這一點? 如果我使用多個'setContentView',我認爲它只會使用最後一個 – user8442416

+0

這可能是我想的,儘管似乎動態改變佈局的推薦方法是使用Fragments。碎片有複雜的生命週期,但我建議讀一讀它們。 您可以自己手動充氣視圖,然後在適當的視圖上設置各種按鈕等。如果你創建一個視圖'view1 = getLayoutInflater()。inflate(R.layout.layout1,null);'那麼你可以像這樣找到你的按鈕'button1 = view1.findViewById(R.id.button_1);'和那麼你可以按照你的喜好'setContentView(view1);'(或任何其他視圖)。 – instantiator