調試時出現錯誤,我不知道爲什麼。嘗試在com.comp.Project上的空對象引用上調用虛擬方法'...'
錯誤:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void layout.CardFragment.setCard(com.mycomp.MyCards.Card)' on a null object reference at com.mycomp.MyCards.MainActivity.onCreate(MainActivity.java:16)
我認爲這是說,我試圖通過進入cardFragment.setCard(Card card)
的Card
對象爲null。我已經檢查過,它不是空的。
MainActivity.java
1 package com.mycomp.MyCards;
2
3 import android.support.v7.app.AppCompatActivity;
4 import android.os.Bundle;
5
6 public class MainActivity extends AppCompatActivity {
7 public Card cardApples;
8 public CardFragment cardFragment = (CardFragment)
9 getSupportFragmentManager().findFragmentById(R.id.frgCard);
10
11 @Override
12 protected void onCreate(Bundle savedInstanceState) {
13 super.onCreate(savedInstanceState);
14 setContentView(R.layout.activity_main);
15 createDummyCards();
16 ---> cardFragment.setCard(cardApples);
17 }
18
19 public void createDummyCards() {
20 cardApples = new Card(new SideText("Apple"), new SideText("Red"));
21 }
22 }
Card.java
package com.mycomp.MyCards;
public class Card {
public Side[] sides;
public Card(Side...sides) {
this.sides = sides;
}
}
Side.java
package com.mycomp.MyCards;
public class Side {}
SideText.java
package com.mycomp.MyCards;
public class SideText extends Side{
public String text;
public SideText(String text) {
this.text = text;
}
}
CardFragment.java
package com.midassoft.testingerror;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class CardFragment extends Fragment {
private Card card;
private int sideIndex;
private static TextView lblText;
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_card, container, false);
lblText = (TextView) view.findViewById(R.id.lblText);
return view;
}
public void setCard(Card card) {
this.card = card;
sideIndex = 0;
showSide();
}
private void showSide() {
Side side = card.sides[sideIndex];
switch (side.getClass().getName()) {
case "SideText":
lblText.setText(((SideText) side).text);
break;
case "SideMultipleChoice":
///do stuff
break;
case "SideTrueFalse":
///do stuff
break;
default: break;
}
}
}
您試圖連接視圖之前得到片段的對象,這就是爲什麼它沒有找到視圖'id',給你一個空目的。 –