Java 如果从帮助器类调用,则活动方法中的Android findViewById不起作用
我在主要活动中有此方法:Java 如果从帮助器类调用,则活动方法中的Android findViewById不起作用,java,android,nullpointerexception,textview,Java,Android,Nullpointerexception,Textview,我在主要活动中有此方法: public void setPositionToView (Context ctx, List<Address> addresses) { try { String street = addresses.get(0).getAddressLine(0); String city = addresses.get(0).getAddressLine(1); String country = addresses.get(
public void setPositionToView (Context ctx, List<Address> addresses) {
try {
String street = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getAddressLine(1);
String country = addresses.get(0).getAddressLine(2);
Log.i(AppHelper.APP_LOG_NAMESPACE, street);
// display toast message with success state
Toast.makeText(ctx, "TEST", Toast.LENGTH_LONG).show();
// change state text to success and colorize text green
TextView eanTv = (TextView) findViewById(R.id.street);
eanTv.setText("Test");
//stateTv.setTextColor(getResources().getColor(R.color.green));
} catch (Exception e) {
Log.e(AppHelper.APP_LOG_NAMESPACE, "getAndSavePosition method cannot be processed", e);
e.printStackTrace();
}
}
我得到的总是空指针异常,但如果我尝试像这样从主活动方法中的onCreate方法调用,是否一切正常:
public void colorizeIt () {
try {
TextView stateTv = (TextView) findViewById(R.id.state);
stateTv.setText("This is O.K");
} catch (Exception e) {
Log.e(AppHelper.APP_LOG_NAMESPACE, "getAndSavePosition method cannot be processed", e);
e.printStackTrace();
}
}
我试图找到一些解决方案,但没有运气,我应该创建一些布局,视图实例或类似下面的例子
LayoutInflater in = getLayoutInflater() ;
View layout = in.inflate(R.layout.toast_layout, (ViewGroup) findViewById ( R.id.toast_layout_root ) ) ;
谢谢你的建议和例子
public void setPositionToView (Context ctx, List addresses,View mainview) { try {
String street = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getAddressLine(1);
String country = addresses.get(0).getAddressLine(2);
Log.i(AppHelper.APP_LOG_NAMESPACE, street);
// display toast message with success state
Toast.makeText(ctx, "TEST", Toast.LENGTH_LONG).show();
// change state text to success and colorize text green
TextView eanTv = (TextView) mainview.findViewById(R.id.street);
eanTv.setText("Test");
//stateTv.setTextColor(getResources().getColor(R.color.green));
} catch (Exception e) {
Log.e(AppHelper.APP_LOG_NAMESPACE, "getAndSavePosition method cannot be processed", e);
e.printStackTrace();
}
}
像这样打电话
setPositionToView (ctx, addresses,(ViewGroup)view.getParent());
在它工作的地方,你试图找到“R.id.state”,在它不工作的地方,你搜索“R.id.street”。你确定R.id.street是你布局的一部分吗 是的,示例中的ID是不同的,但每个ID都包含在布局中。我不能在helper类中使用(ViewGroup)view.getParent(),还有其他方法吗,很热吗?plz为我提供活动和helper类,所以我了解PLZZ,所以我尝试了它,但它不是最佳解决方案,通过3个方法传递参数。但是谢谢你的帮助。
setPositionToView (ctx, addresses,(ViewGroup)view.getParent());