2014-10-12 4 views
1

У меня проблема, которую я не могу решить. Я объявляю и инициализирую несколько TextView. Но когда я помещаю свой фон в цвет, у меня есть исключение NullPointerException.Android - NullPointerException в TextView

Вот необходимый код:

public static ArrayList<Integer> questList = new ArrayList<Integer>(); 
public static ArrayList<TextView> scores = new ArrayList<TextView>(); 
public static int quest = 50, scoreIndex = 0; 
public boolean first = true, getIndex = false; 
public int corrects = 0, incorrects = 0, index = 0, indexCons = 0; 
public int correctButton = 0; 
public Button ans1, ans2, ans3, ans4; 
LinearLayout ln_an1, ln_an2, ln_an3, ln_an4; 
public TextView question; 
public TextView s1, s2, s3, s4, s5, s6, s7, s8, s9, s10; 
public TextView correctsText, correctsNum, incorrectsText, incorrectsNum; 
public String currentQuest; 
public Handler handler = new Handler(); 

@Override 
public void onBackPressed() {} 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    getWindow().requestFeature(Window.FEATURE_ACTION_BAR); 
    getActionBar().hide(); 
    setContentView(R.layout.container_layout); 


    if(savedInstanceState != null){} 

    scoreIndex = 0; 
    QES.createQuestions(); 
    AES.createAnswers(); 


    s1 = (TextView) findViewById(R.id.score1); 
    s2 = (TextView) findViewById(R.id.score2); 
    s3 = (TextView) findViewById(R.id.score3); 
    s4 = (TextView) findViewById(R.id.score4); 
    s5 = (TextView) findViewById(R.id.score5); 
    s6 = (TextView) findViewById(R.id.score6); 
    s7 = (TextView) findViewById(R.id.score7); 
    s8 = (TextView) findViewById(R.id.score8); 
    s9 = (TextView) findViewById(R.id.score9); 
    s10 = (TextView) findViewById(R.id.score10); 
    scores.add(s1);scores.add(s2);scores.add(s3);scores.add(s4); 
    scores.add(s5);scores.add(s6);scores.add(s7);scores.add(s8); 
    scores.add(s9);scores.add(s10); 

    s1.setBackgroundColor(Color.BLACK); 
    s2.setBackgroundColor(Color.BLACK); 
    s3.setBackgroundColor(Color.BLACK); 
    s4.setBackgroundColor(Color.BLACK); 
    s5.setBackgroundColor(Color.BLACK); 
    s6.setBackgroundColor(Color.BLACK); 
    s7.setBackgroundColor(Color.BLACK); 
    s8.setBackgroundColor(Color.BLACK); 
    s9.setBackgroundColor(Color.BLACK); 
    s10.setBackgroundColor(Color.BLACK); 

    if(findViewById(R.id.fragment_container) != null){ 

     if(savedInstanceState != null){ 
      return; 
     } 

     TenQuestions tq = new TenQuestions(); 

     tq.setArguments(getIntent().getExtras()); 

     getSupportFragmentManager().beginTransaction() 
      .add(R.id.fragment_container, tq).commit(); 

    }` 

У меня есть исключение на линии "s1.setBackgroundColor (Color.Black);"

EDIT: Вот container_layout.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:id="@+id/fragment_container" 
tools:context="com.panagetstudio.quiz.TenQuestionsGameActivity" > 

</FrameLayout> 

и вот часть макета с TextViews:

<LinearLayout 
     android:orientation="horizontal" 
     android:layout_width="0dp" 
     android:layout_weight="1" 
     android:layout_height="wrap_content" 
     android:padding="2dp" 
     android:background="@color/white"> 

     <TextView android:id="@+id/score1" 
      android:layout_width="match_parent" 
      android:textSize="12sp" 
      android:layout_height="wrap_content" 
      android:layout_gravity="center" 
      android:gravity="center"/> 

    </LinearLayout> 

(ПОВТОР 10 РАЗ)

+1

Опубликуйте свой 'container_layout.xml'. – Simas

+0

можете ли вы отправить container_layout? –

+0

очистите и создайте свой проект, также убедитесь, что макет, который вы используете в представлении заданного содержимого, должен иметь текстовое представление с идентификатором 1 и отправить свой xml, если он не решит вашу проблему. –

ответ

0

Попробуйте Инициализация TextViews в вашем Fragment по телефону rootView.findViewById(R.id.your_tv_id).

Например, в вашем Fragment:

public static class YourFragment extends Fragment { 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 

     // Inflate the layout for this fragment 
     View rootView = inflater.inflate(R.layout.example_fragment, container, false); 

     TextView s1 = (TextView) rootView.findViewById(R.id.score1); 

     s1.setBackgroundColor(Color.BLACK); 
    } 
} 

Это возвращение null прямо сейчас, потому что эти TextView объекты не находятся в вашем container_layout.xml, что для Activity, а не ваш Fragment.

+0

Я только что попробовал, похоже, что это не решение –

+0

Можете ли вы разместить то, что выглядит ваш «Фрагмент» и каков ваш макет вашего «Фрагмента»? – ujvl

+0

У моего фрагмента есть только метод setContentView(), не более того, и соответствующий макет моего фрагмента является частью кода, который я редактировал в ответе. Раньше это работало, но я не знаю, почему это исключает меня, я расстроен. –

Смежные вопросы