我在主要活动中有这个方法:
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();
}
}
方法被称为来自辅助类的回调(从Activity扩展)。
如果在方法中我试着打电话:
TextView eanTv = (TextView) findViewById(R.id.street);
我总是得到空指针异常,但是如果我尝试在这样的主要活动方法中调用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 ) ) ;
感谢您的任何建议和示例..
答案 0 :(得分:1)
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());
答案 1 :(得分:0)
在它工作的地方,你试着找到“R.id.state”,它不在哪里搜索“R.id.street”。你确定R.id.street是你布局的一部分吗?