我收到错误 变量可能已初始化 我正在使用onChildClickListener,这使我将变量声明为final。 我需要将我的变量放在try-Catch中,这就是我需要在外面声明变量的原因。
我无法确定如何声明变量以使此错误消失。有什么想法吗?
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_balance, container, false);
ExpandableListView expandableListView = (ExpandableListView)view.findViewById(R.id.fragBalance_expListView);
final ArrayList<Balance> arrayList;
try {
arrayList = (ArrayList<Balance>) new BalanceController(new BalanceFromApiJson()).getBalance(getContext(),"http://10.113.10.10:50591/api/Balance?reservationID=1452455");
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
BalanceAdapter balanceAdapter = new BalanceAdapter(getContext(),arrayList);
expandableListView.setAdapter(balanceAdapter);
expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
Toast.makeText(getContext(),arrayList.get(groupPosition).getTransactions().get(childPosition).toString() , Toast.LENGTH_SHORT).show();
return false;
}
});
return view;
}
答案 0 :(得分:0)
arrayList
期间抛出异常,则不会初始化 BalanceController
。
然后,您可以在try / catch块之后发出未初始化arrayList
的可能性。 Java和编译中不允许这样做。
如果程序的其余部分能够容忍null
arrayList
,那么最简单的方法是在arrayList = null
处理程序中写catch
保持final
(让我们使用多捕获语法来避免重复):
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
arrayList = null;
}
答案 1 :(得分:0)
感谢您的回答,但对我有用的解决方案是声明第二个相同类型的变量,添加我需要的操作,最后将对象复制到最终的ArrayList。
locOrientation