每件事似乎都很好我仍然无法在另一个类中创建一个新对象。我得到了"java.lang.Null.Pointer.Exception"
实际上我有一个用于制作F16飞机的F16级。现在当我尝试在MainActivity中创建一个新对象来显示飞机时,会显示此错误。
MainActivity Class
public class MainActivity extends Activity {
LinearLayout Map=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Map=(LinearLayout)findViewById(R.id.Map);
try{
F16 myF16=new F16();
myF16.CreateAirCraft(myF16.CoordinateX,myF16.CoordinateY, this, Map);
}
catch(Exception ex){
Log.d("Er", ex.toString());
}
}
F16班级
public class F16 extends AirCraft {
Context context;
private int Image=context.getResources().getIdentifier("F16" , "drawable", context.getPackageName());
LinearLayout PlaneBody=null;//a container used to hold All information of Aircraft
TextView PlaneName=null;// mentions to AirCraft name
ImageView PlaneImg=null;//mentions to AirCraft Image
public void CreateAirCraft(byte X , byte Y,Context Ctx,LinearLayout Map){
Name="F-16";
PlaneBody=new LinearLayout(Ctx);
PlaneName=new TextView(Ctx);
PlaneImg=new ImageView(Ctx);
PlaneName.setText(Name);
PlaneImg.setImageResource(Image);
PlaneBody.addView(PlaneName);
PlaneBody.addView(PlaneImg);
Map.addView(PlaneBody);
}
}
AirCraft Class
public abstract class AirCraft {
public String Name="";
public byte CoordinateX=0;
public byte CoordinateY=0;
public byte Weight=0;
}
答案 0 :(得分:2)
使用context作为参数在F16类中创建构造函数 例如
public F16(Context context)
{
Image=context.getResources().getIdentifier("F16" , "drawable", context.getPackageName());
}
并从主要活动传递上下文
F16 myF16=new F16(this);
答案 1 :(得分:1)
尝试以下代码。
public class F16 extends AirCraft {
Context context;
private int Image;
LinearLayout PlaneBody=null;//a container used to hold All information of Aircraft
TextView PlaneName=null;// mentions to AirCraft name
ImageView PlaneImg=null;//mentions to AirCraft Image
public F16(Context context)
{
this.context = context;
Image=context.getResources().getIdentifier("F16" , "drawable", context.getPackageName());
}
public void CreateAirCraft(byte X , byte Y,Context Ctx,LinearLayout Map){
Name="F-16";
PlaneBody=new LinearLayout(Ctx);
PlaneName=new TextView(Ctx);
PlaneImg=new ImageView(Ctx);
PlaneName.setText(Name);
PlaneImg.setImageResource(Image);
PlaneBody.addView(PlaneName);
PlaneBody.addView(PlaneImg);
Map.addView(PlaneBody);
}
}
答案 2 :(得分:0)
NullPointerException
由F16
类的第3行引起。
Context context;
private int Image=context.getResources().getIdentifier("F16" , "drawable", context.getPackageName());
字段context
已隐式初始化为null
。然后正在初始化Image
并调用context.getResources()
,但由于context
为空,因此您获得了NPE。